CoralBricks

CoralBricks Inference API

OpenAI-compatible inference for chat, interactive agents, and long-running autonomous agents. One API key, three surfaces, open models.

Coral Bricks runs open models against the OpenAI wire format. Point your existing OpenAI SDK at the Coral gateway and you get three progressively more powerful surfaces:

  • Chat Completions: turn-based chat. Client owns the conversation.
  • Responses: stateful, interactive agents. Server carries reasoning and thread state across turns.
  • Responses in background mode: autonomous agents that run for minutes to tens of minutes, headless. Fire-and-poll, resumable streams, no HTTP hold.

Same auth. Same model ids. Same SDK. Choose the surface that matches the shape of your workload.

Access is self-serve: sign up, create a key at /api-keys, and pay per token from a prepaid credit balance, with no waitlist or allowlist. Models and prices are at /models.

Building with a coding agent? This page is served as raw markdown at https://www.coralbricks.ai/docs.md. A machine-readable site index lives at /llms.txt, and the complete docs in one file at /llms-full.txt.

Using OpenCode, Cursor, Cline, or Claude Code? One config stanza (or one click) routes their agent loops through Coral. See the setup guides for OpenCode, Cursor, Cline, Claude Code, and Kilo Code.


Coding agent setup guides

Point your coding agent at Coral with one config change:

  • OpenCode: open-source, multi-provider terminal agent
  • Cline: VS Code extension for autonomous coding
  • Claude Code: Anthropic's terminal coding agent
  • Kilo Code: open-source VS Code agent
  • Pi: minimal, extensible terminal coding harness

Which API should I use?

Your workload Use Why
Turn-based chat, single-shot generation, you already have OpenAI Chat code Chat Completions Stateless per request. Drop-in for any Chat Completions client.
Multi-step interactive agent, tool use, reasoning that should carry across turns, a human is waiting Responses Server-side state via previous_response_id. Reasoning preserved between turns, which is measurably better on reasoning models.
Long-running headless agent, runs in CI / cron / a cloud box / a coding agent, no human waiting on the socket Responses (background) Fire-and-poll. Resumable streams. Survives caller death, network drops, and multi-minute runs.

All three share the same base URL (https://inference.coralbricks.ai/v1), the same API key, and the same model ids. With Zero Data Retention on, Responses runs without stored state, so background mode is unavailable.


Authentication

Every request needs:

Authorization: Bearer <CORAL_API_KEY>
  • Mint and rotate keys at /api-keys. Keys look like cb_… (older ak_… keys remain valid).
  • Keep keys server-side. Never embed in a browser bundle or a mobile app. Anyone with the key can spend against your account.
  • Newly-minted keys may take up to ~30 seconds to be honoured.

Any account can create keys and call the API; spend is drawn from the account's prepaid credit balance (see Credits).


Credits

Check the calling key's remaining prepaid balance:

curl -sS https://inference.coralbricks.ai/v1/quota \
  -H "Authorization: Bearer $CORAL_API_KEY"
{
  "object": "credits",
  "currency": "USD",
  "balance": 34.14,
  "balance_cents": 3420,
  "pending_charge_cents": 6
}

balance is the effective remaining amount in USD: the prepaid balance minus any un-flushed pending spend (balance_cents - pending_charge_cents). The endpoint has no credit gate, so it works even at a zero balance. Spend is also rejected up front: a request that would run against a non-positive balance returns 429 insufficient_credits.

Zero balance:

{
  "object": "credits",
  "currency": "USD",
  "balance": 0,
  "balance_cents": 0,
  "pending_charge_cents": 0
}

Pending spend:

{
  "object": "credits",
  "currency": "USD",
  "balance": 0.4,
  "balance_cents": 100,
  "pending_charge_cents": 60
}

Models

The production model catalog is loaded live from the same DynamoDB control plane that enables models in the gateway. Its machine-readable form is available at /api/public/models.

ModelContextInput / 1MCached read / 1MOutput / 1MStatus
DeepSeek V4.1 Flash Fast
deepseek-v4.1-flash-fast
1M $0.45 $0.009 $1.80 Available
DeepSeek V4.1 Flash Standard
deepseek-v4.1-flash
1M $0.19 $0.008 $0.60 Available
DeepSeek V4.1 Flash Value
deepseek-v4.1-flash-value
1M $0.005 $0.003 $0.57 Available

Pass the model id verbatim as the model field on any request. Earlier IDs of the models listed above still work: they reach the same model at the same price.

GLM 5.3 left the shared API on October 18, 2026. A request for glm-5.3-fast, or for any ID it had before, returns 404 with a message naming DeepSeek V4.1 Flash (deepseek-v4.1-flash-fast), the model to use instead. GLM 5.3 is still available as a Custom Endpoint.

GLM 5.3 Flash was retired on October 7, 2026. A request for glm-5.3-flash-fast, or for any ID it had before, returns 404 with the code model_retired. Use DeepSeek V4.1 Flash (deepseek-v4.1-flash-fast) instead: the API key and base URL stay the same. The exact set enabled for your key is also available programmatically:

curl -sS https://inference.coralbricks.ai/v1/models \
  -H "Authorization: Bearer $CORAL_API_KEY"

The same model ids work across Chat Completions, Responses, and background mode. Capability fields such as supports_image_input on each /v1/models row are authoritative; unsupported content returns 400 unsupported_content_type rather than being silently dropped.

Measured serving stats

Each row also carries what our own serving measured over the last 30 minutes and the last day, the same two windows OpenRouter's endpoints API uses.

Field Meaning
decode_speed_last_30m / _1d Output tokens per second while a response streams: the rate one caller's answer arrives at, not fleet capacity.
latency_last_30m / _1d Time to first token, median, in seconds.
cache_hit_rate_last_30m / _1d Share of prompt tokens served from cache, percent.

These are measured on requests we served on our own GPUs, so they describe our serving rather than a vendor's. A model that was too quiet to measure in a window simply carries no field for it. It is never a zero, which would claim a measurement we do not have.

Reasoning

Each row says whether the model reasons and which settings it takes. An alias row (an earlier ID) carries the same values as the model it points to.

{
  "id": "deepseek-v4.1-flash-fast",
  "supports_reasoning": true,
  "reasoning": {
    "supported_efforts": ["low", "high", "max"],
    "default_effort": "none",
    "mandatory": false,
    "disable": {"reasoning_effort": "none"}
  }
}
Field Meaning
supports_reasoning The model can return reasoning.
reasoning.supported_efforts The effort values that change how long it thinks.
reasoning.default_effort What runs when the request sets no effort.
reasoning.mandatory true when reasoning can't be turned off.
reasoning.disable The request field that turns reasoning off, or null when nothing does.

Today's values:

Model default_effort mandatory disable
DeepSeek V4.1 Flash Fast none (no reasoning unless asked) false {"reasoning_effort": "none"}
DeepSeek V4.1 Flash Standard none (no reasoning unless asked) false {"reasoning_effort": "none"}
DeepSeek V4.1 Flash Value none (no reasoning unless asked) false {"reasoning_effort": "none"}

All three DeepSeek V4.1 Flash tiers, including the Value model on the Subscription key, answer without reasoning when the request sets no effort. To have the model reason, ask for it on every request, as described below.

Set the effort with reasoning_effort on Chat Completions and reasoning.effort on Responses. DeepSeek V4.1 Flash takes low, high and max, and none turns its reasoning off. For clients that send other names, minimal is read as low, medium as high and xhigh as max. Any other value returns 400 unsupported_value, so a typo never silently changes how the model reasons. "reasoning": {"enabled": false} works like none; {"enabled": true} doesn't turn DeepSeek's reasoning on, so send an effort instead. On Messages, thinking: {"type": "enabled"} turns it on. No model takes a token budget.

Pricing

You pay per token, on every request, at the prices on /pricing. Each model bills three things, each at its own rate per 1M tokens: input, cached reads and output. There is no cache-write charge. A prefix your requests repeat, such as an agent's system prompt, tools and conversation so far, is read from the cache and billed at the cached-read rate. Prompt caching is automatic, with no cache flags to set.

Organizations created before Oct 16, 2026, 20:53:32 UTC keep their pricing and need no extra setup. Your console's Pricing page shows what your organization pays.

Cached input and cache writes

Cached reads and physical writes are reported per response. Cache writes are the novel input for that request: prompt_tokens - cached_tokens.

Novel input pays the input rate and cached tokens pay the model's cached-read rate. There is no cache write charge.

Prompt cache retention

This is about how long new tokens stay in the prompt cache and whether that is billed, not about what CoralBricks stores: that is Zero Data Retention, and it doesn't change anything here.

prompt_cache_retention has only two states:

  • Empty: omit the field or send null to use the platform's default prompt cache retention.
  • Off: send "off" to opt out of retained-cache billing.

There is no cache-write charge, so at the prices on /pricing there is nothing on the bill to opt out of.

/v1/messages (Anthropic Messages) has no way to send it, so Messages requests always use the default retention.

OpenAI's values "in_memory" and "24h" are also accepted, so a client that sends them works unchanged. They behave like an empty field and do not set a duration. Any other value, including an empty string, returns 400 invalid_prompt_cache. To request a specific retention duration, leave prompt_cache_retention empty and use a positive, whole-minute TTL in prompt_cache_options.ttl:

{
  "prompt_cache_options": { "ttl": "30m" }
}

The maximum TTL is 30m; a longer one returns 400 invalid_prompt_cache. The TTL sets the retention you are billed for. It doesn't make the cache hold a prefix any longer: the cache is transient in-memory storage that evicts on its own as space is needed, and a prefix can be evicted before its TTL runs out.

To opt out:

{
  "prompt_cache_retention": "off"
}

Opting out does not turn off engine prefix caching. Physical writes and cache hits can still occur and are still reported; it only keeps novel input in the plain-input billing bucket.

"usage": {
  "prompt_tokens": 20767,
  "prompt_tokens_details": {
    "cached_tokens": 20032,
    "cache_write_tokens": 735,
    "billable_cache_write_tokens": 0
  },
  "completion_tokens": 246,
  "cost": 0.000579,
  "cost_details": {
    "currency": "USD",
    "input": 0.000184,
    "cached_input": 0.0001,
    "cache_write": 0,
    "output": 0.000295
  }
}

Every response's usage also carries the request's cost in USD (usage.cost) and a per-bucket usage.cost_details breakdown, a Coral extension that equals what the request is billed. Present on both APIs, unary and streamed (on the final usage-bearing chunk). The example above is DeepSeek V4.1 Flash Fast: cached_input is the cached tokens at the model's cached-read rate, and there is no cache write charge.

Prompt cache key

Caching needs no key. A conversation that re-sends its history is served from the cache on its next turn whether or not the request names one. prompt_cache_key is an optional string on /v1/chat/completions and /v1/responses that says which cache a request belongs to:

{
  "model": "deepseek-v4.1-flash-fast",
  "prompt_cache_key": "session-7f3a9c",
  "messages": [{ "role": "user", "content": "..." }]
}
  • Same key, same prefix: reused. Requests that carry one key find each other's cached prefix. Without a key, two requests that share a long prefix but aren't turns of one conversation don't always find it.
  • Different keys never share. The same prompt under another key, or with no key, is written to the cache again.
  • Use one stable ID per session or conversation, and keep it for the whole conversation. A new key starts cold: its first request writes the full prompt, system prompt and tools included.
  • Share one key across conversations that share a prefix, such as forks of one parent response or workers reading the same document. See Cross-session prompt cache reuse.
  • promptCacheKey is accepted as an alias. Send either one. If a request carries both, they must match.
  • A key is at most 512 characters. A longer key, a key that isn't a string, or two aliases that differ return 400 with the code invalid_prompt_cache.
  • /v1/messages has no such field. Caching there is automatic, and a prompt_cache_key in the body is ignored.

Whether a coding agent sends a key is up to the agent:

Agent Sends a key
Codex CLI Always
OpenHands Always (the conversation ID)
OpenCode With setCacheKey: true; always in OpenCode 2
Kilo Code With setCacheKey: true
Pi On the Responses API; with supportsPromptCacheKey: true in oh-my-pi
Cline No
GitHub Copilot Not with the Chat Completions setup
Cursor Not established
Claude Code Not applicable: it uses /v1/messages

Zero Data Retention

An organization owner chooses a Zero Data Retention level on Data & Privacy in the dashboard: the Standard level (the default), No content, or No content + no metadata. It applies to every API key in the organization, on every inference endpoint, within about two minutes of the change.

Zero Data Retention applies to our persistent datastores: what is kept after a request finishes. It has no effect on prompt caching. The prompt cache is transient in-memory storage that only saves compute while requests are served, so cache reuse, prompt_cache_key, and cached-read billing are the same at No content and at No content + no metadata as at the Standard level. How a request is served and billed doesn't change either.

The trade-off is support: at the Standard level we keep the prompt, so when you send us a request ID we can replay the request to investigate it. Under either Zero Data Retention level there is nothing to replay.

What each level keeps:

Standard No content No content + no metadata
Content: prompts, completions, transcripts, tool-call arguments, and the model settings sent with them (temperature, thinking level) Kept up to 30 days Not kept Not kept
Metadata: HTTP headers such as User-Agent and session IDs, and the client IP address Kept up to 45 days Kept up to 45 days Not kept (the client IP address may stay in security logs to prevent fraud and abuse)
Operational data: model, endpoint, token counts, timings, status Kept up to 45 days Kept up to 45 days Kept
Billing records: credits consumed, usage counts per endpoint Kept Kept Kept

The privacy policy and the Trust Center are the full terms.

Where it applies, under either Zero Data Retention level:

Endpoint Zero Data Retention What changes
/v1/chat/completions (Chat Completions) Full Nothing.
/v1/messages and /v1/messages/count_tokens (Anthropic Messages, used by Claude Code) Full Nothing.
/v1/responses (Responses) Full Nothing is stored to continue from, so send the full conversation in input on every turn. Every response reports "store": false, whatever the request sent. previous_response_id and background: true return 400 with the code unsupported_parameter (background: true sent with store: false fails the store check first: 400 invalid_request on store), and X-Coral-Session no longer chains turns. On No content, GET /v1/responses/{id} returns the completed response without its output, and DELETE deletes it. On No content + no metadata, both return 404 response_not_found once the request has finished (a streamed GET sends one error event with that code).
  • Billing doesn't change with your Zero Data Retention level. It is input, cached reads and output, with no cache-write charge (see Cached input and cache writes). Prompt cache retention (prompt_cache_retention) is a separate setting and works the same at every level.
  • No content + no metadata stops per-request usage history. Credit balances and totals keep working, and billing records are kept at every level.
  • It applies going forward. Turning it on doesn't delete what is already stored; that ages out under the Standard level's windows in the table above.

1. Chat Completions

Turn-based chat. Stateless per request: you send the full message history on every call, and the server returns one assistant turn. The foundational OpenAI-compatible chat endpoint, unchanged from what your existing SDK expects.

Use when: you already have working chat.completions code, you're generating a single response, or you don't need the server to remember anything about the conversation.

POST /v1/chat/completions

curl -sS -X POST https://inference.coralbricks.ai/v1/chat/completions \
  -H "Authorization: Bearer $CORAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4.1-flash-fast",
    "messages": [
      {"role": "system", "content": "You are a careful research assistant."},
      {"role": "user",   "content": "What are the key metrics to watch for a Series A SaaS company?"}
    ]
  }'

Streaming is supported the OpenAI way: pass stream: true and consume the SSE. Tool calling (tools / tool_choice) works the same as upstream. Background mode is not available on this endpoint. Use /v1/responses for that.

from openai import OpenAI

client = OpenAI(base_url="https://inference.coralbricks.ai/v1", api_key="cb_...")

resp = client.chat.completions.create(
    model="deepseek-v4.1-flash-fast",
    messages=[
        {"role": "system", "content": "You are a careful research assistant."},
        {"role": "user",   "content": "Explain KV attention in one paragraph."},
    ],
)
print(resp.choices[0].message.content)

2. Responses: interactive agents

Stateful. The server holds reasoning and conversation state between turns, so subsequent calls can reference an earlier response by id instead of resending the full history. This preserves the model's reasoning context across turns, which measurably improves multi-step tool-using agents.

Use when: you're building an interactive agent (multi-step tool calling, iterative reasoning, threaded conversation) and a human (or an upstream agent) is waiting on the reply. Timescale: seconds.

With Zero Data Retention on, the server keeps no thread: previous_response_id returns 400. Send the full conversation in input instead.

POST /v1/responses

curl -sS -X POST https://inference.coralbricks.ai/v1/responses \
  -H "Authorization: Bearer $CORAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4.1-flash-fast",
    "input": "Sketch a plan to refactor the auth module."
  }'

Follow-up turns pass previous_response_id to continue the thread. The server carries state; you don't have to replay the transcript:

first = client.responses.create(
    model="deepseek-v4.1-flash-fast",
    input="Sketch a plan to refactor the auth module.",
)

# Same thread, no history replay needed.
next_turn = client.responses.create(
    model="deepseek-v4.1-flash-fast",
    input="OK, now do step 1 in detail.",
    previous_response_id=first.id,
)
print(next_turn.output_text)
Field Type Notes
model string Required. One of the ids from GET /v1/models.
input string or array Required. Same shape as OpenAI Responses.
instructions string Optional system / developer instructions.
previous_response_id string Continues an existing thread. Sticky-routed back to the same replica for locality.
stream boolean When true, SSE stream of Responses events.
...other OpenAI fields Forwarded verbatim.

GET /v1/responses/{id}

Retrieve any prior response by id, which is useful for auditing, resuming a UI after a page reload, or re-hydrating a thread from persistent storage. Also serves stream resumption (see background mode).

curl -sS https://inference.coralbricks.ai/v1/responses/$RESPONSE_ID \
  -H "Authorization: Bearer $CORAL_API_KEY"

DELETE /v1/responses/{id}

Delete a stored response.

Long generations and client timeouts

Streaming keeps bytes moving, but your SDK or HTTP client still owns a total-request timeout. Many OpenAI-compatible clients default to roughly 300 seconds; a large max_tokens value, a long agent turn, or a large prompt can legitimately take longer than that even while tokens stream normally.

For interactive calls:

  • Keep max_tokens aligned with what the user will actually read.
  • Set your client's timeout based on the expected whole turn, not just time-to-first-token.
  • If a call is intentionally long, use /v1/responses with background: true and poll or resume the stream rather than holding the original request open.

If the client disconnects while Coral is still generating, usage records show HTTP 499 / client_disconnected. The abandon_verdict distinguishes a normal caller hang-up from a Coral deadline miss.


3. Responses in background mode: autonomous agents

Same endpoint as above, plus one flag: background: true. The call returns immediately with a response id and status: "queued". The model then runs on Coral's cluster, not on your socket, for as long as the work takes. You poll (or resume the stream) on your own cadence.

Background mode needs the result kept until it is fetched, so background: true returns 400 with Zero Data Retention on.

Use when: the caller is not a human at a chat window. Long-running research loops, coding agents, batch pipelines, CI jobs, cron tasks, overnight runs. Timescale: minutes to tens of minutes. Nobody is waiting on the next token.

Why the shape matters for autonomous agents:

  • No HTTP hold. The socket closes when create returns. No proxy timeouts, no keepalive plumbing, no reconnect logic.
  • Survives caller death. If your agent process crashes or your CI runner is preempted, the response keeps running server-side. A fresh process retrieves by id and gets the completed result.
  • Resumable streams. If you were streaming and the socket dropped, a GET /v1/responses/{id}?stream=true from any process picks up where you left off.
  • Location-independent. Kick off from your laptop, poll from a Lambda, render in a Slack bot. One id, three consumers.

POST /v1/responses (with background: true)

curl -sS -X POST https://inference.coralbricks.ai/v1/responses \
  -H "Authorization: Bearer $CORAL_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "deepseek-v4.1-flash-fast",
    "input": "Plan a 5-step refactor for the attached repo, then execute step 1.",
    "background": true
  }'
{
  "id": "resp_01HXY…",
  "object": "response",
  "status": "queued",
  "model": "deepseek-v4.1-flash-fast"
}

GET /v1/responses/{id} (polling)

The status moves through queued → in_progress → completed | failed | cancelled. Poll on any cadence you like.

import time

queued = client.responses.create(
    model="deepseek-v4.1-flash-fast",
    input="Run the full research loop. Take your time.",
    background=True,
)

while True:
    current = client.responses.retrieve(queued.id)
    if current.status in ("completed", "failed", "cancelled"):
        break
    time.sleep(5)

print(current.output_text)

POST /v1/responses/{id}/cancel

Cooperative cancel of an in-progress background response. Queued responses flip to cancelled synchronously.

curl -sS -X POST https://inference.coralbricks.ai/v1/responses/$RESPONSE_ID/cancel \
  -H "Authorization: Bearer $CORAL_API_KEY"

Stream + background

You can combine stream: true with background: true. The initial call returns an SSE stream that you can consume; if the socket drops or you want a second consumer, GET /v1/responses/{id}?stream=true picks up from where the last event left off. Useful when the agent loop and the renderer live on different machines.


Session IDs

Pass your own conversation ID in the x-session-id header: one ID per conversation, the same value on every turn of it, and never one ID shared across users or unrelated calls. CoralBricks records it with each request, so the requests of one conversation can be found together, for example when you ask support about a slow or failed turn. It changes nothing else: routing, caching and billing are the same with or without it.

resp = client.chat.completions.create(
    model="deepseek-v4.1-flash-fast",
    messages=messages,
    extra_headers={"x-session-id": conversation_id},
)
const resp = await client.chat.completions.create(
  { model: "deepseek-v4.1-flash-fast", messages },
  { headers: { "x-session-id": conversationId } },
);
  • One ID per conversation, not per process or per user. Use your own conversation or thread ID, or a UUID you generate when the conversation starts. A client-wide default header puts every conversation into one session.
  • Any string works. Up to 512 characters are recorded.
  • Coding agents that send their own session ID need nothing: OpenCode and Kilo Code do. A request with no session ID is recorded under its prompt_cache_key when it has one.
  • The ID is request metadata, kept as described in the privacy policy. The No content + no metadata level of Zero Data Retention drops it.

X-Coral-Session on Responses

On /v1/responses, the X-Coral-Session header also continues the thread. When a request carries it and no previous_response_id, CoralBricks continues from the last stored response of that session, so a client that can't keep track of response ids still gets a threaded conversation. An explicit previous_response_id takes precedence, and store: false requests ignore the header. Sessions are scoped to your account.

Because it joins turns together, this matters even more here: pass your own conversation ID, one per conversation, and never a value shared across users or unrelated conversations, or their turns are chained into one thread. To label requests only, use x-session-id. On /v1/chat/completions, X-Coral-Session is recorded like x-session-id.


Streaming

Every surface supports OpenAI-shape SSE streaming via stream: true. Consume it exactly as you would from OpenAI's SDK. See the background section above for stream resumption via GET.

The balance may take up to ~30 seconds to reflect a top-up or completed inference charge because API-key account data is briefly cached.


Errors

Errors follow the OpenAI error shape:

{"error": {"message": "…", "type": "…", "code": "…"}}
Status code Meaning
400 bad_request / model_required The body isn't valid JSON, or a required field is missing.
400 invalid_request A field has a value the model can't accept, e.g. an unknown message role, or a max_tokens above the model's context window. param names the field when the gateway can tell.
400 context_length_exceeded The prompt plus the output budget doesn't fit the model's context window. See Context length.
400 unsupported_value A field has a value the model doesn't support, e.g. an unknown reasoning effort. param names the field and the message lists the values it takes.
400 invalid_prompt_cache A prompt cache field is invalid, e.g. a prompt_cache_key over 512 characters. The message names the field.
401 missing_api_key / invalid_api_key Auth header absent or rejected. Re-mint at /api-keys.
403 access_denied The key's account can't use this endpoint. Contact us if you think that's wrong.
404 model_not_accepted The model id isn't enabled for your account or doesn't match a known id.
404 model_retired The model is no longer served. The message names the model to use instead.
404 response_not_found Wrong response_id, or it belongs to another account.
429 rate_limit_exceeded Per-API-key rate limit. Slow down and retry with backoff.
429 concurrency_limit Your account already has as many requests in flight as it may. Retry after Retry-After (2 seconds).
499 client_disconnected The caller closed the connection. For long generations, use background mode or raise the client's whole-request timeout.
502 upstream_error Upstream model server returned an error. Safe to retry.
503 backend_unconfigured Transient. Retry.
504 timeout Sync request waited too long. Re-issue with background: true.

Context length

A request fits when its prompt tokens plus its output budget (max_tokens, or max_output_tokens on Responses) are at most the model's context window: 1,048,576 tokens on every model today (context_length on each /v1/models row). A request that doesn't fit is refused before any generation, so a stream is never cut off part-way by the limit.

  • Leave the output budget out, on Chat Completions and Responses, and the gateway uses the room the prompt leaves, so a long prompt is only refused when the prompt alone is over the window. Background responses (background: true) don't do this yet: there, send a budget that fits.
  • Send an explicit budget and it has to fit alongside the prompt. /v1/messages always takes one: max_tokens is required there, as it is on Anthropic's API.

The error says how many tokens were asked for, so a client can shorten the conversation, or lower the budget, and retry.

On Chat Completions and Responses the code is context_length_exceeded:

{"error": {"message": "This model's maximum context length is 1048576 tokens. However, you requested 1051081 tokens (920009 in the messages, 131072 in the completion). Please reduce the length of the messages or completion.", "type": "invalid_request_error", "code": "context_length_exceeded", "param": "messages"}}

When the prompt alone is over the window, the message reads However, your messages resulted in 1200009 tokens. Please reduce the length of the messages.

On /v1/messages the error is Anthropic's invalid_request_error, with Anthropic's wording:

{"type": "error", "error": {"type": "invalid_request_error", "message": "input length and `max_tokens` exceed context limit: 920009 + 131072 > 1048576, decrease input length or `max_tokens` and try again"}}

When the prompt alone is over the window, the message reads prompt is too long: 1200009 tokens > 1048576 maximum.

On a streaming request the status is 200 and the error is the stream's one event, because the stream opens before the request has been checked. Read the event, not the status:

  • Chat Completions: a single data: {"error": {…}} line, with no finish_reason and no [DONE].
  • Responses: response.created, response.in_progress, then error and response.failed, both carrying the code.
  • /v1/messages: message_start, ping, then error.

Coding agents use these messages to tell a full context from a failed request: they shorten the conversation and retry. An output budget that is itself above the window (say max_tokens: 2000000) is a different error, invalid_request with param: "max_tokens": no amount of shortening the prompt would make it fit.


Support