Sub topic 10
Testing with a small pilot batch before scaling
This chapter assumes you can build a JSONL request file, submit a batch, poll it, and read the output and error files. It also assumes you know what custom_id is for. The OpenAI Batch API is the worked example, but the habit applies to any batch provider.
Why a pilot pays for itself
A batch job has a slow feedback loop. A synchronous call tells you within seconds that a prompt is wrong. A batch can sit in validating, in_progress, or finalizing for hours, and the completion window can be up to 24 hours. If the mistake is in the request format, the prompt, or your parsing code, you find out after waiting, and you may have paid for the whole run.
A pilot is a small batch, usually 20 to 200 requests, that goes through exactly the same path as the full job: build the file, upload it, create the batch, poll it, download the results, parse them. You aren't testing the model. You are testing your pipeline and your estimates.
A pilot answers six questions:
- Does the file pass validation, with the right endpoint, a single model, and unique
custom_idvalues? - Does the prompt produce output your parser accepts?
- How many tokens does a typical request use, and what will the full run cost?
- What fraction of requests fail, and why?
- How long does a batch of this kind take to turn around?
- Does your collection code handle both the output file and the error file?
Iterate fast, then pilot once
The pilot is not the place to tune the prompt. Each pilot round trip may take minutes to hours. Tune the prompt with ordinary synchronous calls on the same sample, where feedback takes seconds. The synchronous calls cost more per token, but the sample is small. Once the outputs look right, run one batch pilot to confirm that the batch path works end to end.
Choosing the sample
A sample of the first 50 rows is rarely representative. Files are often sorted by date, source, or length, so the head of the file can look nothing like the rest. Use a seeded random sample so the pilot is reproducible, and force the extremes in: the shortest and longest inputs. Extremes are where context-length errors, empty-input quirks, and truncated outputs appear.
If your data has distinct categories (languages, document types, sources), sample from each one. If you know of ugly cases, such as empty strings, text with unusual encodings, or very long documents, add them by hand.
import random
def pick_pilot(documents, size=50, seed=7):
"""Return a reproducible list of custom_ids that always includes
the shortest and the longest document."""
ids = sorted(documents, key=lambda k: len(documents[k]))
must_have = {ids[0], ids[-1]}
rest = [i for i in ids if i not in must_have]
rng = random.Random(seed)
k = max(0, min(size, len(ids)) - len(must_have))
chosen = must_have | set(rng.sample(rest, k))
return sorted(chosen)
if __name__ == "__main__":
docs = {f"doc-{n:03d}": "word " * (n + 1) for n in range(200)}
pilot_ids = pick_pilot(docs, size=20)
print(len(pilot_ids), pilot_ids[:5])Use one code path for pilot and full run
The most common way a pilot misleads you is when it uses different code from the full run. Put request construction in one function and give it a list of IDs. The pilot passes a short list and the full run passes a long one.
import json
MODEL = "gpt-4o-mini"
def build_request(custom_id, text):
return {
"custom_id": custom_id,
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": MODEL,
"messages": [
{"role": "system", "content": "Summarize the text in one sentence."},
{"role": "user", "content": text},
],
"max_tokens": 100,
},
}
def write_batch_file(path, documents, ids):
with open(path, "w", encoding="utf-8") as f:
for custom_id in ids:
request = build_request(custom_id, documents[custom_id])
f.write(json.dumps(request) + "\n")
if __name__ == "__main__":
documents = {
"doc-001": "The meeting moved to Thursday because of a venue conflict.",
"doc-002": "Quarterly revenue grew 4% while costs stayed flat.",
}
write_batch_file("pilot_input.jsonl", documents, ["doc-001", "doc-002"])Keep the pilot's custom_id values identical to the ones the full run would use. Then the pilot results are not wasted. They are real results for real inputs, and the full run can skip them.
Submit and poll the pilot with the same code as in the earlier chapters. Record the elapsed time from created_at to the terminal status, since that is your first turnaround data point.
Reading the pilot report
Each successful output record includes a usage object with prompt_tokens and completion_tokens. Those numbers let you extrapolate cost from the sample. The function below also counts failures and parse problems, and it reports a high-percentile token count, not just the mean.
import json
def pilot_report(output_lines, requested_ids, total_requests,
price_in_per_m, price_out_per_m, margin=1.2):
ok, failed = {}, {}
tokens_in, tokens_out = [], []
for line in output_lines:
record = json.loads(line)
cid = record["custom_id"]
response = record.get("response")
if record.get("error") is None and response and response["status_code"] == 200:
body = response["body"]
ok[cid] = body["choices"][0]["message"]["content"]
tokens_in.append(body["usage"]["prompt_tokens"])
tokens_out.append(body["usage"]["completion_tokens"])
else:
failed[cid] = record.get("error") or response
missing = set(requested_ids) - set(ok) - set(failed)
n = len(tokens_in)
if n == 0:
return {"succeeded": 0, "failed": len(failed), "missing": len(missing)}
def p95(values):
ordered = sorted(values)
return ordered[min(len(ordered) - 1, int(0.95 * len(ordered)))]
mean_in = sum(tokens_in) / n
mean_out = sum(tokens_out) / n
per_request = (mean_in * price_in_per_m + mean_out * price_out_per_m) / 1_000_000
return {
"succeeded": n,
"failed": len(failed),
"missing": len(missing),
"failure_rate": len(failed) / len(requested_ids),
"mean_prompt_tokens": mean_in,
"p95_prompt_tokens": p95(tokens_in),
"mean_completion_tokens": mean_out,
"p95_completion_tokens": p95(tokens_out),
"estimated_full_cost": per_request * total_requests * margin,
}
if __name__ == "__main__":
def fake(cid, p, c):
return json.dumps({
"custom_id": cid, "error": None,
"response": {"status_code": 200, "body": {
"choices": [{"message": {"content": "A summary."}}],
"usage": {"prompt_tokens": p, "completion_tokens": c}}}})
lines = [fake("doc-001", 120, 20), fake("doc-002", 300, 35)]
# Prices below are made up for the demo. Use your provider's current batch prices.
print(pilot_report(lines, ["doc-001", "doc-002", "doc-003"], 10_000, 0.10, 0.40))The __main__ block feeds in fabricated records so you can run the function without an API key. In a real pilot, pass client.files.content(batch.output_file_id).text.splitlines() as output_lines. Fold in the error file records the same way as in the previous chapter.
Never hard-code prices from a tutorial. Batch discounts and per-model prices change, so read them from your provider's pricing page on the day you run.
Go and no-go criteria
Decide the pass conditions before you look at the results. Otherwise it is easy to rationalize a bad pilot. The thresholds below are starting points. Adjust them to your workload.
| Check | How to measure | Reasonable pass condition |
|---|---|---|
| Validation | Batch moves past `validating` | No file-level errors |
| Completeness | `missing` count in the report | Zero missing requests |
| Failure rate | `failed / requested` | Near zero, and every failure has an understood cause |
| Parse rate | Share of outputs your parser accepts | At or above the rate your downstream use needs |
| Token budget | p95 tokens against model limits | Comfortably below context and `max_tokens` limits |
| Cost | `estimated_full_cost` | Within the budget you set |
| Turnaround | Time from creation to terminal status | Fits the deadline, with room for a retry round |
What a pilot can and cannot tell you
A pilot reveals systematic problems. A wrong endpoint, a malformed message list, a prompt that makes the model return prose where you expected JSON, and an output field your parser reads incorrectly will all show up in a sample of 50.
A pilot does not reveal rare problems. If 0.5% of inputs trigger a failure, a 50-request pilot will probably show none. The retry logic from the previous chapter covers those, so the pilot does not replace it.
Cost extrapolation has limits too:
- Token counts from a small sample have a wide margin of error. The p95 value and the safety margin in the report are there for that reason.
- If the full dataset is much more varied than the sample, the mean can be off. Check the pilot's length distribution against the full dataset's character counts.
- Output length depends on the prompt and the model, so changing either one after the pilot invalidates the estimate.
- Turnaround for 50 requests says little about turnaround for 50,000. Large jobs queue differently, and the 24-hour window is a limit, not a prediction.
Reusing pilot results in the full run
Because pilot IDs match full-run IDs, the full run can exclude them. Keep pilot results in a store keyed by custom_id, and compute the remaining work as a set difference.
def remaining_ids(all_ids, completed):
"""IDs still needing a result, in a stable order."""
done = set(completed)
return [i for i in sorted(all_ids) if i not in done]
if __name__ == "__main__":
print(remaining_ids(["a", "b", "c", "d"], {"b": "result"}))This is the same idea you will use for retries and for a restartable pipeline. Work is defined by which IDs lack results, not by which batches have been submitted.
Common mistakes
- Piloting with a hand-written file and then generating the full file with different code.
- Judging the pilot by reading three outputs. Run your real parser on all of them.
- Skipping the pilot for long inputs. The longest document is the one most likely to hit a token limit.
- Using a sample so small that every request is similar, such as 5 short documents.
- Treating a passing pilot as proof that the full run needs no monitoring.
Exercise
A pilot of 40 requests succeeded. The mean was 300 prompt tokens and 80 completion tokens per request. The full job has 50,000 requests. With made-up batch prices of $0.10 per million input tokens and $0.40 per million output tokens, and a 20% safety margin, what is the estimated full cost? Name one problem a 40-request pilot is unlikely to expose.
Show answer
Per request, input costs 300 × 0.10 / 1,000,000 = $0.00003 and output costs 80 × 0.40 / 1,000,000 = $0.000032, so $0.000062 in total. Over 50,000 requests that is $3.10, and with the 20% margin it is about $3.72. A 40-request pilot is unlikely to expose a rare failure, such as an input type that appears in well under 1% of the data. Retry logic handles that kind of failure.