How the OpenAI Batch API Works for High-Volume Classification
The OpenAI Batch API processes asynchronous request files at a 50% cost discount on input and output tokens compared to synchronous calls, with a target completion window of up to 24 hours (often completing much faster) and separate batch queue capacity.
A single batch input file supports up to 50,000 requests and up to 200 MB, making it a direct fit for a 50,000-prompt classification job:
- Unique
custom_idper line: Because responses arrive out of order in an output JSONL file, every line needs a uniquecustom_id(such as your database row ID) so you can join results back to each classification item. - One JSON object per line (JSONL): Each line specifies
custom_id,method: "POST",url(such as"/v1/chat/completions"or"/v1/responses"), andbodycontaining the standard request parameters. - Separate output and error files: When the batch finishes, successful responses are written to
output_file_idand per-request failures are written toerror_file_id.
Steps to Run a 50,000-Prompt Batch Job
- Generate the JSONL input file: Write 50,000 lines—each a valid single-line JSON object with a unique
custom_idand your classification prompt/schema. - Upload with
purpose: "batch": Upload the.jsonlfile via the Files API (client.files.create). - Create the batch job: Call
client.batches.createwithinput_file_id,endpoint: "/v1/chat/completions", andcompletion_window: "24h". - Poll until terminal status: Check
client.batches.retrieve(batch.id)periodically untilstatusis"completed"(or"failed","expired","cancelled"). - Download and reconcile results: Stream/read
output_file_id(anderror_file_idif present), match each record bycustom_id, and re-queue any individual failed items.
Python Example: Build, Submit, Poll, and Parse 50,000 Prompts
import json
import time
from pathlib import Path
from openai import OpenAI
client = OpenAI()
def build_classification_jsonl(items: list[dict], jsonl_path: Path, model: str = "gpt-4o-mini") -> None:
"""Write up to 50,000 classification requests into a JSONL file."""
with jsonl_path.open("w", encoding="utf-8") as f:
for item in items:
record = {
"custom_id": str(item["id"]),
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": model,
"temperature": 0,
"messages": [
{
"role": "system",
"content": "Classify the text into one label: billing, bug, feature_request, or other. Reply with the label only.",
},
{
"role": "user",
"content": item["text"],
},
],
},
}
f.write(json.dumps(record, ensure_ascii=False) + "\n")
def run_classification_batch(jsonl_path: Path, poll_interval_sec: int = 30) -> dict[str, str]:
# 1. Upload JSONL file with purpose="batch"
with jsonl_path.open("rb") as file_obj:
input_file = client.files.create(file=file_obj, purpose="batch")
# 2. Create the batch job (24h completion window)
batch = client.batches.create(
input_file_id=input_file.id,
endpoint="/v1/chat/completions",
completion_window="24h",
)
# 3. Poll until finished
terminal_statuses = {"completed", "failed", "expired", "cancelled"}
while batch.status not in terminal_statuses:
time.sleep(poll_interval_sec)
batch = client.batches.retrieve(batch.id)
print(
f"Batch {batch.id} status={batch.status} "
f"completed={batch.request_counts.completed}/{batch.request_counts.total}"
)
if batch.status != "completed" or not batch.output_file_id:
raise RuntimeError(f"Batch did not complete cleanly. Status: {batch.status}")
# 4. Download and parse output lines keyed by custom_id
results: dict[str, str] = {}
content = client.files.content(batch.output_file_id).text
for line in content.splitlines():
if not line.strip():
continue
row = json.loads(line)
custom_id = row["custom_id"]
resp = row.get("response", {})
if resp.get("status_code") == 200:
label = resp["body"]["choices"][0]["message"]["content"].strip()
results[custom_id] = label
# Optional: inspect error_file_id if any individual requests errored
if batch.error_file_id:
error_text = client.files.content(batch.error_file_id).text
print("Error file entries:", len(error_text.splitlines()))
return results
if __name__ == "__main__":
sample_items = [{"id": f"ticket-{i}", "text": f"Sample support message {i}"} for i in range(50_000)]
input_path = Path("classification_batch.jsonl")
build_classification_jsonl(sample_items, input_path)
classifications = run_classification_batch(input_path)
print("Classified count:", len(classifications))
Helpful Tips for 50,000-Item Batches
- Watch the 50,000-request and 200 MB ceilings: Keep each JSONL file at or below 50,000 lines and 200 MB—if your prompts are long and approach 200 MB, split into two smaller batches.
- Check enqueued token limits: Large batches also count against per-model batch queue token limits; if a huge batch hits queue caps, split into sequential chunks.
- Never assume line order matches input order: Always join outputs using
custom_idrather than array index, and persistbatch.idin your database/job state so your worker can resume polling across restarts.
You must log in or register to comment.
