Sub topic 4
Building the JSONL request file
This chapter assumes you can write basic Python with file I/O and JSON, and that you have called a chat completions API before. It also assumes you know what JSON Lines is. Here you build the input file that a batch job reads.
What the file is
A batch input file is a plain text file in JSON Lines (JSONL) format. Each line holds one complete JSON object, and each object describes one API request. The batch service reads the file and runs every request on its own schedule. It is as if you had made thousands of synchronous calls, except that you describe them all up front.
The OpenAI Batch API is the worked example here. Other providers use similar ideas with different field names, which a later chapter compares.
The four fields of a request line
Every line needs the same four top-level keys.
| Field | Meaning | Example |
|---|---|---|
| `custom_id` | Your own label for this request. It must be unique within the file. | `"doc-001"` |
| `method` | The HTTP method. Batch supports `POST`. | `"POST"` |
| `url` | The endpoint path this request targets. | `"/v1/chat/completions"` |
| `body` | The same JSON you would send to that endpoint in a synchronous call. | `{"model": ..., "messages": [...]}` |
The body is the part you already know. If a synchronous call works with a given payload, the same payload works as body. The other three keys are a wrapper around it.
Writing the file
The script below builds one request per document. It sets a fixed system prompt, puts each document in the user message, and writes each request as a single line.
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")Use json.dumps instead of building strings by hand. It escapes any newline inside a document as \n, so a multi-line document still occupies exactly one physical line. A raw newline in the middle of an object breaks the one-object-per-line rule.
Rules the service enforces
- Every
custom_idmust be unique within the file. Duplicates cause the batch to be rejected. - Every line must use the same
url, and that URL must match theendpointyou pass when you create the batch. - A file should use one model. Mixing models in a single file is rejected.
- For OpenAI, a file holds at most 50,000 requests and at most 200 MB. Check the current documentation, because limits change. A later chapter covers splitting large jobs.
Checking the file before you upload
This function reads the file back and tests the rules above. It returns a list of problems, and an empty list means the file passed.
import json
def validate_batch_file(path, expected_url="/v1/chat/completions"):
problems = []
seen = set()
models = set()
with open(path, encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
try:
record = json.loads(line)
except json.JSONDecodeError:
problems.append(f"line {number}: not valid JSON")
continue
custom_id = record.get("custom_id")
if not custom_id:
problems.append(f"line {number}: missing custom_id")
elif custom_id in seen:
problems.append(f"line {number}: duplicate custom_id {custom_id}")
seen.add(custom_id)
if record.get("url") != expected_url:
problems.append(f"line {number}: unexpected url")
models.add(record.get("body", {}).get("model"))
if len(models) > 1:
problems.append(f"multiple models in file: {sorted(map(str, models))}")
return problems
print(validate_batch_file("batch_input.jsonl") or "file looks valid")Choosing custom_id values
The custom_id is how you find each result later, because output order is not guaranteed. Derive it from something stable in your data, such as a database primary key or a document hash. Avoid a bare line counter, because it changes meaning if you reorder or filter the inputs. The next chapter covers matching results back to inputs.
Exercise
A teammate writes a batch file where line 1 uses the URL /v1/chat/completions and line 2 uses /v1/embeddings. Both lines are valid JSON with unique custom_id values. Why will this file fail, and how would you fix it?
Show answer
All lines in one batch file must target the same endpoint, and that endpoint must match the one given when the batch is created. Split the requests into two files, one per endpoint, and create a separate batch for each.