bagaco3 / classifier /scripts /process_openrouter.py
duarteocarmo
update
880db5d
Raw History Blame Contribute Delete
6.77 kB
"""Submit and retrieve OpenRouter batch jobs."""
import argparse
import json
import os
import urllib.error
import urllib.request
from pathlib import Path
BATCHES_URL = "https://openrouter.ai/api/beta/batches"
MAX_REQUESTS_PER_BATCH = 5_000
TERMINAL_STATUSES = {"completed", "failed", "expired", "cancelled"}
def openrouter_api_key() -> str:
"""Return the configured OpenRouter API key."""
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
raise RuntimeError("Set OPENROUTER_API_KEY before submitting or monitoring a batch.")
return api_key
def send_request(
url: str, method: str, api_key: str, payload: dict | None = None
) -> dict:
"""Send an authenticated JSON request to OpenRouter."""
data = json.dumps(payload).encode() if payload is not None else None
request = urllib.request.Request(
url=url,
data=data,
headers={
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
},
method=method,
)
try:
with urllib.request.urlopen(request) as response:
return json.load(response)
except urllib.error.HTTPError as error:
details = error.read().decode()
raise RuntimeError(f"OpenRouter returned HTTP {error.code}: {details}") from error
def batch_requests(
input_file: Path,
max_tokens: int,
reasoning_effort: str | None,
start_row: int,
end_row: int | None,
) -> list[dict]:
"""Convert prompt rows into chat-completion batch requests."""
requests = []
with input_file.open(encoding="utf-8") as file:
for line_number, line in enumerate(file):
if line_number < start_row:
continue
if end_row is not None and line_number >= end_row:
break
row = json.loads(line)
body = {
"messages": [{"role": "user", "content": row["prompt"]}],
"max_tokens": max_tokens,
"response_format": {"type": "json_object"},
}
if reasoning_effort:
body["reasoning"] = {"effort": reasoning_effort}
requests.append(
{
"custom_id": row.get("custom_id", f"row-{line_number:06d}"),
"body": body,
}
)
if not requests:
raise ValueError(f"{input_file} contains no requests.")
return requests
def submit_batch(arguments: argparse.Namespace) -> None:
"""Split a JSONL file into OpenRouter batch jobs and submit them."""
if arguments.start_row < 0:
raise ValueError("--start-row must be zero or greater.")
if arguments.end_row is not None and arguments.end_row <= arguments.start_row:
raise ValueError("--end-row must be greater than --start-row.")
requests = batch_requests(
input_file=arguments.input_file,
max_tokens=arguments.max_tokens,
reasoning_effort=arguments.reasoning_effort,
start_row=arguments.start_row,
end_row=arguments.end_row,
)
manifest_file = arguments.manifest_file or arguments.input_file.with_suffix(
".batches.json"
)
submitted_batches = []
for start in range(0, len(requests), MAX_REQUESTS_PER_BATCH):
request_batch = requests[start : start + MAX_REQUESTS_PER_BATCH]
payload = {
"endpoint": "/v1/chat/completions",
"model": arguments.model,
"requests": request_batch,
}
batch = send_request(
url=BATCHES_URL,
method="POST",
api_key=openrouter_api_key(),
payload=payload,
)
submitted_batches.append({"id": batch["id"], "requests": len(request_batch)})
manifest_file.write_text(
json.dumps(
{
"model": arguments.model,
"input_file": str(arguments.input_file),
"start_row": arguments.start_row,
"end_row": arguments.end_row,
"batches": submitted_batches,
},
indent=2,
)
+ "\n",
encoding="utf-8",
)
print(f"Submitted {len(request_batch):,} requests: {batch['id']}")
print(f"Status: {batch['status']}")
print(f"Saved batch IDs to {manifest_file}")
def monitor_batch(arguments: argparse.Namespace) -> None:
"""Print batch status and save completed results."""
batch = send_request(
url=f"{BATCHES_URL}/{arguments.batch_id}",
method="GET",
api_key=openrouter_api_key(),
)
print(f"Status: {batch['status']}")
print(json.dumps(batch["request_counts"], indent=2))
if batch["status"] not in TERMINAL_STATUSES:
return
if batch["status"] != "completed":
return
output_file = arguments.output_file or Path(f"{arguments.batch_id}.jsonl")
with output_file.open(mode="w", encoding="utf-8") as file:
for result in batch["results"]:
file.write(json.dumps(result, ensure_ascii=False) + "\n")
print(f"Saved {len(batch['results']):,} results to {output_file}")
def parse_arguments() -> argparse.Namespace:
"""Parse submit and monitor command-line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
commands = parser.add_subparsers(dest="command", required=True)
submit = commands.add_parser(
name="submit", help="Submit a JSONL prompt file as a batch job."
)
submit.add_argument("input_file", type=Path)
submit.add_argument("--model", required=True, help="OpenRouter model slug.")
submit.add_argument("--max-tokens", type=int, default=256)
submit.add_argument("--manifest-file", type=Path)
submit.add_argument(
"--start-row",
type=int,
default=0,
help="Skip input rows before this zero-based row number.",
)
submit.add_argument(
"--end-row",
type=int,
help="Stop before this zero-based row number.",
)
submit.add_argument(
"--reasoning-effort",
choices=("none", "low", "medium", "high"),
help="OpenRouter reasoning effort; omit to use the model default.",
)
submit.set_defaults(handler=submit_batch)
monitor = commands.add_parser(
name="monitor", help="Check a batch and save completed results."
)
monitor.add_argument("batch_id")
monitor.add_argument("--output-file", type=Path)
monitor.set_defaults(handler=monitor_batch)
return parser.parse_args()
def main() -> None:
"""Run the selected batch command."""
arguments = parse_arguments()
arguments.handler(arguments)
if __name__ == "__main__":
main()