Sub topic 7
Uploading, submitting, and polling a batch
This chapter assumes you can write basic Python with file I/O and JSON, have called a chat completions API before, and know what JSON Lines is. It also assumes you already have a request file like the one built in the previous chapter, batch_input.jsonl, with one request per line and a unique custom_id on each.
The three steps
Submitting a batch is a three-step process. Each step is a separate API call, and each returns an object with an id that the next step needs.
- Upload the JSONL file with the purpose
batch. The API returns a file ID. - Create the batch from that file ID. The API returns a batch ID and starts the job.
- Poll the batch by its ID until it reaches a terminal status.
Upload and create
The upload step stores your file on the provider's side. The purpose="batch" value matters. A file uploaded for another purpose cannot be used to create a batch.
from openai import OpenAI
client = OpenAI()
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",
)
print(batch.id, batch.status)Two arguments deserve attention:
endpointmust match theurlfield in every line of the file. If one line targets a different endpoint, that request is rejected.completion_windowis the longest time the provider may take. At the time of writing,"24h"is the only value the OpenAI API accepts. It is a deadline, not an estimate. Many batches finish much sooner.
The new batch usually starts in the validating status. The provider checks the file format before any request runs.
Polling for completion
A batch does not push a result to you. You ask for its state with client.batches.retrieve. Statuses fall into two groups.
| Status | Meaning | Terminal? |
|---|---|---|
| `validating` | The input file is being checked | No |
| `in_progress` | Requests are running | No |
| `finalizing` | Results are being written to files | No |
| `completed` | The job finished, though individual requests may have failed | Yes |
| `failed` | Validation failed, so no requests ran | Yes |
| `expired` | The window closed before all requests finished | Yes |
| `cancelling` | A cancel was requested and is in progress | No |
| `cancelled` | The batch was cancelled | Yes |
Here is a polling loop that waits for a terminal status and prints progress as it goes.
import time
TERMINAL = {"completed", "failed", "expired", "cancelled"}
def wait_for_batch(client, batch_id, interval=60):
batch = client.batches.retrieve(batch_id)
while batch.status not in TERMINAL:
counts = batch.request_counts
print(f"{batch.status}: {counts.completed}/{counts.total} done, {counts.failed} failed")
time.sleep(interval)
batch = client.batches.retrieve(batch_id)
return batch
batch = wait_for_batch(client, batch.id)
print(batch.status, batch.request_counts)A polling interval of one minute is reasonable. Batches take minutes to hours, so polling every second wastes calls and gains nothing.
Common errors
- A
failedstatus right after creation. The file did not pass validation. Typical causes are a line that is not valid JSON, a duplicatecustom_id, or aurlthat does not matchendpoint. Readbatch.errorsfor the reason. - Losing the batch ID. If your script stops while polling, the batch keeps running on the provider's side. Save
batch.idto disk right after creating it so you can resume polling instead of submitting again and paying twice. - Treating
expiredas total loss. An expired batch may still have an output file containing the requests that finished in time. Those can be kept, and only the rest need resubmitting. - Polling with no limit. A loop that never stops on a stuck job runs forever. In real code, add an overall deadline slightly beyond the completion window.
Exercise
Your script uploads a file, creates a batch, and crashes while polling. You rerun it from the top. What goes wrong, and how would you prevent it?
Show answer
The rerun uploads the file again and creates a second batch, so the same requests run twice and you pay for both. Prevent this by saving the batch ID to disk right after batches.create returns. On startup, check for a saved ID and, if one exists, skip upload and creation and go straight to polling that batch.
Exercise
A batch ends with status completed and request_counts of total=500, completed=480, failed=20. Is it safe to use the output file as is?
Show answer
No. The output file holds results for the successful requests, and the 20 failed ones need separate handling through the error file. Match results by custom_id, identify the failed IDs, and resubmit only those.