Sub topic 5
Using custom_id to match results to inputs
A batch job returns its results as a file, and that file does not promise to list results in the order you sent them. The custom_id field is the only dependable link between an input and its output. This chapter covers how to design those IDs, how to validate them before you submit, and how to join results back to inputs.
This chapter assumes you can read and write JSON Lines files in Python and that you have seen the request format from the previous chapter. The examples follow the OpenAI Batch API, and the ideas carry over to other providers.
Why position cannot identify a result
In a synchronous call, the response belongs to the request you just made. A batch breaks that link. The provider spreads your requests across spare capacity, so they finish at different times. The output file is written from whatever finished, and the lines can appear in any order.
Matching by line number can therefore fail without any error:
- Summary 7 is attached to document 12, and nothing flags the mismatch.
- Failed requests are not in the output file at all, so every later line shifts by one.
- Failed requests may appear in a separate error file, which has its own order.
Each request you submit carries a custom_id string, and each result line echoes it back. Treat that string as a foreign key between your data and the provider's results.
Properties of a good custom_id
A good ID has four properties.
- Unique within the batch. Providers require this. Two requests with the same ID cannot be told apart in the output, and a batch with duplicates may be rejected at validation.
- Stable across retries. If you resubmit a failed request in a later batch, it should get the same ID. Then your result store can be keyed by ID and a retry simply fills the gap.
- Decodable by you. You should be able to look at an ID in a log and know which record, task, and prompt version it came from.
- Portable. Different providers accept different characters. Anthropic's Message Batches API, for example, restricts IDs to letters, digits, underscores, and hyphens, up to 64 characters. If you stay inside
[A-Za-z0-9_-]{1,64}, the same IDs work almost everywhere.
Avoid putting personal data, secrets, or whole prompts in an ID. IDs appear in logs, dashboards, and error messages.
Strategies for building IDs
| Strategy | Example | Strength | Weakness |
|---|---|---|---|
| Source key | `doc-001` | Simple, easy to read | Collides if one document is sent for two tasks |
| Source key plus task and prompt version | `summarize-v2-doc-001` | Safe to store results from many runs side by side | Longer |
| Source key plus content hash | `summarize-v2-doc-001-ab12cd34` | Detects when the input text changed since the last run | Hash must be computed the same way each time |
| Row number | `row-000017` | Works when data has no natural key | Breaks if the input is re-sorted or filtered |
| Random UUID | `3f2a...` | Never collides | Not stable on retry unless you save the mapping |
For most pipelines, use the third row. The source key says which record it is. The task and prompt version stop results from different experiments overwriting each other. The short content hash lets you spot a stale result when the document has been edited since it was processed.
Use a random UUID only if you also write a mapping file from UUID to input before submitting. Without that file, a crash after submission leaves you with results you cannot attribute.
Building IDs and validating them before upload
Check IDs locally before you upload. A duplicate or malformed ID found after a 24-hour wait costs far more than one found in a millisecond. The script below builds IDs, checks them, and writes the request file.
import hashlib
import json
import re
ID_PATTERN = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
documents = {
"doc-001": "The meeting moved to Thursday because of a venue conflict.",
"doc-002": "Quarterly revenue grew 4% while costs stayed flat.",
}
def make_custom_id(task, prompt_version, doc_key, text):
digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:8]
return f"{task}-{prompt_version}-{doc_key}-{digest}"
def build_requests(documents, task="summarize", prompt_version="v1"):
requests = []
seen = set()
for doc_key, text in documents.items():
custom_id = make_custom_id(task, prompt_version, doc_key, text)
if not ID_PATTERN.match(custom_id):
raise ValueError(f"Invalid custom_id: {custom_id!r}")
if custom_id in seen:
raise ValueError(f"Duplicate custom_id: {custom_id!r}")
seen.add(custom_id)
requests.append(
{
"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,
},
}
)
return requests
requests = build_requests(documents)
with open("batch_input.jsonl", "w", encoding="utf-8") as f:
for request in requests:
f.write(json.dumps(request) + "\n")
# Keep the expected IDs: they are the checklist you compare results against.
expected_ids = {r["custom_id"] for r in requests}
print(len(expected_ids), "requests written")The set expected_ids is the important output. Save it, or be able to recompute it from the same inputs, because you need it when reading results.
Two details are easy to miss:
- The hash is computed from the exact text. If you normalize whitespace on one run and not on the next, the same document gets two different IDs.
- The ID is built from the document key, not the position in the loop. Re-sorting the input leaves every ID unchanged.
Joining results by custom_id
Each line of the output file is a JSON object that includes your custom_id. Some lines hold a successful response. Others hold an error. A request can also be missing from both files, for example when the batch expired before it ran.
The function below sorts every expected ID into one of four outcomes: succeeded, failed, missing, or unexpected. It takes the lines as text so that you can test it without calling the API. The sample data is deliberately out of order and includes a failure.
import json
def collect(lines, expected_ids):
results = {}
failed = {}
seen = set()
duplicates = set()
for line in lines:
if not line.strip():
continue
record = json.loads(line)
custom_id = record["custom_id"]
if custom_id in seen:
duplicates.add(custom_id)
continue
seen.add(custom_id)
response = record.get("response")
if record.get("error") is None and response and response.get("status_code") == 200:
results[custom_id] = response["body"]["choices"][0]["message"]["content"]
else:
failed[custom_id] = record.get("error") or response
missing = set(expected_ids) - seen
unexpected = seen - set(expected_ids)
return results, failed, missing, unexpected, duplicates
sample_ids = {"summarize-v1-doc-001-aaaa1111", "summarize-v1-doc-002-bbbb2222", "summarize-v1-doc-003-cccc3333"}
sample_output = [
json.dumps({
"id": "batch_req_2",
"custom_id": "summarize-v1-doc-002-bbbb2222",
"response": {"status_code": 200, "request_id": "r2",
"body": {"choices": [{"message": {"content": "Revenue rose 4%."}}]}},
"error": None,
}),
json.dumps({
"id": "batch_req_1",
"custom_id": "summarize-v1-doc-001-aaaa1111",
"response": {"status_code": 200, "request_id": "r1",
"body": {"choices": [{"message": {"content": "The meeting moved to Thursday."}}]}},
"error": None,
}),
]
results, failed, missing, unexpected, duplicates = collect(sample_output, sample_ids)
print(sorted(results))
print("missing:", sorted(missing))Running this prints the two successful IDs, in sorted order and not in file order, then missing: ['summarize-v1-doc-003-cccc3333']. The third document never appeared in the file, and only the ID comparison revealed it.
With a real batch, pass client.files.content(batch.output_file_id).text.splitlines() as lines. Run collect a second time on the error file, if there is one, and merge the failures.
How the join works
The diagram shows where each ID is created, carried, and checked.
The expected-ID set is what makes the join complete. Without it you can only report what came back. With it you can also report what did not come back.
Edge cases
Identical inputs. If two records have the same key and the same text, they produce the same ID, and build_requests raises an error. Decide what you want. Usually you deduplicate and fan the single result out to both records afterward, which also saves money.
The same document for two tasks. Putting the task name in the ID, as in summarize-v1- and classify-v1-, keeps results from two jobs distinct even if you merge them into one store.
Errors that lack a useful body. A failed line can have response set to null and an error object instead. Some failures return a response with a non-200 status code and an error body. The collect function handles both by checking the error field and the status code together.
Result lines with no matching expected ID. This usually means you are reading the output of a different batch, or your ID logic changed between building and reading. Treat a non-empty unexpected set as a bug and stop, because writing those results into your store can corrupt it.
Duplicate IDs in the output. This should not happen for a valid batch. Keeping the first and recording the rest, as the code does, makes the problem visible without crashing a long job.
Changing the ID scheme mid-project. If you alter the format after storing results, old results no longer match new IDs, and you will resubmit work that was already done. Version the scheme deliberately and keep the old results table readable.
Checklist
- Build IDs from stable inputs: source key, task, prompt version, and a short content hash.
- Restrict them to
[A-Za-z0-9_-]and 64 characters. - Check for duplicates and invalid IDs before upload.
- Persist the expected-ID set, or be able to regenerate it.
- Read both the output file and the error file.
- Report four groups: succeeded, failed, missing, unexpected.
- Never rely on line order.
Exercise
A teammate matches results to inputs with zip(inputs, output_lines). In a test batch of 20 requests, one request fails and appears in the error file instead. What goes wrong, and what should the code use instead?
Show answer
The output file holds only 19 lines, and they may be in a different order from the inputs. zip pairs each result with the wrong input from the point of the first mismatch onward, and it also silently drops the last input. Each result should be looked up by its custom_id in a dictionary built from the output file. The set of expected IDs minus the IDs seen in the output and error files then gives the requests that need attention.
Exercise
You run the same summarization job weekly. Documents are sometimes edited between runs. Design a custom_id format that lets you skip unchanged documents and reprocess edited ones, and say why a plain row number would not work.
Show answer
Use a format such as summarize-v1-<doc_key>-<hash8>, where the hash is taken from the document text. Before each run, compute the IDs for all current documents and subtract the IDs already in your results store. An unchanged document yields an ID that is already stored, so it is skipped. An edited document yields a new hash, so its ID is new and it is resubmitted. A row number changes whenever rows are added, removed, or re-sorted, and it says nothing about whether the content changed, so it cannot support this comparison.