Datasets:
File size: 6,769 Bytes
21cb70f 880db5d 21cb70f | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | """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()
|