Sub topic 5
Using custom_id to match results to inputs
This chapter assumes you can write basic Python with file I/O and JSON, you have called a chat completions API, and you know the JSON Lines format (one JSON object per line). It uses the OpenAI Batch API as the worked example.
Why order cannot be trusted
A batch job runs your requests in parallel and finishes them at different times. The output file lists results as they complete. Line 5 of the output may answer line 12 of your input. The provider does not promise any order.
The custom_id field solves this. It is a string you attach to each request. The provider copies it unchanged into the matching result line. You then join results to inputs by this key, never by position.
What a good custom_id looks like
Each custom_id must be unique within one batch. The API rejects a file that contains duplicates.
A good ID has these properties:
- It is stable. Rebuilding the file from the same data gives the same IDs.
- It maps back to your source record, such as a database primary key or a file name.
- It is short and plain text. Avoid personal data, because IDs appear in logs and error files.
| Approach | Example | Problem or benefit |
|---|---|---|
| Source key | `doc-001` | Stable and traceable. Best default. |
| Row number | `row-17` | Breaks if the input is re-sorted or filtered. |
| Random UUID | `a3f9...` | Unique, but you must store the mapping yourself. |
| Content hash | `sha1-9c1d...` | Stable and deduplicates identical inputs. Needs a hash step. |
If the same record appears in several requests, add a suffix for the task. For example, doc-001:summary and doc-001:sentiment. The suffix keeps IDs unique and tells you what each result answers.
Building the lookup
Keep a dictionary from custom_id to the source record while you write the request file. This is the same file-writing step from the previous chapter, with the dictionary kept in memory or saved to disk.
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.",
}
seen = set()
with open("batch_input.jsonl", "w", encoding="utf-8") as f:
for custom_id, text in documents.items():
if custom_id in seen:
raise ValueError(f"Duplicate custom_id: {custom_id}")
seen.add(custom_id)
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")The duplicate check catches the mistake locally. Otherwise you find out only after the upload is rejected.
Joining results by key
After the job finishes, each output line carries the same custom_id. Build a result dictionary keyed by that ID, then look up answers per document.
import json
results = {}
for line in open("batch_output.jsonl", encoding="utf-8"):
record = json.loads(line)
response = record.get("response")
if record.get("error") is None and response and response["status_code"] == 200:
results[record["custom_id"]] = response["body"]["choices"][0]["message"]["content"]
for custom_id, text in documents.items():
print(custom_id, "->", results.get(custom_id, "NO RESULT"))The loop runs over your inputs, not the output file. Any input without an entry shows NO RESULT. This is how you find missing requests, which the next chapters handle.
Common errors
- Duplicate IDs. The batch is rejected at validation. Check uniqueness before upload.
- Position-based matching. It appears to work in small tests, then silently misaligns in large runs.
- Unstable IDs. If you generate random IDs and do not save the map, a restart cannot tell which results belong to which records.
- Assuming one line per input. A failed request may appear in the error file, or not appear at all. Always compare the set of IDs you sent with the set you received.
Exercise
A teammate builds IDs as row-0, row-1, and so on from the current position in a list that is sorted by date. Next week the list is re-sorted and the job is rerun. What goes wrong, and what would you use instead?
Show answer
The same ID now points to a different record, so saved results from the earlier run attach to the wrong inputs. Use a stable key from the source data, such as a database primary key or file name, optionally with a task suffix like :summary.
Exercise
Your output file has 998 lines for 1,000 requests. Using custom_id, how do you find the two missing requests?
Show answer
Build the set of IDs you sent and the set of IDs found in the output and error files, then subtract: set(sent) - set(results) - set(failed). The difference is the missing IDs.