Expert about 7 h
The picture
01
Pre-compute
facts in code
02
Build requests
compact JSONL
03
Chunk
count + size limits
04
Submit + track
checkpoint table
05
Collect + retry
error file
06
Validate
schema, spot checks
When to use batch
If results are not needed in seconds, a batch API is usually cheaper (providers typically discount batch jobs heavily; check current pricing) and avoids rate-limit juggling. Typical jobs: explaining or classifying every record in a table, enriching a catalogue, scoring a backlog, generating evaluation or training data.
The engineering problem is no longer the prompt. It is making a job with hundreds of thousands of requests finish correctly, once, even if something fails along the way.
Step 1: do the arithmetic outside the model
Compute every derived number (differences, ratios, rankings, eligibility flags) in your data engine (Spark, SQL, pandas) and give the model facts. The model's task becomes explaining or classifying, which it does well; it never has to do arithmetic it can get wrong, and the output is checkable against the data.
Step 2: compact, consistent payloads
Tokens cost money at scale, so every field in every request is multiplied by the row count. A compact label=value layout with only the needed fields beats pretty JSON.
def row_to_prompt(r: dict) -> str:
fields = ["id", "segment", "service_gap_pct", "recommended_qty", "current_qty", "delta_qty", "option_a", "option_b"]
return "\n".join(f"{k}={r[k]}" for k in fields if r.get(k) is not None)
def to_request(r: dict, system_prompt: str, model: str):
return {
"custom_id": str(r["id"]),
"method": "POST",
"url": "/v1/chat/completions",
"body": {"model": model, "max_tokens": 250, "temperature": 0,
"messages": [{"role": "system", "content": system_prompt}, {"role": "user", "content": row_to_prompt(r)}]},
}
Keep the static system prompt identical across requests and first, so provider prompt caching can discount it. Validate the prompt rules on a stratified sample of about 50 rows before spending on the full run.
Step 3: chunk by count and by size
Providers limit both the number of requests and the file size per batch. Split on whichever limit you hit first, with headroom.
import json
def chunk_requests(requests, max_count=20_000, max_bytes=150 * 1024 * 1024):
chunk, size = [], 0
for req in requests:
line = json.dumps(req, ensure_ascii=False) + "\n"
b = len(line.encode("utf-8"))
if chunk and (len(chunk) >= max_count or size + b > max_bytes):
yield chunk
chunk, size = [], 0
chunk.append(line)
size += b
if chunk:
yield chunk
Step 4: a checkpoint table you can trust
Every chunk has a row with its state. Updating that row is the only way progress is recorded.
import sqlite3, hashlib
db = sqlite3.connect("batch_state.db")
db.execute("""CREATE TABLE IF NOT EXISTS chunks (
run_id TEXT, chunk_idx INTEGER, content_hash TEXT,
status TEXT, -- pending | submitted | completed | failed
batch_id TEXT, n_requests INTEGER, n_ok INTEGER, n_err INTEGER,
PRIMARY KEY (run_id, chunk_idx))""")
def submit_run(run_id, chunks, client):
for i, lines in enumerate(chunks):
h = hashlib.sha256("".join(lines).encode()).hexdigest()
row = db.execute("SELECT status FROM chunks WHERE run_id=? AND chunk_idx=?", (run_id, i)).fetchone()
if row and row[0] in ("submitted", "completed"):
continue # resume: never resubmit finished work
path = f"inputs/{run_id}_{i}.jsonl"
open(path, "w", encoding="utf-8").writelines(lines)
f = client.files.create(file=open(path, "rb"), purpose="batch")
b = client.batches.create(input_file_id=f.id, endpoint="/v1/chat/completions", completion_window="24h")
db.execute("INSERT OR REPLACE INTO chunks VALUES (?,?,?,?,?,?,?,?)", (run_id, i, h, "submitted", b.id, len(lines), None, None))
db.commit()
On a platform like Databricks the same idea is a Delta table updated with MERGE, which is atomic and idempotent: re-running the notebook upserts rows rather than duplicating them.
Step 5: collect, retry and validate
def collect(run_id, client):
for chunk_idx, batch_id in db.execute("SELECT chunk_idx, batch_id FROM chunks WHERE run_id=? AND status='submitted'", (run_id,)).fetchall():
b = client.batches.retrieve(batch_id)
if b.status not in ("completed", "failed", "expired", "cancelled"):
continue # still running; check again later
ok = err = 0
if b.output_file_id:
for line in client.files.content(b.output_file_id).text.splitlines():
rec = json.loads(line)
if rec.get("error") or rec["response"]["status_code"] != 200 or not valid(rec):
err += 1
save_for_retry(rec["custom_id"])
else:
ok += 1
save_result(rec["custom_id"], rec["response"]["body"]["choices"][0]["message"]["content"])
if b.error_file_id:
for line in client.files.content(b.error_file_id).text.splitlines():
save_for_retry(json.loads(line)["custom_id"])
db.execute("UPDATE chunks SET status='completed', n_ok=?, n_err=? WHERE run_id=? AND chunk_idx=?", (ok, err, run_id, chunk_idx))
db.commit()
Rebuild the failed items into a new, smaller run and repeat until the failure count is negligible or the remainder needs a human. Track the completion rate (for example 153,931 of 153,938 is 99.995 percent) and look at the remaining items by hand: they are usually revealing.
Validation of outputs
Every output is checked by code before it is accepted: parses, within length, mentions only fields it was given, contains no forbidden claims, numbers quoted in the text match the input fields. Then read a random sample by eye. Batch jobs make a systematic error expensive, and cheap to catch early.
Cost model
def run_cost(n_items, in_tok, out_tok, p_in, p_out, cached_frac=0.0, p_cached=None, batch_discount=0.5):
p_cached = p_in * 0.1 if p_cached is None else p_cached
per_item = ((1 - cached_frac) * in_tok * p_in + cached_frac * in_tok * p_cached + out_tok * p_out) / 1e6
return n_items * per_item * batch_discount
print(run_cost(150_000, 2100, 250, p_in=0.15, p_out=0.60, cached_frac=0.6)) # placeholder prices
Measure real token counts on the 50-row sample, then multiply. Set a hard budget and abort the run if the projection exceeds it.
Common mistakes
- One giant batch with no checkpoints.
- Resubmitting a chunk after a restart because status was only in memory.
- Letting the model compute figures that the pipeline could have computed exactly.
- Accepting outputs without validating them.
Exercises
- Build the chunker and checkpoint table, run 1,000 items, kill the process midway, and prove the resume does no duplicate work.
- Write a validator that checks every number in each explanation against its input row, and report the failure rate.
You are done when you can…
- Build JSONL batch requests and split them by both request count and file size
- Design a checkpoint table so an interrupted run resumes without resubmitting finished chunks
- Estimate cost per item and total run cost from token counts