ข้ามไปยังเนื้อหา
เอกสาร
Authentication

หน้านี้ยังไม่ได้รับการแปล กำลังแสดงฉบับภาษาอังกฤษ

Batch API

The Batch API runs many model requests at once, at a discount, when you don’t need the answers right away. Send them in one POST to https://opencode.ai/inference/v1/batches, then read every result when the batch ends. Most batches end within minutes, Grok batches can take an hour or more, and all end within 24 hours.

เทอร์มินัล
curl -X POST "https://opencode.ai/inference/v1/batches" \
  -H "Authorization: Bearer <token>" \
  -H "Content-Type: application/json" \
  -d '{
    "endpoint": "/v1/messages",
    "model": "claude-haiku-5-5",
    "requests": [
      { "custom_id": "greeting", "body": { "max_tokens": 256, "messages": [{ "role": "user", "content": "Say hi" }] } },
      { "custom_id": "farewell", "body": { "max_tokens": 256, "messages": [{ "role": "user", "content": "Say bye" }] } }
    ]
  }'

The API has the same shape as OpenRouter’s batch API.

Batches use the same personal API keys and service account keys as the Inference API. A key sees only its own workspace’s batches.

Authorization: Bearer <token>

MethodPathDoes
POST/inference/v1/batchesSubmits a batch.
GET/inference/v1/batches/{id}Returns a batch, with its results.
GET/inference/v1/batches/{id}/resultsReturns a page of results.
GET/inference/v1/batchesLists the workspace’s batches.
POST/inference/v1/batches/{id}/cancelCancels a batch.
DELETE/inference/v1/batches/{id}Deletes an ended batch.

A batch is one model, one endpoint format, and a list of requests.

FieldRequiredValue
endpointYes/v1/messages, /v1/chat/completions, /v1/responses, or /v1/embeddings.
modelYesThe model every request runs on, such as claude-haiku-5-5.
requestsYes1 to 50,000 { custom_id, body } objects.
completion_windowNo24h, the only window.

Each body is an ordinary request in the endpoint’s format, as you’d send it to the Inference API. Leave out its model, or set it to the batch’s. stream is ignored.

JSON
{
  "custom_id": "summary-42",
  "body": {
    "max_tokens": 1024,
    "system": "Summarize the ticket in one sentence.",
    "messages": [{ "role": "user", "content": "My card was charged twice..." }]
  }
}

custom_id is how you match results to requests. It must be 1 to 64 characters and unique in the batch.

The batch is accepted with 202 and returned with status validating or in_progress.

JSON
{
  "id": "batch_01KBX9Q8H6T2M4N7P3R5S8V0WZ",
  "object": "batch",
  "endpoint": "/v1/messages",
  "model": "claude-haiku-5-5",
  "completion_window": "24h",
  "status": "in_progress",
  "created_at": 1796385600,
  "finalized_at": null,
  "expires_at": 1796472000,
  "provider": "anthropic",
  "request_counts": { "total": 2, "completed": 0, "failed": 0 },
  "usage": null,
  "results": null,
  "error": null
}

Each request follows the workspace’s model rules, as it would if sent on its own. A batch with one request that can’t be sent is refused whole, with 400 naming that request.

GET /inference/v1/batches/{id} returns the batch. Poll it until status is one that has ended.

เทอร์มินัล
curl "https://opencode.ai/inference/v1/batches/batch_01KBX9Q8H6T2M4N7P3R5S8V0WZ" \
  -H "Authorization: Bearer <token>"
FieldMeaning
statusWhere the batch is. See statuses.
request_countstotal, completed, and failed requests.
usage.costUS dollars charged for the batch, once its results are charged. null until then.
providerThe provider running the batch, such as anthropic, openai, xai, or google.
created_atWhen the batch was submitted, in Unix seconds.
finalized_atWhen the batch ended, in Unix seconds. null while it runs.
expires_atWhen the provider stops working on the batch, in Unix seconds.
error{ message } when the whole batch failed, otherwise null.
resultsEvery result, once the batch ended and was charged. null until then.

Once the batch ended and its results are charged, results has one row per request. A row has a response in the batch’s endpoint format, or an error.

JSON
"results": [
  {
    "custom_id": "greeting",
    "response": {
      "id": "msg_01...",
      "type": "message",
      "role": "assistant",
      "content": [{ "type": "text", "text": "Hi there!" }],
      "usage": { "input_tokens": 9, "output_tokens": 6 }
    }
  },
  {
    "custom_id": "farewell",
    "error": { "code": "cancelled", "message": "The batch was cancelled before this request ran" }
  }
]

Every request gets exactly one row, including requests that never ran because the batch was cancelled or expired. Those rows have the error code cancelled or expired, and aren’t charged.

StatusMeaning
validatingThe provider is checking the batch.
in_progressThe requests are running.
finalizingThe batch ended and its results are being charged.
completedEvery request ran. Some may still have failed, so check each row.
failedThe batch failed as a whole. error says why.
cancellingThe batch is being cancelled.
cancelledThe batch was cancelled.
expiredThe provider didn’t finish within 24 hours.

completed, failed, cancelled, and expired have ended.

GET /inference/v1/batches/{id}/results returns the same rows a page at a time. It’s the cheaper way to poll, since a large batch’s inline results can be many megabytes.

เทอร์มินัล
curl "https://opencode.ai/inference/v1/batches/batch_01KBX9Q8H6T2M4N7P3R5S8V0WZ/results?limit=500" \
  -H "Authorization: Bearer <token>"
ParameterValue
limitRows per page, 1 to 1,000. Defaults to 500.
cursorThe next_cursor of the previous page. Omit for the first page.

A page also ends early, before about 4 MiB. While has_more is true, pass next_cursor back as cursor.

JSON
{
  "object": "list",
  "data": [
    {
      "custom_id": "greeting",
      "response": { "type": "message", "content": [{ "type": "text", "text": "Hi there!" }] }
    },
    { "custom_id": "farewell", "response": { "type": "message", "content": [{ "type": "text", "text": "Goodbye!" }] } }
  ],
  "has_more": false,
  "next_cursor": null
}

The endpoint returns 409 until the results are ready, so a loop can poll the first page while it gets 409.

เทอร์มินัล
while true; do
  code=$(curl --silent --output results.json --write-out "%{http_code}" \
    "https://opencode.ai/inference/v1/batches/$BATCH_ID/results" \
    -H "Authorization: Bearer <token>")
  [ "$code" != 409 ] && break
  sleep 60
done
echo "$code"

The loop stops on any other status. 200 means results.json holds the first page, and anything else holds an error. Once a batch has ended, including one that failed as a whole, the endpoint returns 200. A batch the provider refused before it ran has an empty page.

There are no webhooks, so poll to learn when a batch ends.

GET /inference/v1/batches returns the workspace’s batches, newest first, without their results.

เทอร์มินัล
curl "https://opencode.ai/inference/v1/batches?limit=20" \
  -H "Authorization: Bearer <token>"
ParameterValue
limitBatches per page, 1 to 100. Defaults to 20.
afterA batch ID. Returns the batches submitted before it.

The response is { object: "list", data, first_id, last_id, has_more }. To read the next page, pass last_id as after.

POST /inference/v1/batches/{id}/cancel stops a running batch. Requests that already ran are charged. The rest come back as cancelled rows.

เทอร์มินัล
curl -X POST "https://opencode.ai/inference/v1/batches/batch_01KBX9Q8H6T2M4N7P3R5S8V0WZ/cancel" \
  -H "Authorization: Bearer <token>"

It returns the batch, which moves to cancelling, then cancelled. A batch that already ended returns 409.

DELETE /inference/v1/batches/{id} removes what the provider keeps of a batch that ended. It returns 409 while the batch runs, so cancel it first.

เทอร์มินัล
curl -X DELETE "https://opencode.ai/inference/v1/batches/batch_01KBX9Q8H6T2M4N7P3R5S8V0WZ" \
  -H "Authorization: Bearer <token>"
JSON
{ "id": "batch_01KBX9Q8H6T2M4N7P3R5S8V0WZ", "object": "batch", "deleted": true }

Batches run on OpenCode’s paid models that have a batch price on models.dev.

ModelsBatch price
Claude50% of the model’s price.
GPT50% of the model’s price.
Gemini50% of the model’s price. Some keep cached input at full price, per their models.dev entry.
Grok 4.5–4.780% of the model’s price.
  • Reasoning tokens count as output.
  • A model without a batch price returns 400 saying it has no batch price.
  • Free and Go models can’t be batched.

When you submit a batch, its estimated cost is held from your balance. Each request is estimated at its input, with each image counted as 4,784 tokens, plus its output limit.

A request without an output limit gets one of 8,192 tokens (max_completion_tokens for Chat Completions, max_output_tokens for Responses). Set your own limit for longer answers; the hold grows with it. Grok models’ output limit doesn’t include their reasoning, so a Grok batch holds four times each request’s output limit.

The hold is an estimate: when the batch ends, each result is charged at its actual usage, which can be more or less than was held.

  • A batch your balance, or your pay-later credit limit, can’t cover returns 402 with the estimate and what’s available.
  • Budgets must have room for the estimate when you submit.
  • When the batch ends, the hold is released and each result is charged at its actual usage.

Each charged result appears in Activity › Logs with the request ID <batch id>/<custom_id>, such as batch_01KBX9Q8H6T2M4N7P3R5S8V0WZ/greeting. Filter Logs by batch to see one batch’s results together.

LimitValuePast it
Requests per batch50,000400
Size of a batch64 MiB413
Open batches per workspace10429
custom_id1 to 64 characters, unique in the batch400
Time to finish24 hoursexpired

Some workspaces and models can’t use batches.

  • Your own provider keys. Batches run on OpenCode’s models only, so a model on a provider key returns 400.
  • Compliance obligations. A workspace with obligations such as HIPAA returns 403. Providers keep a batch’s requests and results for up to about 30 days, outside zero data retention and BAAs.

OpenCode doesn’t store a batch’s requests or results. The provider that runs the batch keeps them, and OpenCode reads them from it each time you ask.

ProviderKeeps a batch for
Anthropic29 days
OpenAIAbout 30 days
xAIAbout 30 days
GeminiAbout 2 days
  • Gemini deletes a batch’s result files after 48 hours, so read Gemini results soon after the batch ends.
  • Batches are never zero data retention at the provider, even for models whose regular requests are.
  • Deleting a batch removes the provider’s copy. xAI keeps a batch until it expires.

Errors return { "error": { "code", "message" } }, and the message names the field that’s wrong.

JSON
{ "error": { "code": 400, "message": "requests[3].custom_id must be a string of 1 to 64 characters." } }
StatusMeaning
400An invalid field, a duplicate custom_id, a model that can’t be batched, or a provider key’s model.
401No credentials, or an expired or revoked key.
402The balance or credit limit can’t cover the batch’s estimate.
403The workspace has compliance obligations, or the key’s permissions don’t allow calling models.
404No batch with that ID in the workspace.
409The results aren’t ready yet, the batch already ended (cancel), or it’s still running (delete).
413The batch is over 64 MiB.
429The workspace already has 10 open batches.
502The provider refused or couldn’t take the batch.