Sub topic 12
Batch non-urgent work
This chapter assumes you can call an LLM API from Python and know how tokens map to price, as covered in the earlier chapters. Batch processing trades speed for lower cost. It suits work that nobody is waiting on.
What batch processing is
A batch job is a set of requests you submit together and collect later. Many providers offer a batch API. You upload a file of requests, the provider processes them within a time window (often up to 24 hours), and you download the results. In exchange for the delay, providers commonly charge a discount on token prices. The size of the discount and the window vary, so check your provider's current terms.
Batch work gets this discount because the provider can run it when capacity is free. You give up control over when each request finishes.
When batching fits
Good candidates share one trait: no user is waiting.
- Classifying or tagging a backlog of documents.
- Generating embeddings or summaries for a search index.
- Running your evaluation set against a new model or prompt.
- Nightly reports and data enrichment.
Poor candidates are chat replies, autocomplete, and anything interactive. Those need low time to first token, which a batch window cannot give you.
The usual workflow
Provider APIs differ in detail, but the steps are the same.
- Give each request a unique ID of your own, such as
doc-1042. - Write all requests to a file, one JSON object per line (JSONL).
- Upload the file and create the batch job.
- Poll the job status, or check it on a schedule.
- Download the results and match them to inputs by ID.
Step 5 matters. Results usually do not come back in input order, so never rely on position.
The sketch below prepares the input file and joins results by ID. The request body shape is illustrative. Use the format your provider documents.
import json
def write_batch_file(path, model, prompts):
"""Write one request per line, each with a custom ID."""
with open(path, "w", encoding="utf-8") as f:
for i, prompt in enumerate(prompts):
request = {
"custom_id": f"item-{i}",
"body": {
"model": model,
"messages": [{"role": "user", "content": prompt}],
"max_tokens": 200,
},
}
f.write(json.dumps(request) + "\n")
def read_results(path):
"""Return a dict mapping custom_id to its result line."""
results = {}
with open(path, encoding="utf-8") as f:
for line in f:
record = json.loads(line)
results[record["custom_id"]] = record
return results
write_batch_file("batch_in.jsonl", "example-model", ["Summarize A.", "Summarize B."])Common errors
- Batching work that is not really offline. If a user later needs the answer in seconds, the discount is not worth it.
- Ignoring partial failure. Some requests in a batch can fail while others succeed. Check each result for an error, collect the failed IDs, and resubmit only those.
- Skipping a small test. A malformed request can waste a whole run. Send a handful of items through the live API first, then submit the full batch.
- Forgetting limits. Providers cap the number of requests and the file size per batch. Split large jobs into several batches.
- No output cap. Batch pricing still charges for output tokens, so keep
max_tokensset.
Estimating the saving
Use the cost estimate from the earlier chapter, then apply the batch discount to the result. If a live run costs $40 and the batch discount is 50%, the batch run costs about $20. Measure your real token counts first, so the estimate rests on your own numbers.
Exercise
You must label 200,000 archived support tickets by topic. The results are needed by next week. A teammate suggests sending them through your live chat endpoint with 8 parallel workers. What would you do instead, and what two safeguards would you add?
Show answer
Submit the tickets as a batch job, since no one is waiting and the deadline allows the batch window. This gives the discounted price and avoids rate limit pressure on the live endpoint. Safeguards: give every request a custom ID and match results by ID rather than position, and check each result for errors so you resubmit only the failed items. Testing a small sample through the live API first is also reasonable.