# Batch

The Batch API runs a file of requests asynchronously at a lower price than the
synchronous API. You choose a completion window of 24, 48 or 72 hours; results
are produced within it when capacity allows, and requests not finished when it
ends expire (`batch_expired`) and are not billed. It is compatible with the
OpenAI Batch API and with OVHcloud AI Endpoints' batch mode: the unmodified
`openai` SDK works against it with only the base URL and the API key changed.

Use it for work that does not need an answer now: evaluations, embeddings
over a corpus, classification or extraction over many documents.

The Batch API is available to every organisation. If uploading a file or
creating a batch answers `403 feature_disabled`, support has turned it off for
your organisation: contact support.

## Quickstart (Python `openai` SDK)

1. Write one request per line to a JSONL file, `requests.jsonl`:

```jsonl
{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemma-4-26b-a4b", "messages": [{"role": "user", "content": "Say hello in one sentence."}], "max_tokens": 100}}
{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemma-4-26b-a4b", "messages": [{"role": "user", "content": "Name three primary colours."}], "max_tokens": 100}}
```

2. Upload it, create the batch, wait for it, and read the results:

```python
import json
import time

from openai import OpenAI

client = OpenAI(base_url="https://api.models.blade.sh/v1", api_key="sk-blade-...")

batch_input = client.files.create(file=open("requests.jsonl", "rb"), purpose="batch")

batch = client.batches.create(
    input_file_id=batch_input.id,
    endpoint="/v1/chat/completions",
    completion_window="24h",
)

while batch.status not in ("completed", "failed", "expired", "cancelled"):
    time.sleep(60)
    batch = client.batches.retrieve(batch.id)

if batch.output_file_id:
    for line in client.files.content(batch.output_file_id).text.splitlines():
        result = json.loads(line)
        print(result["custom_id"], result["response"]["body"]["choices"][0]["message"]["content"])

if batch.error_file_id:
    for line in client.files.content(batch.error_file_id).text.splitlines():
        result = json.loads(line)
        print(result["custom_id"], result["error"]["code"], result["error"]["message"])
```

Results are not in input order: match them to your requests by `custom_id`.

The same flow with `curl`:

```bash
curl https://api.models.blade.sh/v1/files \
  -H "Authorization: Bearer $BLADE_API_KEY" \
  -F purpose=batch \
  -F file=@requests.jsonl

curl https://api.models.blade.sh/v1/batches \
  -H "Authorization: Bearer $BLADE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"input_file_id": "file-...", "endpoint": "/v1/chat/completions", "completion_window": "24h"}'

curl https://api.models.blade.sh/v1/batches/batch_... \
  -H "Authorization: Bearer $BLADE_API_KEY"

curl https://api.models.blade.sh/v1/files/file-.../content \
  -H "Authorization: Bearer $BLADE_API_KEY" \
  -o results.jsonl
```

## Input file

Each non-blank line of the file is one request:

```json
{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemma-4-26b-a4b", "messages": [{"role": "user", "content": "Hello"}]}}
```

| Field | Rule |
|---|---|
| `custom_id` | A non-empty string, unique within the file. It is how you match a result to its request. |
| `method` | `"POST"`. |
| `url` | One of `/v1/chat/completions`, `/v1/completions`, `/v1/embeddings`, `/v1/responses`, `/v1/audio/transcriptions`, `/v1/images/generations`. |
| `body` | The JSON body you would send to that endpoint synchronously, with its `model`. `stream: true` is refused. |

- The model must be a shared catalogue model that takes batch work: text chat
  models on the three chat endpoints, text embedding models on
  `/v1/embeddings`, and the OCR, transcription and image models that take
  batch work on the lines below.
  `/v1/models` shows `batch.enabled` for each model, and `batch.endpoints` the
  batch endpoints a line naming it may target.
  Dedicated endpoints (`ded/...`) are not available in batches.
- Models hosted by an external provider (`gpt-oss-120b`, served by OVHcloud AI
  Endpoints) take batch lines too, with these rules:
  - Your organisation must have enabled external providers; otherwise each
    line naming such a model fails validation with
    `external_provider_not_enabled`.
  - Only `/v1/chat/completions` lines; other endpoints are refused
    (`endpoint_not_batchable`). The lines for one such model may total at most
    190 MiB (`provider_input_too_large`).
  - We forward those lines to the provider's own batch service, which runs a
    limited number of batches at once. While they wait for a slot, the batch
    shows `paused_reason: "provider_queue"`. Lines the provider cannot start
    before the completion window ends expire unbilled (`batch_expired`).
  - OVHcloud AI Endpoints stores the forwarded lines and their results until
    we have read the results back; we then delete them at OVHcloud. Each
    output line carries the same `routing` block as a synchronous response.
- On every endpoint, a line may only use function tools
  (`"type": "function"`). Built-in (server) tools such as `web_search`,
  `web_fetch` or `code_interpreter`, `web_search_options` and the `web_search`
  flag are refused (`tool_not_supported_in_batch`). On `/v1/responses`, `store: true` and
  `previous_response_id` are refused too, as on the synchronous route.
- Each body is held to the same size limit as a synchronous request.
- The upload checks the file's UTF-8 and JSONL shape, **not images embedded inside a
  line's `body`**. A multimodal image in an eligible chat/Responses line is
  validated, fetched through the egress guard if it is a URL, and re-encoded
  without metadata **when the line executes**, through the same gateway path as
  a synchronous request. Bad images fail that line with `invalid_image` (400);
  they do not make the entire upload invalid. Image limits: 8 MB, 40 MP, at
  most 8 remotely fetched images per request.


### Mixing models and endpoints

One file may mix models and endpoints. For example, a chat request on one
model and a text completion on another can go in the same batch:

```jsonl
{"custom_id": "chat-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemma-4-26b-a4b", "messages": [{"role": "user", "content": "Summarise: the cat sat on the mat."}]}}
{"custom_id": "complete-1", "method": "POST", "url": "/v1/completions", "body": {"model": "mistral-small-24b", "prompt": "The cat sat on the", "max_tokens": 20}}
```

The `endpoint` you pass to `batches.create` is still required (the SDK
requires it) and is echoed back on the batch, but each line runs on its own
`url`. Each line is priced at its own model's batch price.

Media lines (the OCR, transcription and image generation lines below) are
available to every organisation. If support has turned them off for yours, a line on
`/v1/audio/transcriptions` or `/v1/images/generations` fails validation with
`endpoint_not_batchable`, and a line naming an OCR, transcription or image
model fails with `model_not_batchable`.

### OCR lines

A `/v1/chat/completions` line may carry images, as `image_url` parts, on a
vision model that takes batch work (an OCR model, for example):

```json
{"custom_id": "ocr-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "deepseek-ocr-2", "messages": [{"role": "user", "content": [{"type": "text", "text": "Extract the text."}, {"type": "image_url", "image_url": {"url": "https://example.com/page-1.png"}}]}]}}
```

- Each image is a `data:image/...;base64,` URI or an `http(s)` URL; anything
  else is refused (`invalid_media_url`). A line references at most 8 images by
  URL (`too_many_images`).
- An image URL is fetched when the line runs, not when the batch is created:
  it must stay valid until the batch's `expires_at`, a presigned URL included.
  A fetched image is at most 8,000,000 bytes.
- Audio, video and file parts are refused (`media_not_supported_in_batch`).
- The line is billed in tokens, like any chat line.
- A `/v1/responses` line's `input_image` URLs are fetched the same way, when
  the line runs, with the same 8,000,000-byte limit; a failed fetch ends the
  line with `media_fetch_failed` (retried when transient), `media_too_large` or
  `invalid_media`. A Responses line is not checked at submission
  (`invalid_media_url`, `too_many_images`): more than 8 images by URL fails when
  the line runs, with `invalid_image`.

### Transcription lines

A `/v1/audio/transcriptions` line names its audio by URL in `file_url`; there
is no upload:

```json
{"custom_id": "audio-1", "method": "POST", "url": "/v1/audio/transcriptions", "body": {"model": "whisper-large-v3-turbo", "file_url": "https://example.com/call-1.mp3", "language": "en"}}
```

- The body takes `model`, `file_url`, `language`, `prompt`, `temperature`,
  `response_format` and `timestamp_granularities`, and no other key. A `file`
  field is refused.
- `response_format` is `json` (the default) or `verbose_json`. Only a
  transcription model (`kind: transcription` in `/v1/models`, such as
  `whisper-large-v3-turbo`) takes `verbose_json` and `timestamp_granularities`;
  an audio chat model such as `voxtral-mini-3b` refuses them.
- `file_url` is an `http(s)` URL, fetched when the line runs: it must stay
  valid until the batch's `expires_at`, a presigned URL included.
- The audio is wav, mp3, flac, ogg, m4a or webm, recognised from its content,
  and at most 25 MB.
- The output line's `body` is what the synchronous route returns. The line is
  billed per minute of audio.

### Image generation lines

```json
{"custom_id": "image-1", "method": "POST", "url": "/v1/images/generations", "body": {"model": "flux-2-klein", "prompt": "A lighthouse at dawn", "n": 2, "size": "1024x1024"}}
```

- `prompt`: 1 to 2,000 characters, not blank.
- `n`: an integer from 1 to 4 (default 1).
- `size`: `1024x1024`, `768x768` or `512x512`.
- `response_format`: `b64_json` only (the default). URLs are not returned.
- `seed`: an integer. Other keys are ignored, as on the synchronous route.
- A file asks for at most 5,000 images in all (the sum of `n` over its image
  lines; `too_many_images_in_file`).
- Images come back inline in the output file: expect about 2.7 MB of base64 per
  1024×1024 image. The line is billed per image generated.

## Limits

| Limit | Value |
|---|---|
| Input file size | 200 MB |
| Requests per input file | 50,000 |
| Batches `in_progress` per organisation | 10 |
| Batches waiting for a slot per organisation | 50 |
| Images referenced by URL per chat line | 8 |
| Fetched image size | 8,000,000 bytes |
| Fetched audio size | 25 MB |
| Images per input file (sum of `n`) | 5,000 |
| Request body sent to the model, media inlined | 26,279,936 bytes |
| Output of one line | 23 MiB |

A batch created while 10 of your organisation's batches are `in_progress` is
not refused: once validated, it stays in `validating` until a slot frees.
Its completion window still runs from `created_at`. Once 50 batches are
waiting, create answers `429 batch_queue_full`.

## Completion window

`completion_window` is `"24h"`, `"48h"` or `"72h"`, and **`"48h"` when
omitted**. `expires_at` on the batch is `created_at` plus the window. When the
window ends, the batch goes to `expired`: the lines that finished are
delivered and billed, and the rest go to the error file as `batch_expired`.

The OpenAI SDK types `completion_window` as required; to rely on the default,
send the body yourself:

```python
import openai

batch = client.post(
    "/batches",
    cast_to=openai.types.Batch,
    body={"input_file_id": batch_input.id, "endpoint": "/v1/chat/completions"},
)
```

## Price

Each line is billed at its model's list price (see [Pricing](pricing.md))
multiplied by the model's batch multiplier, **0.5 unless
the model says otherwise**.
`/v1/models` shows each model's `batch` block:

```json
{"id": "gemma-4-26b-a4b", "batch": {"enabled": true, "multiplier": 0.5, "price_in": 0.0345, "price_out": 0.129, "endpoints": ["/v1/chat/completions", "/v1/completions", "/v1/responses"]}, ...}
```

- A transcription model's block adds `price_audio_min`, the batch price per
  minute of audio; an image model's adds `price_image`, the batch price per
  image generated. Both are the list price multiplied by the batch multiplier.
- `usage` on the batch adds `audio_seconds` (audio transcribed) and `images`
  (images generated) to the token counts.

- The multiplier of each model in the file is fixed when the batch is
  submitted and shown on the batch in `pricing.multipliers`. A later change to
  a model's multiplier does not reprice a running batch.
- **Batch usage is billed from your organisation's paid balance only.**
  Welcome credits and other free credits do not cover batch usage.
- Only lines that succeed are billed. Lines that fail, expire or are cancelled
  before they run are free. A batch whose input fails validation bills
  nothing.
- Creating a batch runs the same balance and spending-cap checks as a
  synchronous request and answers the same `402` (or `403
  payment_method_required`); an organisation holding only free credit gets
  `402 paid_credit_required`. If the paid balance runs out while a batch runs, its
  lines wait (`paused_reason: "insufficient_balance"`) and restart within a
  minute of a top-up. Lines still waiting when the window ends expire, unbilled.

## Peak hours

Batch work is paced so that it does not compete with synchronous traffic, and
it runs outside peak hours unless a deadline needs it. While a model's GPU class
is in its peak period, that model's lines wait. A batch whose remaining lines on
a model would otherwise not finish 4 hours before `expires_at` runs them anyway.

In a mixed batch, each model is paced on its own: lines on a model outside its
peak keep running while another model's lines wait.

`paused_reason` is `"peak_hours"` when peak hours hold back at least one of the
batch's models and none of its lines has run for about two minutes; in a mixed
batch whose other models keep running it stays `null`. It is cleared as soon as
the batch's lines run again. `"insufficient_balance"` takes precedence over
`"peak_hours"`.

## Status lifecycle

| Status | Meaning |
|---|---|
| `validating` | The input file is being checked, or the batch is valid and waiting for one of the 10 `in_progress` slots. |
| `failed` | At least one line broke a rule (see `errors`). Nothing ran and nothing is billed. |
| `in_progress` | Lines are running. `request_counts` moves as they finish. |
| `finalizing` | Every line has finished; the output files are being completed. |
| `completed` | Done. Read `output_file_id` and `error_file_id`. |
| `expired` | The window ended first. Finished lines are delivered; the rest are in the error file as `batch_expired`. |
| `cancelling` | Cancel was requested; lines already sent are finishing. |
| `cancelled` | Lines that had not started were cancelled and not billed; lines that finished are delivered and billed. |

`POST /v1/batches/{batch_id}/cancel` is accepted in `validating` and
`in_progress`; in any other status it answers `409 batch_not_cancellable`.
Any member of the organisation can cancel any of its batches.

`output_file_id` is `null` when no line succeeded, and `error_file_id` is
`null` when no line failed.

### Credentials

A batch runs as the credential that created it, which must be an API key, a
console session or an OAuth token. Other credentials get
`403 unsupported_credential`.

- **API key:** if the key is revoked or loses the `inference` scope, the batch
  stops within 60 seconds: lines
  not yet run go to the error file as `authentication_error`.
- **Console session or OAuth token:** the batch keeps running after the session
  or token ends. Only a locked organisation or an erased account stops it.

## The batch object

The batch has OpenAI's shape (`id`, `status`, `request_counts`, `errors`,
`usage`, the timestamps, ...) with these differences:

- `model` is `null` until the file has been validated, and for a file that
  mixes models. A validated single-model batch, including one waiting for a
  slot, shows its model.
- Extension fields, ignored by the SDKs:
  - `pricing`: `{"mode": "batch", "multipliers": {"<model>": <multiplier>, ...}}`,
    one entry per model in the file, fixed at submission.
  - `endpoints`: the endpoints the file's lines use, once validated.
  - `paused_reason`: `"peak_hours"`, `"insufficient_balance"` or `null`.

## Output and error files

Results are written to two files with purpose `batch_output`. Read them with
`GET /v1/files/{file_id}/content` (`client.files.content(...)`).

**Output file**: one line per request that succeeded. `body` is exactly what
the synchronous endpoint returned:

```json
{"id": "batch_req_...", "custom_id": "request-1", "response": {"status_code": 200, "request_id": "req_...", "body": {"id": "chatcmpl-...", "object": "chat.completion", "choices": [...], "usage": {...}}}, "error": null}
```

**Error file**: one line per request that did not succeed. Every error line has
`error: {code, message}`.

- A request that failed with an HTTP status (a `4xx` caused by its own body,
  or an upstream failure after retries) also carries the response, whose
  `body` is the error envelope the synchronous route returned:

```json
{"id": "batch_req_...", "custom_id": "request-7", "response": {"status_code": 400, "request_id": "req_...", "body": {"error": {"message": "...", "type": "invalid_request_error", "code": "context_length_exceeded"}}}, "error": {"code": "context_length_exceeded", "message": "..."}}
```

- A request that never ran has `response: null`:

```json
{"id": "batch_req_...", "custom_id": "request-9", "response": null, "error": {"code": "batch_expired", "message": "The batch's completion window ended before this request completed."}}
```

A request that answers `429` or `5xx` is retried with backoff, up to 5
attempts in all; the last failure is its answer.

## Error codes

### Creating a batch or uploading a file

| HTTP | `code` | When |
|---|---|---|
| 400 | `unsupported_purpose` | Upload: `purpose` is not `batch`. |
| 400 | `invalid_json` | Upload: the file is not UTF-8 JSONL (each non-blank line must start a JSON object), or it is empty. |
| 400 | `invalid_request_error` | A missing or invalid parameter; `param` names it (`input_file_id` not a batch input, `endpoint`, `completion_window`, `metadata`, `expires_after`, `output_expires_after`). |
| 402 | `insufficient_balance` | Create: the organisation's balance is exhausted. |
| 402 | `paid_credit_required` | Create: only free credit is held, and it does not cover this. |
| 402 | `invoice_unpaid` | Create: an invoice is unpaid. |
| 402 | `monthly_budget_exceeded` | Create: a spending cap is reached. |
| 403 | `payment_method_required` | Create: a verified payment method is required. |
| 403 | `feature_disabled` | The Batch API is turned off for the organisation. |
| 403 | `unsupported_credential` | The credential is not an API key, a console session or an OAuth token. |
| 404 | `not_found` | The file or batch does not exist or belongs to another organisation. |
| 409 | `batch_not_cancellable` | Cancel: the batch is not `validating` or `in_progress`. |
| 413 | `request_too_large` | Upload: the file is larger than 200 MB. |
| 429 | `batch_queue_full` | Create: 50 batches are already waiting for a slot. |

### Validation (`errors.data` of a `failed` batch)

A batch whose file breaks a rule goes to `failed`, and `errors.data` lists
`{code, message, param, line}` (the first 1,000 entries). `line` is the
1-based line number, or `null` for errors about the whole batch.

| `code` | Meaning |
|---|---|
| `invalid_json` | The line is not a JSON object. |
| `invalid_request` | `param` names the missing or malformed field: `custom_id`, `method`, `body` or `body.model`; on a media line also `body.file_url`, `body.language`, `body.prompt`, `body.temperature`, `body.timestamp_granularities`, `body.n`, `body.size` or `body.seed`. With `line: null` and `param: "input_file_id"`, the input file was deleted before validation read it. |
| `duplicate_custom_id` | The `custom_id` is already used by an earlier line. |
| `endpoint_not_batchable` | `url` is not one of the six batch endpoints, or is a media endpoint support has turned off for your organisation. |
| `stream_not_supported` | The body sets `stream: true`. |
| `body_too_large` | The body exceeds the per-request size limit. |
| `model_not_batchable` | The model does not exist, does not take batch work, or does not serve the line's endpoint. |
| `tool_not_supported_in_batch` | A line, on any endpoint, uses a tool other than a function tool, `web_search_options` or the `web_search` flag. |
| `unsupported_parameter` | A `/v1/responses` line uses `store: true` or `previous_response_id`; a transcription line uses `file`, a key it does not take or a `response_format` other than `json` or `verbose_json`, or asks a model that is not `kind: transcription` for `verbose_json` or `timestamp_granularities`; an image line asks for a `response_format` other than `b64_json`. |
| `invalid_media_url` | An image of a chat line is not a `data:image` base64 URI or an `http(s)` URL, or a transcription line's `file_url` is not an `http(s)` URL. |
| `too_many_images` | A chat line references more than 8 images by URL. |
| `media_not_supported_in_batch` | A chat line carries an audio, video or file part. |
| `too_many_images_in_file` | The file's image lines ask for more than 5,000 images. |
| `too_many_requests_in_file` | The file has more than 50,000 requests. |
| `authentication_error` | `line: null`. The batch can no longer run as its creator (API key revoked or without the `inference` scope, organisation locked or account erased). |
| `validation_error` | `line: null`. Validation kept failing on our side. Create a new batch from the same file; contact support if it persists. |

### Error file lines (`error.code`)

| `code` | `response` | Meaning |
|---|---|---|
| The synchronous error's code | present | The request failed with an HTTP status; `response.body` is the error envelope. |
| `batch_expired` | `null` | The completion window ended before the request ran. |
| `cancelled` | `null` | The batch was cancelled before the request ran. |
| `authentication_error` | `null` | The batch's API key was revoked or lost the `inference` scope, or its organisation locked or account erased, before the request ran. |
| `server_error` | `null` | The request could not be completed on our side, and no response was kept. |
| `invalid_request` | `null` | The request line could not be read back from the input file. |
| `media_fetch_failed` | present | A media URL could not be fetched. A timeout, a DNS or connection failure, or an origin `429` or `5xx` is retried, up to 5 attempts; any other failure is final. |
| `media_too_large` | present | The fetched media is above its limit (see Limits), or the request with the media inlined is above what the model accepts. |
| `invalid_media` | present | The content at the URL is not a supported image or audio format. |
| `audio_duration_unknown` | present | The audio's duration could not be determined, so the transcription is not billed. |
| `output_too_large` | present | The model's answer is above the size limit of a batch line's output. |

None of these media failures is billed, nor is `output_too_large`, whatever the
line's endpoint: the answer is not kept.

## Retention

- **Input files** are kept 30 days from upload. Set a shorter time with
  `expires_after` on upload (`{"anchor": "created_at", "seconds": N}`, N from
  3600 to 2592000). An input file used by an unfinished batch is kept until
  that batch ends.
- **Output and error files** are kept 15 days after the batch ends.
  `output_expires_after` on `batches.create` can shorten this (1 hour to 15
  days), never extend it.
- **`DELETE /v1/files/{file_id}` always wins.** The file is gone from the API
  at once and erased from storage within minutes. Deleting the input file of
  an unfinished batch cancels that batch: lines already sent finish and are
  billed, the rest are cancelled and not billed.
- When a batch's output files expire, its `metadata` and `errors` are cleared.
  The batch itself stays listed with its status, counts, usage and timestamps.
- The file's **filename** and the batch's **metadata** are the only text of
  yours kept in our database. They are deleted with their file or batch, but
  remain in our nightly backups for up to 7 days.
- Request bodies, outputs and `custom_id` values are never written to our
  logs.

## Coming from OVHcloud AI Endpoints

Code written for OVHcloud AI Endpoints' batch mode runs here with only the base
URL and the API key changed: the same JSONL line format, ids (`file-`,
`batch_`, `batch_req_`), statuses, `request_counts`, completion windows and
default, 200 MB / 50,000-request limits, output line format and 15-day output
retention. The differences that remain:

| Topic | OVHcloud AI Endpoints | Blade Models |
|---|---|---|
| Endpoints | Chat completions, responses, embeddings | Also `/v1/completions` |
| Tools in batch lines | Accepted | Function tools only, on every endpoint; built-in tools are refused (`tool_not_supported_in_batch`) |
| `model` on the batch | Set | `null` for a file that mixes models |
| Batches in progress per organisation | 5 | 10; up to 50 more wait in `validating` |
| Extension fields on the batch | None | `pricing`, `paused_reason`, `endpoints` |
| Error file lines | `error` | `error`, plus `response` for requests that failed with an HTTP status |
