> ## Documentation Index
> Fetch the complete documentation index at: https://docs.siray.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Batch API

> Submit hundreds of asynchronous image, video, audio and 3D generations in a single request; poll one batch instead of hundreds of task ids.

## Overview

The Batch API groups many asynchronous generation requests into a single **batch**. You submit the batch once, the service queues every request, dispatches them through the same relay path a direct call would use, tracks the resulting tasks, and lets you download one aggregated result file.

> [!TIP]
>
> Batches are designed for throughput, not for latency. A batch item starts within a few seconds of submission, but total wall-clock time is bounded by the slowest generation in the batch and by the concurrency throttle.

## Supported endpoints

A batch item may only target the asynchronous generation endpoints below. Any other `url` is rejected with `unsupported_url`.

| `url` you send | Status endpoint used to collect the result |
| - | - |
| `/v1/images/generations/async` | `/v1/images/generations/async/{task_id}` |
| `/v1/video/generations` | `/v1/video/generations/{task_id}` |
| `/v1/audio/generations` | `/v1/audio/generations/{task_id}` |
| `/v1/3d/generations` | `/v1/3d/generations/{task_id}` |

## Endpoints

| Method | Path | Description |
| - | - | - |
| `POST` | `/v1/batches` | Create a batch |
| `GET` | `/v1/batches` | List batches (`limit` + `after` cursor) |
| `GET` | `/v1/batches/{batch_id}` | Retrieve one batch |
| `POST` | `/v1/batches/{batch_id}/cancel` | Cancel a batch (idempotent) |
| `GET` | `/v1/batches/{batch_id}/output` | Download successful results as JSONL |
| `GET` | `/v1/batches/{batch_id}/errors` | Download failed/cancelled results as JSONL |

All endpoints require `Authorization: Bearer <SIRAY_API_TOKEN>`.

## Create a batch

* `POST https://api.siray.ai/v1/batches`

The create endpoint accepts **three** input shapes; pick whichever fits your client.

### Option 1 — inline JSON

```bash theme={null}
curl -X POST "https://api.siray.ai/v1/batches" \
  -H "Authorization: Bearer ${SIRAY_API_TOKEN}" \
  -H "Content-Type: application/json" \
  -d '{
    "completion_window": "24h",
    "metadata": { "team": "media" },
    "requests": [
      {
        "custom_id": "img-1",
        "method": "POST",
        "url": "/v1/images/generations/async",
        "body": { "model": "seedream-4.0-t2i", "prompt": "a cat on a windowsill" }
      },
      {
        "custom_id": "vid-1",
        "url": "/v1/video/generations",
        "body": { "model": "veo-3-fast-t2v", "prompt": "a dog running on a beach" }
      }
    ]
  }'
```

`body` is the exact JSON object you would have posted to that endpoint — including image inputs, `data:` URLs, durations, aspect ratios, and so on.

You may also post a bare array of request items (no wrapper object); it is treated as `{"requests": [...]}`.

### Option 2 — raw JSONL

Set `Content-Type: application/jsonl` (or `application/x-ndjson`, or `text/plain`) and send one request item per line. Blank lines and trailing `\r` are ignored.

```jsonl theme={null}
{"custom_id":"img-1","url":"/v1/images/generations/async","body":{"model":"seedream-4.0-t2i","prompt":"a cat on a windowsill"}}
{"custom_id":"vid-1","url":"/v1/video/generations","body":{"model":"veo-3-fast-t2v","prompt":"a dog running on a beach"}}
```

### Option 3 — multipart file upload

Send `multipart/form-data` with a `file` part containing JSONL, plus an optional `completion_window` form field.

```bash theme={null}
curl -X POST "https://api.siray.ai/v1/batches" \
  -H "Authorization: Bearer ${SIRAY_API_TOKEN}" \
  -F "file=@requests.jsonl" \
  -F "completion_window=24h"
```

### Request item fields

| Field | Type | Required | Description |
| - | - | - | - |
| `custom_id` | string | Yes | Your identifier for the request. Unique inside the batch, ≤191 characters. It is echoed in the result line so you can correlate results. |
| `method` | string | No | Only `POST` is supported. Defaults to `POST` when omitted. |
| `url` | string | Yes | One of the [supported endpoints](#supported-endpoints). |
| `body` | object | Yes | The JSON body forwarded verbatim to `url`. ≤1 MB per item. |

### Top-level fields

| Field | Type | Description |
| - | - | - |
| `requests` | array | Required for the inline JSON shape. 1 … `BATCH_MAX_REQUESTS` items (default 1000). |
| `completion_window` | string | Hours, formatted as `<n>h`. 1–168. Defaults to the service value (`24h`). `expires_at` is computed as `created_at + completion_window`. |
| `metadata` | object | Free-form string map (≤16 KB after serialization). Echoed back on the batch object. |

### Validation rules

Every request is validated before anything is persisted, so a single malformed item rejects the whole batch instead of producing a half-valid one.

| Rule | Error `code` |
| - | - |
| Body is valid JSON (or valid JSONL) | `invalid_json` / `invalid_jsonl` |
| `custom_id` present, ≤191 chars, no duplicates | `missing_custom_id` / `invalid_custom_id` / `duplicate_custom_id` |
| `method` is `POST` | `invalid_method` |
| `url` present and in the supported list | `missing_url` / `unsupported_url` |
| `body` present and a JSON object, ≤1 MB | `missing_body` / `invalid_body` / `body_too_large` |
| Item count ≤ `BATCH_MAX_REQUESTS` | `batch_too_large` |
| At least one item | `empty_batch` |
| `completion_window` well-formed and ≤168h | `invalid_completion_window` |
| `metadata` is a string map ≤16 KB | `invalid_metadata` |
| Whole request body ≤32 MB | `invalid_body` / `input_too_large` |

Errors are returned in the standard shape:

```json theme={null}
{
  "error": {
    "message": "request 2: unsupported url \"/v1/images/generations\"; supported: /v1/images/generations/async, /v1/videos, /v1/video/generations, /v1/audio/generations, /v1/3d/generations",
    "type": "invalid_request_error",
    "param": "",
    "code": "unsupported_url"
  }
}
```

### Response

A successful create returns the batch object with `status` already set to `in_progress`:

```json theme={null}
{
  "id": "batch_3fcfd7e3cda945cbb0dcf434c5c0dd7d",
  "object": "batch",
  "endpoint": "mixed",
  "input_file_id": null,
  "completion_window": "24h",
  "status": "in_progress",
  "output_file_id": null,
  "error_file_id": null,
  "errors": null,
  "created_at": 1762900000,
  "in_progress_at": 1762900000,
  "expires_at": 1762986400,
  "request_counts": { "total": 2, "completed": 0, "failed": 0 },
  "metadata": { "team": "media" },
  "output_url": "/v1/batches/batch_3fcfd7e3cda945cbb0dcf434c5c0dd7d/output",
  "error_url": "/v1/batches/batch_3fcfd7e3cda945cbb0dcf434c5c0dd7d/errors"
}
```

## Batch object

| Field | Description |
| - | - |
| `id` | Batch id, `batch_` followed by 32 hex characters. |
| `object` | Always `batch`. |
| `endpoint` | The shared `url` when every item targets the same endpoint, otherwise `mixed`. |
| `status` | See [batch status](#batch-status). |
| `completion_window` | Normalized window, e.g. `24h`. |
| `request_counts.total` | Number of requests in the batch. |
| `request_counts.completed` | Requests that finished successfully. |
| `request_counts.failed` | Failed **and** cancelled requests. |
| `created_at` / `in_progress_at` / `expires_at` | Unix seconds. |
| `completed_at` / `failed_at` / `expired_at` / `cancelling_at` / `cancelled_at` | Set when the matching transition happened; `0`/absent otherwise. |
| `errors` | Batch-level error (`{code, message, type}`), `null` while healthy. |
| `metadata` | The map you supplied at creation. |
| `input_file_id` / `output_file_id` / `error_file_id` | Always `null` — retained for OpenAI wire compatibility. |
| `output_url` / `error_url` | Non-standard additions: JSONL download paths for this batch. |

### Batch status

```
in_progress ──all items terminal──> completed
     ├── cancel ──> cancelling ──in-flight tasks finish──> cancelled
     └── past expires_at ──> expired
```

| Status | Meaning |
| - | - |
| `in_progress` | Requests are being dispatched and/or tasks are being polled. |
| `completed` | Every request reached a terminal state. Individual requests may still have failed — check `request_counts` and the error stream. |
| `cancelling` | Cancel accepted, queued requests stopped, in-flight tasks still running. |
| `cancelled` | Cancel finished; nothing else will change. |
| `expired` | `expires_at` passed; requests that had not started were failed. Tasks already submitted keep running and their results are still collected. |
| `validating` | Reserved for OpenAI state-machine compatibility. Validation happens synchronously at create time, so a batch never rests in `validating`. |
| `failed` | Reserved for OpenAI state-machine compatibility and not produced today: a batch whose items all fail still ends as `completed`, with `request_counts.failed` equal to the total. Read per-request outcomes from `request_counts` and the error stream. |

### Item status

`queued` → `submitting` → `submitted` → `completed` / `failed`. A request that is stopped before it is ever dispatched ends as `cancelled`.

## Retrieve a batch

* `GET https://api.siray.ai/v1/batches/{batch_id}`

```bash theme={null}
curl -X GET "https://api.siray.ai/v1/batches/${BATCH_ID}" \
  -H "Authorization: Bearer ${SIRAY_API_TOKEN}"
```

Returns the same batch object shown above with refreshed `status` and `request_counts`. Polling every 3–5 seconds is a good default; a batch with long video generations will spend most of its life in `in_progress`.

## List batches

* `GET https://api.siray.ai/v1/batches?limit=20&after={batch_id}`

| Parameter | Default | Description |
| - | - | - |
| `limit` | `20` | Page size, 1–100. Values above the maximum are clamped. |
| `after` | — | Cursor: pass the previous page's `last_id`. An unknown or invisible cursor returns `400 invalid_after`. |

```json theme={null}
{
  "object": "list",
  "data": [ { "id": "batch_...", "object": "batch", "status": "completed", "...": "..." } ],
  "first_id": "batch_...",
  "last_id": "batch_...",
  "has_more": false
}
```

Pages are ordered newest-first.

## Cancel a batch

* `POST https://api.siray.ai/v1/batches/{batch_id}/cancel`

```bash theme={null}
curl -X POST "https://api.siray.ai/v1/batches/${BATCH_ID}/cancel" \
  -H "Authorization: Bearer ${SIRAY_API_TOKEN}"
```

Behaviour:

* Queued requests are marked `cancelled` immediately and are never sent upstream.
* Requests already accepted by an upstream provider cannot be recalled — the provider offers no cancel operation. Their results are still collected and returned, so you do not silently lose the quota you already paid for.
* The batch moves to `cancelling` and becomes `cancelled` once no request can change state anymore.
* The call is idempotent: cancelling a `completed`, `failed`, `expired` or `cancelled` batch simply returns its current object.

## Download results

Two JSONL streams are available. Both are scoped to the batch and require the same API key.

| Stream | Endpoint | Contents |
| - | - | - |
| Success | `GET /v1/batches/{batch_id}/output` | Items with status `completed` |
| Failure | `GET /v1/batches/{batch_id}/errors` | Items with status `failed` or `cancelled` |

```bash theme={null}
curl -X GET "https://api.siray.ai/v1/batches/${BATCH_ID}/output" \
  -H "Authorization: Bearer ${SIRAY_API_TOKEN}" \
  -o "${BATCH_ID}_output.jsonl"
```

Each line is one result:

```json theme={null}
{
  "id": "batch_req_12",
  "custom_id": "vid-1",
  "response": {
    "status_code": 200,
    "request_id": "batch-batch_3fcfd7e3cda945cbb0dcf434c5c0dd7d-12",
    "body": {
      "code": "success",
      "message": "",
      "data": {
        "task_id": "video_69196fafcc9c8190acccf32e9b560c3f0da8a6d1948cfaa5",
        "status": "SUCCESS",
        "progress": "100%",
        "outputs": ["https://api.siray.ai/redirect/example-output"]
      }
    }
  },
  "error": null
}
```

### Result line fields

| Field | Description |
| - | - |
| `id` | Line id, `batch_req_<n>`. Also usable as the `after` cursor. |
| `custom_id` | Echo of the request's `custom_id`. |
| `response` | `null` when the request never produced an HTTP response (for example the API key was revoked before dispatch). |
| `response.status_code` | Raw status code of the replayed call. |
| `response.request_id` | Correlation id used for the replay, `batch-<batch_id>-<item_id>`. Use it to find the matching entries in usage logs. |
| `response.body` | The target endpoint's original JSON response. |
| `error` | `null` for successful items. For failed/cancelled items, `error.code` is the item status (`failed` or `cancelled`) and `error.message` carries the reason. |

Notes on the error stream:

* A generation that failed upstream still has a `response.body` (the task status payload containing `fail_code` / `fail_reason`); `error.message` mirrors that failure reason.
* A request that failed before reaching a provider has `response: null` and the reason in `error.message`.
* If the task is finished but reading its result is rejected (any non-2xx, for example the API key was revoked or its IP allowlist changed while the batch was running), the error document is never stored as the result: the line falls back to a minimal body built from the stored task (`outputs` / `fail_reason`) with `status_code: 200`, and the item settles on the task's real terminal status.

### Pagination

Both streams are paginated:

| Parameter | Default | Description |
| - | - | - |
| `limit` | `500` | Lines per page, 1–500. |
| `after` | — | Last `id` of the previous page, either `batch_req_12` or `12`. |

The response header `X-Batch-Has-More: true` indicates another page exists. The `Content-Disposition` header suggests a filename such as `batch_xxx_output.jsonl`. Streaming is incremental — you can read partial results while the batch is still running.

## End-to-end example

```bash theme={null}
# 1. create
BATCH_ID=$(curl -sS -X POST "https://api.siray.ai/v1/batches" \
  -H "Authorization: Bearer ${SIRAY_API_TOKEN}" \
  -H "Content-Type: application/jsonl" \
  --data-binary @requests.jsonl | jq -r .id)

# 2. poll
while :; do
  STATUS=$(curl -sS "https://api.siray.ai/v1/batches/${BATCH_ID}" \
    -H "Authorization: Bearer ${SIRAY_API_TOKEN}" | jq -r .status)
  echo "status=${STATUS}"
  case "${STATUS}" in
    completed|cancelled|expired) break ;;
  esac
  sleep 5
done

# 3. download both result streams
curl -sS "https://api.siray.ai/v1/batches/${BATCH_ID}/output" \
  -H "Authorization: Bearer ${SIRAY_API_TOKEN}" -o output.jsonl
curl -sS "https://api.siray.ai/v1/batches/${BATCH_ID}/errors" \
  -H "Authorization: Bearer ${SIRAY_API_TOKEN}" -o errors.jsonl
```

## Billing

* Every batch request is a normal asynchronous generation and is charged per item at the model's price. The batch itself is free.
* **The key used for a replay is the key that gets charged.** A batch replays with the key that created it; if that key is deleted, disabled, exhausted or expired, replay falls back to the oldest enabled key of the same user and key identity — so a rotated key keeps the batch collectable. Quota, group, model limits and usage-log attribution follow the fallback key; the batch itself stays owned by its creator. Tasks created by any key of the same identity count as the batch's own result; another identity's task is never adopted.
* Usage log entries carry `request_id` values of the form `batch-<batch_id>-<item_id>`, so a batch can be reconciled line by line.
* A failing item never affects its siblings: insufficient balance, moderation rejection or an unsupported model only fails that one request.

## Errors

| `code` | HTTP | Description |
| - | - | - |
| `invalid_json` / `invalid_jsonl` | 400 | Request body is not valid JSON / JSONL. |
| `invalid_body` | 400 | An item `body` is not a JSON object, or the request body could not be read. |
| `empty_batch` | 400 | No requests supplied. |
| `batch_too_large` | 400 | Item count exceeds `BATCH_MAX_REQUESTS`. |
| `missing_custom_id` / `invalid_custom_id` / `duplicate_custom_id` | 400 | `custom_id` missing, too long, or repeated inside the batch. |
| `invalid_method` | 400 | Only `POST` is accepted. |
| `missing_url` / `unsupported_url` | 400 | `url` missing or outside the supported endpoint list. |
| `missing_body` / `body_too_large` | 400 | `body` missing or larger than 1 MB. |
| `invalid_completion_window` | 400 | Window is not `<n>h` within 1–168. |
| `invalid_metadata` | 400 | `metadata` is not a string map or exceeds 16 KB. |
| `input_file_unsupported` | 400 | `input_file_id` used, but no `/v1/files` API exists here. |
| `missing_file` / `invalid_file` / `invalid_multipart` / `input_too_large` | 400 | Multipart upload problems. |
| `invalid_limit` | 400 | `limit` is not a positive integer. |
| `invalid_after` | 400 | A cursor points outside your scope (`GET /v1/batches`) or cannot be parsed (`after` on the result streams). It is never silently ignored. |
| `batch_requires_identity` | 403 | Batch creation requires a key carrying an identity; an account-level key would create a batch nobody could read. |
| `batch_not_found` | 404 | Batch does not exist or is not visible to this API key. |
| `batch_api_disabled` | 404 | `BATCH_API_ENABLED=false`. |
| `batch_worker_disabled` | 503 | The task worker is disabled on the server, so no batch could ever progress. |
| `batch_create_failed` / `batch_list_failed` / `batch_load_failed` / `batch_cancel_failed` / `batch_output_failed` | 500 | Server or database error. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.