Skip to content

Docs / Batch API

Batch API

Submit up to 1,000 chat completion requests at once and run them in the off-peak window. Statuses, results, costs and retention.

Get an API key

The Batch API runs many chat completion requests for you, in the background. By default it waits for the off-peak window, where a route prices by time of day, and runs them then. Use it for work that does not need an answer right away: evaluations, labelling, summarising a backlog.

At a glance

Requests per batch 1 to 1,000
Request format Chat Completions bodies (/v1/chat/completions), no streaming
Schedule off_peak (default) or asap
Completion window 24h. Requests not run by then are marked expired and not charged
Results kept 7 days after the batch finishes, or until you delete it
Submissions 10 batches per organisation per minute
Retries A request that fails for a temporary reason is tried up to 3 times in total
Billing Each request is billed once, at the price when it ran

Endpoints

Method Path What it does
POST /v1/batches Submit a batch
GET /v1/batches?limit=20 Your organisation’s batches, newest first (limit 1 to 100)
GET /v1/batches/{id} One batch
GET /v1/batches/{id}/results Each request’s outcome
POST /v1/batches/{id}/cancel Cancel requests that have not run
DELETE /v1/batches/{id} Cancel, and delete stored prompts and results now

Any key in your organisation can see and manage its batches. The same batches are in the console under Batches.

Submit a batch

curl https://api.yunshurouter.com/v1/batches \
  -H "Authorization: Bearer $YUNSHU_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "schedule": "off_peak",
    "requests": [
      {
        "custom_id": "review-1",
        "body": {
          "model": "deepseek-v4.1-flash",
          "max_tokens": 200,
          "messages": [{"role": "user", "content": "Classify the sentiment: I love it."}]
        }
      },
      {
        "custom_id": "review-2",
        "body": {
          "model": "deepseek-v4.1-flash",
          "max_tokens": 200,
          "messages": [{"role": "user", "content": "Classify the sentiment: It broke on day two."}]
        }
      }
    ]
  }'
import httpx

BASE = "https://api.yunshurouter.com/v1"
HEADERS = {"Authorization": "Bearer tq-..."}

reviews = ["I love it.", "It broke on day two."]
batch = httpx.post(
    f"{BASE}/batches",
    headers=HEADERS,
    json={
        "schedule": "off_peak",
        "requests": [
            {
                "custom_id": f"review-{i}",
                "body": {
                    "model": "deepseek-v4.1-flash",
                    "max_tokens": 200,
                    "messages": [{"role": "user", "content": f"Classify the sentiment: {text}"}],
                },
            }
            for i, text in enumerate(reviews)
        ],
    },
).json()
print(batch["id"], batch["status"], batch["estimated_cost"])
const BASE = "https://api.yunshurouter.com/v1";
const headers = { Authorization: `Bearer ${process.env.YUNSHU_API_KEY}`, "Content-Type": "application/json" };

const reviews = ["I love it.", "It broke on day two."];
const res = await fetch(`${BASE}/batches`, {
  method: "POST",
  headers,
  body: JSON.stringify({
    schedule: "off_peak",
    requests: reviews.map((text, i) => ({
      custom_id: `review-${i}`,
      body: {
        model: "deepseek-v4.1-flash",
        max_tokens: 200,
        messages: [{ role: "user", content: `Classify the sentiment: ${text}` }],
      },
    })),
  }),
});
const batch = await res.json();
console.log(batch.id, batch.status);

This is not OpenAI’s file-based Batch API: there is no file upload. Requests go in the JSON body, and the OpenAI SDK’s client.batches methods do not apply.

Request fields

Field Rules
requests Required. 1 to 1,000 items
requests[].custom_id Required. 1 to 64 characters, unique in the batch. Use it to match results
requests[].body Required. A Chat Completions body, checked exactly as /v1/chat/completions checks it. stream must not be true
requests[].method Optional. POST only
requests[].url Optional. /v1/chat/completions only
schedule off_peak (default) waits for the off-peak window. asap runs at once
completion_window 24h (the only value)

The body can use combos, :floor / :nitro and models fallbacks.

One bad item refuses the whole batch. The error names the item, for example requests[3] (custom_id 'review-3'): model 'deepseek-v4.1-flsh' is not available. The batch was not accepted.

To submit a batch, your balance must be above zero (402 insufficient_balance otherwise). Your organisation must not have zero retention switched on (403 permission_denied), because a batch stores its prompts until it runs.

The batch object

{
  "id": "...",
  "object": "batch",
  "endpoint": "/v1/chat/completions",
  "status": "queued",
  "schedule": "off_peak",
  "completion_window": "24h",
  "request_counts": {
    "total": 2, "queued": 2, "in_progress": 0, "completed": 0,
    "failed": 0, "cancelled": 0, "expired": 0
  },
  "created_at": "2026-11-03T08:00:00+00:00",
  "started_at": null,
  "finished_at": null,
  "expires_at": "2026-11-04T08:00:00+00:00",
  "cancelled_at": null,
  "purged_at": null,
  "purge_after": null,
  "estimated_cost": {
    "currency": "USD",
    "off_peak": "...", "peak": "...", "savings": "...",
    "off_peak_micros": 0, "peak_micros": 0, "savings_micros": 0
  },
  "cost": {"currency": "USD", "amount": "0", "micros": 0},
  "peak_equivalent_cost": {"currency": "USD", "amount": "0", "micros": 0},
  "savings_vs_peak": {"currency": "USD", "amount": "0", "micros": 0},
  "error": null,
  "api_key_id": "..."
}
Field Meaning
status queued, in_progress, completed, failed, cancelled or expired
request_counts How many requests are in each state
expires_at End of the completion window
purge_after When stored prompts and results will be deleted (7 days after finished_at)
purged_at When they were deleted
estimated_cost At submission: our estimate at off-peak and at peak prices, and the difference. Based on your max_tokens, so it is an upper estimate
cost What has been charged so far
peak_equivalent_cost What the same tokens would have cost at peak prices
savings_vs_peak peak_equivalent_cost minus cost
error Set if the whole batch stopped, with code and message

Money is shown as a decimal string and as integer micros (millionths of a currency unit), in your balance currency.

Results

curl https://api.yunshurouter.com/v1/batches/$BATCH_ID/results \
  -H "Authorization: Bearer $YUNSHU_API_KEY"
{
  "object": "list",
  "batch": { "...": "the batch object" },
  "purged": false,
  "data": [
    {
      "custom_id": "review-1",
      "status": "completed",
      "response": { "id": "...", "object": "chat.completion", "choices": [ ... ], "usage": { ... } },
      "error": null,
      "request_id": "...",
      "cost": {"currency": "USD", "amount": "...", "micros": 0},
      "attempts": 1,
      "finished_at": "2026-11-03T21:04:11+00:00"
    }
  ]
}
  • response is the full Chat Completions response.
  • request_id works with GET /v1/generation.
  • error has a code and message when the item failed, was cancelled or expired.
  • After purge, purged is true and response is no longer available. Counts and costs stay, because they are billing history.

Poll GET /v1/batches/{id} every few minutes, not in a tight loop: each call counts against your rate limit.

When requests fail

Failure What happens
Temporary (model unreachable, no route available) The item is tried again, up to 3 attempts in total
Balance empty, key budget reached, key revoked The batch stops. Every request still queued fails with the same reason
The completion window closes first Remaining items are expired and not charged

Cancel and delete

  • POST /v1/batches/{id}/cancel cancels items that have not started. Items already running finish and are billed.
  • DELETE /v1/batches/{id} cancels too, and deletes every stored prompt and result now. The batch record, counts and costs stay.

In the console, cancelling and deleting need the administrator role. With an API key, any key of the organisation can do both.

Data

Batches are the one place we store your prompts: until the batch finishes, and then for 7 days so you can download results, unless you delete them sooner.