Skip to main content

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​

  1. Configure the provider credentials for files and batches. In config.yaml add a files_settings entry per provider, or turn on managed files so uploads use the deployments in model_list.

    files_settings:
    - custom_llm_provider: openai
    api_key: os.environ/OPENAI_API_KEY
  2. 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.

  3. Upload the input file with purpose: batch. The model in 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"
  4. 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"}}'
  5. 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
  6. 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.

  1. A managed input file carries its model, so the batch runs where the file was uploaded. See managed files.
  2. The model field in the body, the model query parameter or the x-spanway-model header names a model from model_list. With spanway_settings.enable_loadbalancing_on_batch_endpoints: true the gateway also load balances the batch across that model's deployments.
  3. Otherwise custom_llm_provider in the body, the /{provider}/v1/batches path or the custom-llm-provider header names a provider in files_settings.
  4. With none of these, the gateway uses openai. When no OpenAI key is configured either, the create call answers 404 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.

SettingWhereDefaultWhat it does
enable_loadbalancing_on_batch_endpointsspanway_settingsoffOn 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_filesspanway_settingsfalseOn 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_daygeneral_settings, key or team metadataunsetPer key limits, see Limits.
tpd_limit on a teamthe teamunsetTokens 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/files with purpose=batch and either the x-spanway-model header or the target_model_names form 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 answers 400 Spanway-executed batches need a database.
  • SPANWAY_EXECUTED_BATCH_CONCURRENCY (environment variable, default 4) 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 with general_settings.track_unmanaged_batch_cost: true.
  • The job runs every general_settings.proxy_batch_polling_interval seconds (environment variable PROXY_BATCH_POLLING_INTERVAL, default 3600), so the cost can appear up to about an hour after the batch completes. Each run looks at up to MAX_OBJECTS_PER_POLL_CYCLE batches (default 50).
  • Batches still open after MANAGED_OBJECT_STALENESS_CUTOFF_DAYS days (default 7) are marked stale and no longer polled.
  • PROXY_BATCH_POLLING_ENABLED=false turns 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 typeMessageFix
400 invalid_request_error (BadRequestError) on uploadInvalid 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 createExpected 1 model, got <n>Name one model in target_model_names.
400 on createBatches 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 createSpanway-executed batches need a database: set DATABASE_URL so Spanway can keep the batch and its filesConnect 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 cancelRaw provider batch ids cannot be used when require_managed_files is enabled ...Use the id the gateway returned.
400 on retrieve or cancelInvalid Spanway managed batch ID. Missing model_id.The id was changed or truncated. Use the id the gateway returned.
400 on cancelCannot cancel a batch with status '<status>'The batch already finished. Nothing to cancel.
400 on listInvalid '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 foundNo 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_errorBatch 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_exceededBudget 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.
500Server 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​

LevelLineMeaningAction
WARNINGbatch <id> no longer exists at the provider, retiring itThe cost job found a batch the provider deleted. It stops polling it.None.
WARNINGCheckBatchCost 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.
WARNINGCheckBatchCost could not settle batch <id>: <error>The cost was computed but could not be written to the database.Check the database.
WARNINGmanaged batch <id> carries no model_id, retiring itA stored batch has no model, so it cannot be costed.None, the batch is skipped.
INFOCheckBatchCost marked <n> batches older than <date> staleBatches past MANAGED_OBJECT_STALENESS_CUTOFF_DAYS are no longer polled.None.
WARNINGSpanway-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.

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.