Batches
The batch API processes a file of many requests asynchronously at a lower price than real time calls. You upload a JSONL file with one request per line, create a batch that points at it, poll the batch until it completes, and download the output file. The gateway serves the OpenAI batches and files formats for OpenAI, Azure OpenAI, Bedrock, Vertex AI and other providers with batch support, and attributes the cost of completed batches to the key that created them, so overnight jobs show up in the same budgets as interactive traffic.
Scenario
A data team classifies a million support tickets once a quarter. Real time calls would be slow and expensive, so the team writes the requests to a JSONL file, uploads it through the gateway and creates a batch with a 24 hour window. The next morning the batch is complete, the team downloads the results, and the Usage page shows the batch's cost under the team's key with the batch id in the metadata.
Steps
-
Configure the provider credentials for files and batches. In
config.yamladd afiles_settingsentry per provider, or turn on managed files so uploads use the deployments inmodel_list.files_settings:- custom_llm_provider: openaiapi_key: os.environ/OPENAI_API_KEY -
Create a key in Virtual Keys (
/ui/api-keys) with + Create New Key and pick the models the batch will use under Models. When several providers are configured, plan how the batch is routed, see routing a batch to a model. -
Upload the input file with
purpose: batch. Themodelin each line of the file decides where the batch runs.curl -X POST http://localhost:4000/v1/files \-H "Authorization: Bearer $SPANWAY_API_KEY" \-F "purpose=batch" \-F "file=@requests.jsonl" -
Create the batch with the returned file id.
curl -X POST http://localhost:4000/v1/batches \-H "Authorization: Bearer $SPANWAY_API_KEY" -H "Content-Type: application/json" \-d '{"input_file_id": "file-abc123", "endpoint": "/v1/chat/completions", "completion_window": "24h", "metadata": {"job": "nightly-summaries"}}' -
Poll the batch and download the output when it is complete.
curl http://localhost:4000/v1/batches/batch_7c2d4e1f -H "Authorization: Bearer $SPANWAY_API_KEY"curl http://localhost:4000/v1/files/file-out456/content -H "Authorization: Bearer $SPANWAY_API_KEY" --output results.jsonl -
Check the spend. Open Logs (
/ui/logs) and filter by the key. Batch rows show the batch id, and Usage (/ui/usage) shows the cost under the key.
Expected result
{
"id": "batch_7c2d4e1f",
"object": "batch",
"endpoint": "/v1/chat/completions",
"input_file_id": "file-abc123",
"completion_window": "24h",
"status": "validating",
"created_at": 1760441234,
"request_counts": {"total": 0, "completed": 0, "failed": 0},
"metadata": {"job": "nightly-summaries"}
}
A batch has a status of validating, in_progress, finalizing, completed, failed, expired, cancelling or cancelled, with request_counts and output_file_id once done. POST /v1/batches/{batch_id}/cancel stops a running batch, which first shows cancelling and then cancelled. Creating and cancelling a batch is written to the audit log as a batch:<id> row with the caller, never the file content.
Routing a batch to a model
A batch runs on one provider account. The gateway picks it in this order.
- A managed input file carries its model, so the batch runs where the file was uploaded. See managed files.
- The
modelfield in the body, themodelquery parameter or thex-spanway-modelheader names a model frommodel_list. Withspanway_settings.enable_loadbalancing_on_batch_endpoints: truethe gateway also load balances the batch across that model's deployments. - Otherwise
custom_llm_providerin the body, the/{provider}/v1/batchespath or thecustom-llm-providerheader names a provider infiles_settings. - With none of these, the gateway uses
openai. When no OpenAI key is configured either, the create call answers404 No such File object: <input_file_id>, so name the model or the provider.
GET /v1/batches lists one account at a time in the same way, with target_model_names naming a model instead of a provider.
| Setting | Where | Default | What it does |
|---|---|---|---|
enable_loadbalancing_on_batch_endpoints | spanway_settings | off | On spreads batches for a model across all of its deployments, which helps when one provider account has a low batch quota. Off sends a batch to the provider named in the request. |
require_managed_files | spanway_settings | false | On refuses raw provider file and batch ids with a 400, so every batch goes through a managed file the gateway can check the owner of. Turn it on when several teams share the gateway. |
max_batch_file_records, max_batch_file_uploads_per_day | general_settings, key or team metadata | unset | Per key limits, see Limits. |
tpd_limit on a team | the team | unset | Tokens per day across the team's batch submissions, see budgets. |
Batches that run inside the gateway
Some models have no provider batch API, for example a self-hosted vLLM server (hosted_vllm/ models). For those the gateway runs the batch itself: it reads the input file, sends each line as a normal request to the model with the same key, and writes the output file when every line is done, so the client sees the same OpenAI batch flow.
- The input file must be a managed file. Upload it through
POST /v1/fileswithpurpose=batchand either thex-spanway-modelheader or thetarget_model_namesform field naming the model. - The gateway needs its database (
DATABASE_URL), because it keeps the batch and its files there. Without it the create call answers400 Spanway-executed batches need a database. SPANWAY_EXECUTED_BATCH_CONCURRENCY(environment variable, default4) is how many lines of one batch run at the same time. Raise it to finish faster, lower it to put less load on the model server.- The replica that runs a batch writes a heartbeat every 30 seconds. When no heartbeat arrives for 180 seconds, for example because the replica restarted, the batch fails with
the proxy replica running this batch stopped before it finished; resubmit the batch. Resubmit it.
Team batch output expiry
A proxy admin can make every batch output file of a team expire. In Teams (/ui/teams), click the team, open its Settings tab, click Edit Settings and set Batch Output Expiry (seconds). The same field is on the + Create New Team form. The gateway then adds output_expires_after with anchor: created_at and that number of seconds to every batch the team's keys create, so result files with customer data do not stay at the provider longer than your retention rule allows. Leave it empty to keep the provider's default. The value is stored in team metadata as enforced_batch_output_expires_after. A malformed value makes batch creation fail with a 500 Server configuration error that names the field, see Errors.
Endpoints
{{ops:^/v1/batches|^/v1/files(/{file_id}(/content)?)?$}}
Provider configuration
files_settings lists the provider credentials used for file uploads and batches. Alternatively, with managed files on, the gateway stores a mapping from its own file ids to provider file ids per deployment, so a file uploaded once can be used with any model and only its owner can read it. See managed files.
Cost tracking
A background job records what each finished batch cost against the key, user and team that created it, so batch spend appears in budgets and reports with the batch id in the metadata.
- Batches created through a managed file, or with a model from
model_list, are costed by default. A batch created with a raw provider id is costed only withgeneral_settings.track_unmanaged_batch_cost: true. - The job runs every
general_settings.proxy_batch_polling_intervalseconds (environment variablePROXY_BATCH_POLLING_INTERVAL, default3600), so the cost can appear up to about an hour after the batch completes. Each run looks at up toMAX_OBJECTS_PER_POLL_CYCLEbatches (default50). - Batches still open after
MANAGED_OBJECT_STALENESS_CUTOFF_DAYSdays (default7) are marked stale and no longer polled. PROXY_BATCH_POLLING_ENABLED=falseturns the job off, which saves database load on a gateway that runs no batches, but then batch spend is never recorded.- The job is part of the enterprise package, so it runs on a licensed gateway.
Limits
general_settings.max_batch_file_size_mb caps the size of every batch input file on the gateway. max_batch_file_records and max_batch_file_uploads_per_day apply per key, and key or team metadata can carry its own value that overrides them. allowed_file_extensions restricts upload types. For in-process parallel calls without a provider batch API, see batching completions.
Errors
The body of every error is {"error": {"message", "type", "param", "code"}}. The type column shows error.type, and the SDK raises the class in brackets. The error reference lists the same errors.
| Status and type | Message | Fix |
|---|---|---|
400 invalid_request_error (BadRequestError) on upload | Invalid file format for Batch API: '<name>'. Batch input files must be .jsonl files., Batch input file has no request lines., Batch input file line <n> is not valid JSON., Batch input file line <n> must be a JSON object. or Missing required parameter: '<key>' (batch input file line <n>). | Fix the file. Nothing was sent to the provider. |
400 invalid_request_error on create | /batches: Missing required parameter: 'completion_window'. (or input_file_id, endpoint) | Send all three fields. completion_window is always 24h. |
| 400 on create | Expected 1 model, got <n> | Name one model in target_model_names. |
| 400 on create | Batches for <model> run inside Spanway, so the input file must be a Spanway managed file: ... | Upload the file with the model named, see batches that run inside the gateway. |
| 400 on create | Spanway-executed batches need a database: set DATABASE_URL so Spanway can keep the batch and its files | Connect the database. |
| 400 on create | <destination> uses model '<model>', which fails the data policy: <reason> | The key's data policy refuses the model. Use a model that meets it. |
| 400 on retrieve or cancel | Raw provider batch ids cannot be used when require_managed_files is enabled ... | Use the id the gateway returned. |
| 400 on retrieve or cancel | Invalid Spanway managed batch ID. Missing model_id. | The id was changed or truncated. Use the id the gateway returned. |
| 400 on cancel | Cannot cancel a batch with status '<status>' | The batch already finished. Nothing to cancel. |
| 400 on list | Invalid 'limit': integer above maximum value ... | Send limit from 0 to 100. |
403 permission_error (PermissionDeniedError) | With managed files, the key does not own the input file, or may not use the models in it. | Upload with the same key, or add the models to the key. |
404 invalid_request_error (NotFoundError) | No such File object: <id> on create, No batch found with id '<id>'. or Batch <id> not found | No model or provider was named and no OpenAI key exists, or the id is unknown. Name the model or provider, see routing, or use the id the gateway returned. |
413 invalid_request_error | Batch input file is <n> MB, which exceeds the configured max_batch_file_size_mb of <m> MB. or Batch input file has more than <n> records, which exceeds the max_batch_file_records of <n> set <source>. | Split the file or raise the limit. |
422 budget_exceeded | Budget has been exceeded! ... | The key, team or user is over budget. Raise the budget or wait for its reset. spanway_settings.budget_exceeded_status_code: 429 returns 429 instead, see error reference. |
429 rate_limit_error (RateLimitError) | Batch file upload limit reached, the file was not forwarded to the provider: max_batch_file_uploads_per_day is <n> for <scope> ... | Wait for the reset at 00:00 UTC or raise the limit. |
| 500 | Server configuration error: team metadata field 'enforced_batch_output_expires_after' is malformed ... or ... has invalid anchor ... | A proxy admin fixes Batch Output Expiry (seconds) on the team, see team batch output expiry. |
Logs
| Level | Line | Meaning | Action |
|---|---|---|---|
| WARNING | batch <id> no longer exists at the provider, retiring it | The cost job found a batch the provider deleted. It stops polling it. | None. |
| WARNING | CheckBatchCost could not retrieve batch <id>: <error> | The cost job could not read the batch from the provider. It tries again on the next run. | Check the provider credentials when it repeats. |
| WARNING | CheckBatchCost could not settle batch <id>: <error> | The cost was computed but could not be written to the database. | Check the database. |
| WARNING | managed batch <id> carries no model_id, retiring it | A stored batch has no model, so it cannot be costed. | None, the batch is skipped. |
| INFO | CheckBatchCost marked <n> batches older than <date> stale | Batches past MANAGED_OBJECT_STALENESS_CUTOFF_DAYS are no longer polled. | None. |
| WARNING | Spanway-executed batch <id> heartbeat failed: <error> | A batch running inside the gateway could not record its heartbeat. After 180 seconds without one, the batch fails as stopped. | Check the database. |
Related
- Managed files for owner checks and provider mapping.
- Batching completions for concurrent real time calls.
- Fine-tuning, which also uses the files API.
Providers
The gateway's endpoint support matrix marks 12 provider integrations as supporting this endpoint:
Anthropic, Anthropic Text, Azure, Azure AI, Azure Text, Custom OpenAI (custom_openai), Hosted VLLM, Mistral AI API, Oobabooga (oobabooga), OpenAI, Text Completion OpenAI, VLLM.