Skip to content

Batches

Last updated: 2026-11-27T00:33:10-03:00 (UTC-3)

Send thousands of requests in one file and get the results later, in the OpenAI Batch API format. By default the gateway runs each line itself, within the same limits, logs and ledger as a normal call, so batches work with any provider, not just OpenAI. Flag: batches, which requires PostgreSQL.

To pay the provider’s batch price instead (about half the standard one at OpenAI, Anthropic, Google and AWS), let the gateway send the file to the provider’s own batch API: see Provider batches.

The key needs the batches:write scope and the scope of the batch’s route (for example route:chat). Interactive reference at /docs/swagger/, tag Files and batches.

client = openai.OpenAI(api_key=KEY, base_url="https://gateway.example.com/v1")
f = client.files.create(file=open("requests.jsonl", "rb"), purpose="batch")
b = client.batches.create(input_file_id=f.id, endpoint="/v1/chat/completions", completion_window="24h")
# ... when b.status == "completed":
results = client.files.content(b.output_file_id).text

Each line of the file follows the OpenAI format:

{"custom_id": "q1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "<alias>", "messages": [...]}}
Aspect How it works
Endpoints /v1/chat/completions, /v1/embeddings and /v1/responses, one per file
Limits 50 MiB and 10,000 lines
Validation On upload: the whole file is rejected with the number of the line that failed
Execution By the gateway itself, two lines at a time, within the admission limits. Each line appears in the logs and the ledger with the principal batch:<id>
Replicas One replica runs a batch at a time, under a lease in PostgreSQL renewed every 15 s; a replica runs at most 16 batches and evaluation runs at once. Every 30 s each replica takes over open batches whose lease is free or expired (a replica that stopped or crashed), so none waits for a restart. Cancelling on any replica stops the one running it within one renewal
Drain and failures On shutdown the replica stops sending new lines, lets the lines in flight finish within the shutdown deadline and releases the batch to another replica; lines not sent stay pending, never failed. A result the database cannot store is retried, and if it still fails the line stays pending and the batch resumes later instead of reporting a paid answer as failed
Output output_file_id for the lines that succeeded and error_file_id for the ones that failed, in the OpenAI line format. Files expire after 30 days
Security Files and batches belong to the key’s team; another team gets 404. Revoking the key stops its batches
Console Batches shows progress and lets you cancel

By default POST /v1/files reads the whole file into memory (up to 50 MiB) before it checks and stores it, so a replica needs about three times the file size in memory per upload in flight. With the operator flag streaming_file_uploads (off by default; requires batches), the file part streams into PostgreSQL instead:

  • Memory: the upload is stored in 1 MiB chunks as it arrives; it holds at most one chunk and one line (4 MiB at most), whatever the file size. A 40 MiB upload peaked at about 13 MiB of heap growth streamed, against 120 MiB buffered (TestStreamedFileUploadsPostgres).
  • Checks on the stream: the 50 MiB limit (413 request_too_large as soon as it is passed), UTF-8 for text files, and every batch and fine-tune line rule run while the bytes arrive, with the same answers as before. The purpose field may come before or after the file.
  • Nothing half-stored: the chunks are written in one transaction; a refused, cut or failed upload leaves no file and no chunk. Reading the file (/content, batches, evaluations, fine-tuning, vector stores) joins the chunks back in order; delete and expiry remove them.
  • Concurrency: a streamed upload keeps one database connection and transaction open while the client sends, so each replica streams at most 4 uploads at a time; another one answers 503 uploads_busy with Retry-After: 5, leaving the connection pool to the request path.
  • Differences: a form with two file parts is refused (400 invalid_request) instead of keeping the last one, and a fine-tune file with a line longer than 4 MiB is refused (400 invalid_fine_tune_file).
  • Upgrade: migration 180 adds the chunked column (false for existing files) and the chunk table. Files uploaded with the flag on are readable only by this version or later: before rolling back, turn the flag off and re-upload or delete them; an older binary also rejects the flag name.

With the operator flag message_batches (off by default; requires batches and anthropic_messages), the gateway also serves the Anthropic Message Batches API at /v1/messages/batches. The same engine runs it: each request goes through /v1/messages later, as the key that created the batch, so any provider behind the alias works (an OpenAI or Gemini target is translated as for a normal Messages call) and budgets, quotas, guardrails, the customer and the usage ledger apply per request. Provider-native batch discounts are not used.

client = anthropic.Anthropic(api_key=KEY, base_url="https://gateway.example.com")
batch = client.messages.batches.create(requests=[
{"custom_id": "q1", "params": {"model": "<alias>", "max_tokens": 256, "messages": [{"role": "user", "content": "Hello"}]}},
])
# ... when client.messages.batches.retrieve(batch.id).processing_status == "ended":
for line in client.messages.batches.results(batch.id):
print(line.custom_id, line.result.type)
Operation Route
Create POST /v1/messages/batches with {"requests": [{"custom_id", "params"}]}
Retrieve GET /v1/messages/batches/{id}
List GET /v1/messages/batches?limit=&after_id=&before_id= (newest first, limit 1–1000, default 20; has_more, first_id, last_id)
Cancel POST /v1/messages/batches/{id}/cancel
Results GET /v1/messages/batches/{id}/results (JSON Lines)
Delete DELETE /v1/messages/batches/{id} (only once ended)
  • Key: scopes batches:write and route:messages (or route:*); with plan entitlements, the team plan needs batches and anthropic_messages. Batches belong to the key’s team: another team, and /v1/batches, get 404 for a message batch, and GET /v1/batches never lists one.
  • Requests: 1 to 10,000 in a body of up to 50 MiB. custom_id is 1–64 letters, digits, _ or -, unique in the batch. params is a Messages request with model, max_tokens and messages, without stream, on an alias the key may use with the messages capability (an organization alias is refused, as for /v1/batches). The whole batch is refused with the index of the first bad request.
  • Object: id (msgbatch_…), type: message_batch, processing_status (in_progress, canceling or ended), request_counts (processing, succeeded, errored, canceled, expired), created_at, expires_at (24 hours), ended_at, cancel_initiated_at, archived_at (always null) and results_url. results_url is a path on the gateway (/v1/messages/batches/{id}/results), which a client joins to the base URL it already uses; it is never built from the request’s Host.
  • Results: one line per request, in request order, streamed a page at a time: {"custom_id": "q1", "result": {"type": "succeeded", "message": {...}}}; {"type": "errored", "error": {"type": "error", "error": {"type": "invalid_request_error", "message": "..."}}} (an Anthropic error from the provider is kept as it came; a gateway refusal is translated, with its gateway code in error.code); {"type": "canceled"} after a cancel; {"type": "expired"} after the 24-hour window. Before the batch ends the route answers 409 batch_not_ended.
  • Cancel: the batch ends at once; requests already answered keep their results.
  • Retention: results are kept 29 days after creation, then cleared by the hourly purge (404 results_expired after that); the batch itself stays readable until deleted. Delete removes the batch, its requests and results and its input file; usage events and ledger rows stay.
  • Execution, replicas, drain and revocation: exactly as for /v1/batches above (leases, two requests at a time, resume after a crash, the key’s revocation stops the batch).
  • Console: Batches lists message batches beside the others, with endpoint /v1/messages, and cancels them.
  • Upgrade: no migration. An older binary refuses the flag name and cannot run or read message batches: before rolling back, let them end (or cancel them) and remove the flag.

With the operator flag provider_batches (off by default; requires batches), a file whose lines all name aliases marked batch: provider is sent to that provider’s own batch API, at the provider’s batch price, instead of being run line by line. Clients change nothing: they use /v1/batches and /v1/messages/batches as above and get the same result file.

Provider (protocol) Batch API used Extra setup
OpenAI (openai) Batch API: the file is uploaded with purpose: batch, then POST /batches None
Anthropic (anthropic) Message Batches API None
Gemini API (gemini) Batch mode with inline requests (models/{model}:batchGenerateContent), up to 20 MB per batch None
Vertex AI (gemini with a Vertex base_url) Batch prediction jobs, input and output in Cloud Storage providers[].batch.input_uri and output_uri (gs://bucket/prefix); the service account needs storage.objects.create on the input bucket, storage.objects.list and get on the output bucket, and aiplatform.batchPredictionJobs.create, get and cancel
Bedrock (bedrock) Batch inference jobs (CreateModelInvocationJob, Converse format), input and output in S3 providers[].batch.input_uri, output_uri (s3://bucket/prefix) and role_arn (the service role the job runs as, with read on the input and write on the output prefix); the gateway’s own identity needs s3:PutObject, s3:ListBucket, s3:GetObject, bedrock:CreateModelInvocationJob, GetModelInvocationJob, StopModelInvocationJob and iam:PassRole on the role
  1. Turn on provider_batches (and batches).
  2. Mark each alias that should use the provider’s batch API. The alias needs exactly one target, of a provider in the table, and no auto route, canary, affinity, latency or adaptive routing or fallbacks: a provider batch has no routing choice and no fallback.
  3. For Vertex AI and Bedrock, give the provider its storage.
  4. With budgets on, give the approved quota rate a batch tier (quotas.rates[].service_tiers.batch), and for valuation the price book or catalog a batch price. Without it the file is refused before upload, because its lines cannot be held at a known price.
features:
batches: true
provider_batches: true
provider_batches:
poll_seconds: 60 # how often an open provider batch is asked about
max_wait_hours: 48 # how long after upload the gateway waits for it to end
on_failure: none # none, or gateway: a provider job that fails as a whole runs line by line
models:
- id: nightly-summaries
batch: provider # gateway (default) runs each line itself
targets: [{provider: openai, model: gpt-5.4-mini}]
providers:
- id: bedrock-east
protocol: bedrock
base_url: https://bedrock-runtime.us-east-1.amazonaws.com
auth: {type: aws_sigv4, region: us-east-1}
batch:
input_uri: s3://acme-batches/in
output_uri: s3://acme-batches/out
role_arn: arn:aws:iam::111122223333:role/bedrock-batch
Field Default Bounds and rules
models[].batch gateway (also empty) gateway or provider
provider_batches.poll_seconds 60 5–3600
provider_batches.max_wait_hours 48 25–200, from the upload
provider_batches.on_failure none none or gateway
providers[].batch.input_uri none gs://bucket/prefix (Vertex AI) or s3://bucket/prefix (Bedrock); the input is written as <prefix>/<batch id>.jsonl
providers[].batch.output_uri none Same schemes; the provider writes under <prefix>/<batch id>/
providers[].batch.role_arn none Bedrock only, required: an IAM role ARN
providers[].batch.storage_url https://storage.googleapis.com or https://s3.<region>.amazonaws.com An http(s) origin, for a private endpoint
providers[].batch.control_url https://bedrock.<region>.amazonaws.com Bedrock only; an http(s) origin

The provider_batches block is boot configuration (restart to change). models[].batch and providers[].batch follow the model and provider configuration: the YAML, the admin API (PUT /models/{id}, PUT /providers/{id}, where an omitted batch keeps the stored storage and null clears it) and the console (Batches in the model editor, Batch storage in the provider editor).

  1. Mode. At creation the batch takes the provider mode when the flag is on and every model of the file is an alias marked batch: provider of one provider. A file that mixes such aliases with others, or two providers, is refused with 400 (split the file). Any other file runs line by line, as before.
  2. Staging, before anything is sent. Each line runs through the gateway’s normal pipeline up to the provider call: the key and its scopes, the mandatory system prompt, guardrails, request overrides, translation to the provider’s format and the budget and token admission. A line a guardrail blocks is refused there and is never sent; a guardrail that masks text changes what is uploaded. Each line’s worst case (its prompt and its max_tokens) is held on the budget at the batch tier’s approved price, and at least the standard one. Request rate limits (RPM, model rate limits) and token-per-minute or per-day ceilings do not apply to provider batch lines: they protect the provider’s synchronous capacity, which a provider batch does not use; budgets do. If the budget cannot hold the whole file, the batch ends failed (“the file’s worst case does not fit the remaining budget”) with every hold released, and nothing is uploaded.
  3. Upload. The staged lines go to the provider’s batch API in one upload, each under the gateway’s own key for the line (l<line>), never the client’s custom_id.
  4. Polling. A leased job asks the provider every poll_seconds. Between polls the batch holds no replica: any replica takes the next poll. If the replica polling it stops or crashes, another one takes over when its lease expires and keeps polling the same provider batch; nothing is uploaded twice.
  5. Results. When the provider batch ends, each line’s result is passed back through the pipeline as if the provider had just answered it: output guardrails, translation back to the OpenAI or Anthropic shape, the usage ledger and its valuation, all at the batch tier, and the line’s hold settles on its measured usage. The input guardrails are not run again (they ran before upload). The result file is the one the line-by-line engine writes.
  6. Nothing reaches a provider outside the batch API. Neither pass ever calls a provider: if the alias no longer routes to the batch’s provider (its target was changed), staging refuses the file, and a result is refused with provider_batch_route_changed and its hold kept for reconciliation, since the provider ran it. Lines the provider never ran (cancelled, expired) end with batch_cancelled or batch_expired and their holds are released.
  • Cancel: POST /v1/batches/{id}/cancel (or the Messages, or the console, route) answers cancelling. The gateway cancels the provider batch, collects the lines that already ran (they are paid, settled, and in the output file), releases the holds of the rest and ends the batch cancelled. A batch cancelled before or during staging is never uploaded and releases everything.
  • Expiry: the provider’s 24-hour window applies; an expired provider batch is collected the same way and ends expired, with the results of the lines that ran. A provider batch that never ends within max_wait_hours is cancelled at the provider and ends failed, and the holds of the lines not collected are kept as unknown for reconciliation: they may have run.
  • No fallback inside a provider batch. A line the provider answers with an error keeps that error (the provider bills no errored line, and its hold is released). A provider job refused before it ran (the upload refused, or OpenAI failing the file’s validation) releases every hold; with on_failure: gateway the file then runs line by line, otherwise the batch ends failed. A Gemini API, Vertex AI or Bedrock job that fails may have run some lines: what it returned is collected, the holds of the rest are kept as unknown, the batch ends failed, and it never runs line by line.
  • Uncertain upload: a replica that stops after starting the upload, before it recorded the provider batch, cannot know whether the provider created it. The batch ends failed and its holds are kept as unknown for reconciliation; it is never uploaded again. Bedrock is the exception: its create is deduplicated by a client request token (the batch ID), so the upload is resumed safely.
  • Flag turned off: a batch still staging runs line by line; one already uploaded is polled and collected to its end.
  • Only the line’s own call: a line whose pipeline would make any other provider call (another provider, or a read such as a Responses lookup) refuses the whole file before upload.
  • Cancel refused by the provider: the cancel is asked once; if the provider refuses it, the batch runs to its end there and what ran is collected and settled.
  • Kill switch: while the gateway’s kill switch is engaged, staging, upload and result replay pause; polling goes on.
  • Message batches: request_counts.canceled and expired count the requests the provider never ran.
  • The lines of a Gemini API, Vertex AI or Bedrock batch name one model (the provider runs one model per job), and the Gemini API takes at most 20 MB of inline requests. Beyond these, the upload is refused and on_failure applies.
  • Bedrock minimum: Bedrock batch inference takes at least 100 records per job (its default service quota, Minimum number of records per batch inference job). A smaller Bedrock file is refused before anything is uploaded, with a message naming the minimum and the file’s count (for example “takes at least 100 records per job …; this batch has 2”); every hold is released, and on_failure decides: none ends the batch failed, gateway runs it line by line. Send at least 100 lines to a Bedrock alias, or keep its batch at gateway for small files.
  • Result size: result files (OpenAI, Anthropic, Vertex AI, Bedrock) are read as a stream, one line at a time, and each line is replayed as soon as it is read, so a result file of any size is collected with bounded memory (a 650 MiB result file grew the gateway’s heap by about 40 MiB in TestProviderBatchStreamsLargeResultsWithPostgres). One result line may be up to 64 MiB. A Gemini API batch returns its results inline in the batch object, which is read whole, up to 512 MiB (its requests are at most 20 MB). A download cut short is resumed on the next attempt from the lines not yet stored.
  • Gemini API inline results carry the line key when the API returns it, and are matched in request order otherwise; Vertex AI results are matched by the key field written beside each request, or by the request they echo.

On 2026-11-27 a 2-line batch and a 2-line batch cancelled at once ran on the OpenAI Batch API (gpt-5.4-mini) and on the Gemini API batch mode (gemini-3.5-flash-lite). OpenAI’s output reports service_tier: "default" in each answer; the gateway values those lines at the batch tier anyway, since it knows they came through the Batch API. Gemini returns its inline results under response.inlinedResponses.inlinedResponses, each with the line’s metadata.key, and names its states BATCH_STATE_*. Both cancels ended cancelled with no line run and every hold released. Anthropic, Vertex AI and Bedrock are checked on stand-ins only so far. For Vertex AI, the project must have access to the Gemini models on Vertex AI: a project without it gets 404 The PublisherModel ... does not exist at the job create, after the input was uploaded; the batch then ends failed with every hold released. For Bedrock, the account must have batch inference enabled: an account without it gets 400 Your account is not authorized to perform this action at the job create (AWS enables it through a support case).

Migration 305 adds the batch’s mode, provider binding and phase, and each line’s hold and staged request. Existing batches keep the line-by-line mode. An older binary refuses the flag and field names and cannot resume a provider batch: before rolling back, let provider batches end (or cancel them) and remove the flag.

Every route below needs a console session or an admin Bearer token, the role’s permission and, for writes, the X-CSRF-Token header; the full contract is in the API reference.

Route What it does
GET /api/v1/admin/batches Lists the batches the gateway tracks, with their team, key and provider state; team roles see their teams
POST /api/v1/admin/batches/{id}/cancel Cancels a batch at its provider (global admin, or team admin of the batch’s team)

m7gtw[email protected]