Sub topic 8
Reading the output and error files
A batch job that reaches completed has not necessarily succeeded for every request. This chapter shows how to read the two result files, how to turn them into a lookup table keyed by custom_id, and how to find every request that did not produce a usable answer.
This chapter assumes you can already build a JSONL request file with unique custom_id values and submit and poll a batch, as covered in the previous chapters. It also assumes basic Python file and JSON handling. The examples use the OpenAI Batch API.
Where the results live
When a batch finishes, the batch object carries up to two file IDs:
output_file_idpoints to a JSONL file with one line per request that produced a response.error_file_idpoints to a JSONL file with one line per request that failed.
Either field can be None. A batch where every request succeeded has no error file. A batch where every request failed may have no output file. Always check both before downloading.
The terminal status also affects what you find:
| Terminal status | Output file | Error file | What to do |
|---|---|---|---|
| `completed` | Usually present | Present if any request failed | Read both files. |
| `expired` | Holds requests finished before the window closed | Typically lists the unfinished requests | Keep the partial results and resubmit the rest. |
| `cancelled` | Holds requests finished before cancellation | Typically lists the unprocessed requests | Same as `expired`. |
| `failed` | Usually absent | Usually absent | The whole file was rejected. Read `batch.errors` and fix the input. |
The failed status means the batch was rejected during validation, for example because of a malformed line or a duplicate custom_id. No request was processed. The reasons are on the batch object, not in a result file.
The shape of a result line
Each line in the output file is a JSON object. A successful line looks like this, formatted across several lines here for readability:
{
"id": "batch_req_abc123",
"custom_id": "doc-001",
"response": {
"status_code": 200,
"request_id": "req_def456",
"body": {
"id": "chatcmpl-xyz",
"object": "chat.completion",
"model": "gpt-4o-mini",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "The meeting moved to Thursday."},
"finish_reason": "stop"
}
],
"usage": {"prompt_tokens": 31, "completion_tokens": 8, "total_tokens": 39}
}
},
"error": null
}The fields you use most:
custom_idis the ID you assigned in the request file. It is the only reliable link back to your input.response.status_codeis the HTTP status the request would have returned if sent synchronously.response.bodyhas the same shape as a normal chat completion response.errorisnullon success and an object withcodeandmessagewhen the request failed before producing a response.idis a batch-level request ID (batch_req_...). It is useful in support tickets, but it is not your key.
A failed line has response set to null and an error object. Error lines in the error file use the same envelope, so one parser handles both files.
Why order cannot be trusted
Requests in a batch are processed in parallel and finish in any order. The output file is not guaranteed to follow the order of your input file, and failed requests leave gaps. If you zip the output lines against your input list by position, one failure shifts every later result onto the wrong document. This produces wrong answers without raising an error.
Always build a dictionary keyed by custom_id.
Parsing both files
The following script retrieves a finished batch, reads both files, and sorts every result into one of three groups: succeeded, failed, or missing. Set BATCH_ID to your batch's ID, and keep the documents dictionary you used to build the request file.
import json
from openai import OpenAI
client = OpenAI()
BATCH_ID = "batch_replace_with_your_id"
documents = {
"doc-001": "The meeting moved to Thursday because of a venue conflict.",
"doc-002": "Quarterly revenue grew 4% while costs stayed flat.",
}
def read_jsonl(file_id):
text = client.files.content(file_id).text
return [json.loads(line) for line in text.splitlines() if line.strip()]
batch = client.batches.retrieve(BATCH_ID)
if batch.status == "failed":
raise SystemExit(f"Batch rejected: {batch.errors}")
results = {}
failed = {}
if batch.output_file_id:
for record in read_jsonl(batch.output_file_id):
custom_id = record["custom_id"]
response = record.get("response")
if record.get("error") is None and response and response["status_code"] == 200:
results[custom_id] = response["body"]["choices"][0]["message"]["content"]
else:
failed[custom_id] = record.get("error") or response
if batch.error_file_id:
for record in read_jsonl(batch.error_file_id):
failed[record["custom_id"]] = record.get("error") or record.get("response")
missing = set(documents) - set(results) - set(failed)
print(len(results), "succeeded;", len(failed), "failed;", len(missing), "missing")Several details in this script matter.
Handle a missing file ID
Both if batch.output_file_id and if batch.error_file_id guard against None. Passing None to client.files.content raises an error. This crashes exactly the runs where you most need the result handling to work.
Check the status code, not just the error field
A line can have error: null and still carry a non-200 status_code, for example a 429 or 500 that was recorded as a response. Treating "no error" as "success" would put an error body through your choices[0] lookup and raise a KeyError. The script tests both conditions and sends everything else to failed.
Skip blank lines
The if line.strip() filter protects json.loads from a trailing empty line. Parse line by line. Do not call json.loads on the whole file, because the file as a whole is not valid JSON.
Compute the missing set
The missing set is the difference between what you submitted and what you accounted for. A request lands there when it appears in neither file. This can happen after an expired or cancelled batch, or if a file was truncated. Checking request_counts on the batch object tells you how many to expect, but only the set difference tells you which ones.
Checks worth adding
A 200 response does not mean the answer is usable. Before you store a result, check the following:
finish_reason. A value oflengthmeans the model hitmax_tokensand the text is cut off. Treat it as a failure for tasks such as JSON extraction.- Empty content. The
contentfield can be empty orNone, for example when the model returns a refusal or tool call instead. - Parseable output. If you asked for JSON, parse it inside a
tryblock and route parse failures tofailed. - Duplicate IDs. If the same
custom_idappears twice in a file, the dictionary keeps only the last one. Validation normally prevents this on upload, but a defensive check costs one line.
Here is a stricter version of the success test, written as a helper you can call from the loop above:
def extract_text(record):
"""Return (text, reason). text is None when the result is unusable."""
response = record.get("response")
if record.get("error") is not None or not response:
return None, record.get("error") or "no response"
if response["status_code"] != 200:
return None, f"status {response['status_code']}"
choice = response["body"]["choices"][0]
if choice["finish_reason"] != "stop":
return None, f"finish_reason {choice['finish_reason']}"
content = choice["message"].get("content")
if not content:
return None, "empty content"
return content, NoneRequests rejected by this helper go into failed with the reason attached, so the retry step can see why each one failed.
Reading the error file
Error lines tell you whether retrying is worthwhile. Codes vary by provider and over time, so read the code and message fields from your own runs instead of assuming a fixed list. In general, failures fall into two groups:
- Transient. Rate limits, server errors, and
batch_expiredmean the request itself was fine. Resubmit it unchanged. - Permanent. A request body that fails validation, an unknown model name, or a prompt that exceeds the context window will fail again. Fix the input before resubmitting, or skip it and record why.
Counting failures by code is a quick way to see which group dominates:
from collections import Counter
def error_code(value):
if isinstance(value, dict):
return value.get("code") or f"status_{value.get('status_code')}"
return str(value)
counts = Counter(error_code(v) for v in failed.values())
for code, n in counts.most_common():
print(f"{code}: {n}")If one code accounts for most failures, the cause is probably shared, such as a bad parameter in your request template. Fix that before you resubmit anything.
Persist the files before processing
Output files are retained by the provider for a limited time, and you pay nothing extra to download them again while they exist. Save the raw files to disk anyway, and parse from your local copy. If your parser has a bug, you can fix it and rerun without depending on the provider's storage.
from pathlib import Path
out_dir = Path("batch_results")
out_dir.mkdir(exist_ok=True)
if batch.output_file_id:
(out_dir / f"{batch.id}_output.jsonl").write_text(
client.files.content(batch.output_file_id).text, encoding="utf-8"
)
if batch.error_file_id:
(out_dir / f"{batch.id}_errors.jsonl").write_text(
client.files.content(batch.error_file_id).text, encoding="utf-8"
)Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `KeyError: 'choices'` | A non-200 response was parsed as a success | Check `status_code` before reading `body`. |
| Answers attached to the wrong documents | Matching by position | Key every result by `custom_id`. |
| `files.content` raises on `None` | No error file existed | Guard on `error_file_id` before downloading. |
| Count of results is lower than expected, no errors listed | Requests expired or cancelled | Compute the `missing` set from your input IDs. |
| `json.JSONDecodeError` on the whole file | Parsing the file as one JSON document | Parse one line at a time. |
Exercise
A batch of 1,000 requests ends with status completed. Its output file has 970 lines and its error file has 25 lines. After you key everything by custom_id, how many requests are in the missing set, and why is checking for that set still worthwhile?
Show answer
The missing set holds 5 requests, because 1,000 - 970 - 25 = 5, assuming the two files share no custom_ids. These five appear in neither file, so nothing in the files explains what happened to them. Without the set difference you would treat the job as finished and silently lose them. They go into the retry list along with the 25 failures.
Exercise
Why does the parsing loop test both record.get("error") is None and response["status_code"] == 200, and what goes wrong if you test only the first?
Show answer
A line can have no error object but still carry a non-200 status code, such as a 429 or 500. Its body is then an error payload without a choices field, so reading choices[0] raises a KeyError and stops the run. Testing both conditions sends such lines to the failed group, where they can be retried.