Sub topic 4
Building the JSONL request file
A batch job starts with one file. This chapter covers what goes in that file, how to generate it safely, and how to check it before you upload. It assumes you can write basic Python with file I/O and JSON. It also assumes you have called a chat completions API and know that JSON Lines means one JSON object per line.
What a batch file is
A batch input file is a JSON Lines (JSONL) file. Each line is one complete API request, written as a JSON object. The provider reads the file, runs every request on its own schedule, and writes the results to a separate output file.
The file takes the place of the loop you would write for real-time calls. Without batching you would call the API once per document. With batching you write the same requests to disk and hand them over together.
Each line has four fields in the OpenAI format:
| Field | Type | Purpose |
|---|---|---|
| `custom_id` | string | Your own label for the request. It must be unique within the file. |
| `method` | string | The HTTP method. Currently always `"POST"`. |
| `url` | string | The endpoint path, such as `/v1/chat/completions`. |
| `body` | object | The same JSON you would send to that endpoint in a real-time call. |
The body is the part you already know. Anything you would put in a normal chat completion request, such as model, messages, temperature, max_tokens, or response_format, goes here.
Why JSONL and not a JSON array
JSONL lets the provider read one request at a time without loading the whole file. It also lets you append a line without rewriting everything. A truncated file loses only its last line, not its structure.
The format has one rule that matters in practice: a record must never contain a raw newline. json.dumps escapes newlines inside strings as \n, so it is safe. Do not use indent=2 when writing records, because that spreads one request over many lines and breaks the format.
A minimal generator
This script writes the file from a dictionary of documents.
import json
documents = {
"doc-001": "The meeting moved to Thursday because of a venue conflict.",
"doc-002": "Quarterly revenue grew 4% while costs stayed flat.",
}
with open("batch_input.jsonl", "w", encoding="utf-8") as f:
for custom_id, text in documents.items():
request = {
"custom_id": custom_id,
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": "gpt-4o-mini",
"messages": [
{"role": "system", "content": "Summarize the text in one sentence."},
{"role": "user", "content": text},
],
"max_tokens": 100,
},
}
f.write(json.dumps(request) + "\n")Three details are easy to miss:
- Each line ends with exactly one
"\n".json.dumpsdoes not add it. - The file is opened with
encoding="utf-8". Without it, Windows may default to another encoding and corrupt non-ASCII text. - The
urlis a path, not a full address. It has no host name.
Here is the first line the script produces, shown wrapped for reading. In the file it is a single line.
{"custom_id": "doc-001", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "system", "content": "Summarize the text in one sentence."}, {"role": "user", "content": "The meeting moved to Thursday because of a venue conflict."}], "max_tokens": 100}}Rules the whole file must follow
The provider validates the file when you create the batch. A violation of the rules below usually rejects the whole batch, not a single line.
- One endpoint per file. Every
urlmust match theendpointyou pass when you create the batch. You cannot mix chat completions and embeddings in one file. - Unique
custom_idvalues. Duplicates cause validation to fail. - One model per file. With OpenAI, every request in a batch must use the same model. To compare two models, build two files.
- No streaming. Setting
stream: trueis not supported, because nobody is connected to receive the stream. - Size limits. At the time of writing, OpenAI allows up to 50,000 requests and 200 MB per file. Check the current documentation, because limits change. A later chapter covers splitting large jobs.
Treat these as the checklist your validator enforces.
Designing the body
The body deserves the same care as a real-time prompt, and more, because you cannot iterate quickly. A mistake in the prompt costs a full batch and up to 24 hours.
- Set
max_tokens(or the endpoint's equivalent) deliberately. A cap stops a runaway response from using tokens you did not plan for. It also makes cost estimates more reliable. - Pin
temperaturefor repeatable work. For classification and extraction, use0or a low value so reruns of failed items behave like the original run. - Use structured output where you can. If you will parse the response in code, ask for JSON through
response_format. That reduces the parsing failures you will have to retry later. - Keep the system prompt identical across lines. A shared prefix keeps files easy to audit. Where the provider offers prompt caching, a shared prefix may also lower cost, but treat that as a bonus and check the provider's rules.
Designing the custom_id
The custom_id is the only link between a line you wrote and a result you receive. Output order is not guaranteed to match input order, so you cannot rely on line position. The next chapter covers matching in depth. For now, the point is to choose IDs that will still make sense when you read them weeks later.
A good ID has three properties:
- It is unique. The provider requires this.
- It is stable. Building the same request twice yields the same ID. This lets you detect work already done.
- It is informative. It names the source record, and ideally the task and prompt version.
Avoid using a bare loop counter. If you add or remove a document, every later counter shifts and old results no longer line up with new inputs.
import json
PROMPT_VERSION = "v2"
TASK = "summary"
def make_custom_id(doc_id: str) -> str:
return f"{TASK}:{PROMPT_VERSION}:{doc_id}"
def build_request(doc_id: str, text: str) -> dict:
return {
"custom_id": make_custom_id(doc_id),
"method": "POST",
"url": "/v1/chat/completions",
"body": {
"model": "gpt-4o-mini",
"temperature": 0,
"max_tokens": 100,
"messages": [
{"role": "system", "content": "Summarize the text in one sentence."},
{"role": "user", "content": text},
],
},
}
def write_batch_file(path: str, documents: dict) -> int:
count = 0
with open(path, "w", encoding="utf-8") as f:
for doc_id, text in documents.items():
f.write(json.dumps(build_request(doc_id, text), ensure_ascii=False) + "\n")
count += 1
return count
if __name__ == "__main__":
docs = {
"doc-001": "The meeting moved to Thursday because of a venue conflict.",
"doc-002": "Quarterly revenue grew 4% while costs stayed flat.",
}
print(write_batch_file("batch_input.jsonl", docs), "requests written")Because the prompt version is in the ID, results from v1 and v2 of a prompt can sit in the same results store without colliding. The ensure_ascii=False argument keeps non-ASCII characters readable in the file. Both settings are valid JSON, so use whichever you prefer.
Check the provider's rules on ID length and characters. Keep IDs short and use plain letters, digits, colons, and hyphens.
The build pipeline at a glance
The diagram shows the order of steps from source records to a file that is ready to upload.
Validate before you upload
Provider-side validation is slow and gives limited feedback. Check the file yourself first. The validator below reads the file line by line, so it works on large files, and it reports every problem it finds, not just the first.
import json
MAX_REQUESTS = 50_000
MAX_BYTES = 200 * 1024 * 1024
def validate_batch_file(path: str, endpoint: str = "/v1/chat/completions") -> list:
problems = []
seen_ids = set()
models = set()
total_bytes = 0
count = 0
with open(path, "rb") as f:
for line_no, raw in enumerate(f, start=1):
total_bytes += len(raw)
if not raw.strip():
problems.append(f"line {line_no}: blank line")
continue
try:
record = json.loads(raw)
except json.JSONDecodeError as exc:
problems.append(f"line {line_no}: invalid JSON ({exc})")
continue
count += 1
custom_id = record.get("custom_id")
if not isinstance(custom_id, str) or not custom_id:
problems.append(f"line {line_no}: missing or non-string custom_id")
elif custom_id in seen_ids:
problems.append(f"line {line_no}: duplicate custom_id {custom_id!r}")
else:
seen_ids.add(custom_id)
if record.get("method") != "POST":
problems.append(f"line {line_no}: method must be POST")
if record.get("url") != endpoint:
problems.append(f"line {line_no}: url {record.get('url')!r} != {endpoint!r}")
body = record.get("body")
if not isinstance(body, dict):
problems.append(f"line {line_no}: body must be an object")
else:
models.add(body.get("model"))
if body.get("stream"):
problems.append(f"line {line_no}: streaming is not supported")
if count > MAX_REQUESTS:
problems.append(f"{count} requests exceeds {MAX_REQUESTS}")
if total_bytes > MAX_BYTES:
problems.append(f"{total_bytes} bytes exceeds {MAX_BYTES}")
if len(models) > 1:
problems.append(f"multiple models in one file: {sorted(map(str, models))}")
return problems
if __name__ == "__main__":
issues = validate_batch_file("batch_input.jsonl")
print("OK" if not issues else "\n".join(issues))Run the validator as the last step of your generator, and fail the build if it returns anything. A file that passes still may not give good answers. It only means the provider should accept it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The whole batch is rejected at creation | Duplicate `custom_id`, mixed endpoints, or mixed models | Run the validator and fix the first reported problem |
| Invalid JSON on a line | `indent=2`, or a string written with `str(dict)` instead of `json.dumps` | Write each record with `json.dumps(record)` plus one newline |
| Garbled text in results | The file was written without UTF-8 encoding | Open the file with `encoding="utf-8"` |
| Every request fails, but the file is accepted | A wrong parameter inside `body`, such as an unknown model name | Test one body with a real-time call first |
| Results cannot be matched after the input changed | IDs were loop counters | Derive IDs from source record IDs |
The fourth row is the costly one. The provider accepts the file because its structure is correct, then fails each request on its own. Chapter 10 covers pilot batches, but a cheap defense exists now: send the first generated body through a normal synchronous call before you build the rest.
Summary
A batch file is a JSONL file with one self-contained request per line. Each line has a unique, stable custom_id, a method, an endpoint path, and a body identical to a real-time request. Keep one endpoint and one model per file, and avoid streaming. Validate locally before uploading, because errors found after upload cost time.
Exercise
A teammate builds a batch file with custom_ids "req-0", "req-1", and so on, taken from the loop index over a database query that has no ORDER BY clause. A week later, they rerun the job on the same table. What goes wrong, and how would you change the ID?
Show answer
Without ORDER BY, row order can differ between runs, and rows may have been added or removed. The same index can then refer to different documents, so results from the two runs cannot be compared or merged by ID. Use an ID built from the stable primary key of the source row, plus the task and prompt version, such as "summary:v2:doc-001".
Exercise
Your validator reports "multiple models in one file" for a file that compares gpt-4o-mini and another model on the same 500 documents. How do you fix the job without losing the comparison?
Show answer
Build two separate files, one per model, using the same document IDs and the same prompt. Submit them as two batches. Include the model name or a label in the custom_id (for example "summary:v2:mini:doc-001"), or keep the results in separate stores, so the outputs stay distinguishable when you compare them.