Sub topic 7
Uploading, submitting, and polling a batch
This chapter covers the middle of a batch job's life. You take a finished JSONL request file and upload it. You then create the batch, watch it run, and stop when it reaches a final state. Reading the results comes in the next chapter.
I assume you can write basic Python with file I/O and JSON, and that you have called a chat completions API. I also assume you have the openai package installed and OPENAI_API_KEY set in your environment. You should also have a batch_input.jsonl file like the one built in the chapter on the request file format.
The three-step flow
A batch submission is three separate API calls. Each one returns an object with an ID that the next call needs.
- Upload the JSONL file with
purpose="batch". The response is a file object with anid. - Create the batch. You pass the file ID, the endpoint, and a completion window. The response is a batch object with its own
idand astatus. - Poll the batch by ID until its status is final. Then read the output file and error file IDs from the batch object.
The upload and the batch creation are separate so that one uploaded file can be reused. You can re-create a batch from the same file ID, for example after cancelling.
Step 1: Upload the request file
from openai import OpenAI
client = OpenAI()
with open("batch_input.jsonl", "rb") as f:
input_file = client.files.create(file=f, purpose="batch")
print(input_file.id, input_file.bytes)The purpose="batch" value matters. A file uploaded with another purpose, such as "assistants", is not accepted as batch input. Open the file in binary mode ("rb"). The with block closes the handle after the upload. The shorter form file=open(...) works, but it leaves the handle open.
The upload does not check your requests. Validation happens when you create the batch.
Step 2: Create the batch
batch = client.batches.create(
input_file_id=input_file.id,
endpoint="/v1/chat/completions",
completion_window="24h",
metadata={"job": "summaries-pilot", "source": "docs-v3"},
)
print(batch.id, batch.status)The arguments mean the following:
| Argument | Meaning |
|---|---|
| `input_file_id` | The ID returned by the upload. |
| `endpoint` | The API endpoint every request in the file targets. It must match the `url` field on every line. |
| `completion_window` | How long the service has to finish the batch. `"24h"` is the only value the API accepts. |
| `metadata` | Optional key-value strings stored with the batch. |
A batch targets exactly one endpoint. If your file has lines with /v1/chat/completions and lines with /v1/embeddings, the batch is invalid. Split them into two files and two batches.
Use metadata to store your own job name or the hash of the input file. The batch object is the only record the provider keeps of the job. A label there lets you find the batch later with client.batches.list() if your process crashes before you save the ID.
Save batch.id to durable storage right after this call returns. A local file or a database row is enough. If you lose the ID, you must hunt for the batch in the list.
Step 3: Understand the statuses
Right after creation the status is usually validating. The service checks that the file parses and that each line has the required fields. It also checks the endpoint match and the size limits. After that the batch moves through a small set of states.
validating: the input file is being checked.failed: validation rejected the file. No request ran. The reasons are inbatch.errors.in_progress: requests are being run.finalizing: all requests have been handled and the output files are being prepared.completed: the batch is done and the output file is ready.expired: the completion window passed before every request finished.cancellingandcancelled: you asked to stop, and the service is winding the batch down.
The final states are completed, failed, expired, and cancelled. Treat anything else as "still working".
Final does not mean successful. A completed batch can still contain individual requests that failed. An expired batch can contain many finished results. Each final state needs its own handling, which the next chapter covers.
Step 4: Poll for completion
The simplest loop retrieves the batch on a fixed interval until the status is final.
import time
FINAL = {"completed", "failed", "expired", "cancelled"}
while batch.status not in FINAL:
time.sleep(60)
batch = client.batches.retrieve(batch.id)
print(batch.status, batch.request_counts)The request_counts field has three numbers: total, completed, and failed. Here, "completed" means requests that returned a response. The count of failed means requests that produced an error. The two add up to total only when the job is done. While it runs, completed + failed shows progress.
A loop meant for real use needs three more things: a growing interval, a progress log, and a time limit. Here it is as a reusable function:
import time
from openai import OpenAI
client = OpenAI()
FINAL = {"completed", "failed", "expired", "cancelled"}
def wait_for_batch(batch_id, first_delay=30, max_delay=300, timeout=26 * 3600):
"""Poll a batch until it reaches a final status or the timeout passes."""
start = time.monotonic()
delay = first_delay
while True:
batch = client.batches.retrieve(batch_id)
counts = batch.request_counts
print(
f"{batch.id} {batch.status} "
f"done={counts.completed + counts.failed}/{counts.total}"
)
if batch.status in FINAL:
return batch
if time.monotonic() - start > timeout:
raise TimeoutError(f"{batch_id} still {batch.status} after {timeout}s")
time.sleep(delay)
delay = min(delay * 2, max_delay)The function backs off from 30 seconds up to 5 minutes. Batches commonly take minutes to hours, so polling every second wastes calls and gains nothing. The timeout is set a little beyond the 24-hour window. By then the status should have become expired. If it has not, something is wrong, and you should raise an error instead of waiting forever.
Retrieving a batch is a cheap metadata call. It does not run any model requests, and it does not add to your token cost.
What validation errors look like
If the status becomes failed, read batch.errors. It holds a list of error entries. Each has a code, a message, and often the line number of the bad request. Typical causes are:
- A line that is not valid JSON.
- A missing
custom_id, or the samecustom_idused twice. - A
urlon a line that differs from the batch'sendpoint. - A file larger than the allowed size, or more requests than the allowed count.
batch = wait_for_batch(batch.id)
if batch.status == "failed":
for err in batch.errors.data:
print(err.line, err.code, err.message)
raise SystemExit("Fix the input file and resubmit.")Fix the file, upload it again, and create a new batch. A failed batch cannot be restarted.
Cancelling a batch
batch = client.batches.cancel(batch.id)
print(batch.status) # "cancelling"Cancellation is not instant. The batch sits in cancelling for up to several minutes while in-flight requests are stopped. After that it becomes cancelled. Requests that finished before the cancel keep their results in the output file, and you are billed for them. Poll until the status is cancelled before you assume that nothing is still running.
Common mistakes
- Wrong purpose. Uploading with the default or another purpose gives an error at batch creation. Always pass
purpose="batch". - Endpoint mismatch. The
endpointargument and every line'surlmust be identical strings. A missing/v1prefix is the usual cause. - Polling too fast. A tight loop can hit your rate limit on the retrieve endpoint. Use a delay of 30 seconds or more.
- Treating
completedas all-success. Checkrequest_counts.failedanderror_file_idbefore using the results. - Losing the batch ID. Store it first, then poll.
- Mixing models or endpoints in one file. Each batch is tied to one endpoint, and some providers also restrict a batch to one model. Split the file when in doubt.
Putting it together
This script submits a file and waits, with the crash-safe habits above.
import json
import time
from openai import OpenAI
client = OpenAI()
FINAL = {"completed", "failed", "expired", "cancelled"}
with open("batch_input.jsonl", "rb") as f:
input_file = client.files.create(file=f, purpose="batch")
batch = client.batches.create(
input_file_id=input_file.id,
endpoint="/v1/chat/completions",
completion_window="24h",
metadata={"job": "summaries-pilot"},
)
with open("batch_state.json", "w", encoding="utf-8") as f:
json.dump({"batch_id": batch.id, "input_file_id": input_file.id}, f)
delay = 30
while batch.status not in FINAL:
time.sleep(delay)
delay = min(delay * 2, 300)
batch = client.batches.retrieve(batch.id)
c = batch.request_counts
print(batch.status, c.completed, c.failed, c.total)
print("final status:", batch.status)
print("output file:", batch.output_file_id, "error file:", batch.error_file_id)The two file IDs printed at the end are what the next chapter reads. Either one can be None. A batch with no failures has no error file, and a batch where every request failed may have no output file.
Exercise
Your polling script reports status in_progress after 25 hours, and a colleague suggests creating a new batch from the same input file to save time. What should you do first, and why?
Show answer
Retrieve the original batch again and check whether it has moved to a final status. A 24-hour window means the service should mark the batch expired at that point, and an expired batch still returns results for the requests that finished. Creating a second batch now would run every request twice and bill you for both runs. Once the first batch is final, read its output and error files, find the custom_ids with no result, and submit only those in a new batch.
Exercise
A batch you created goes straight to failed. Which field do you read to find out why, and what do you do next?
Show answer
Read batch.errors, which lists error entries with a code, a message, and usually a line number. Fix the input file (for example a duplicate custom_id or a url that does not match the batch endpoint), upload it again with purpose "batch", and create a new batch. A failed batch cannot be restarted.