Serverless Inference API
The OpenAI-compatible /v1 API in full: chat, embeddings, image and video, tool calling, the Anthropic Messages endpoint, plan coverage and errors.
deeprelay's serverless inference is an OpenAI-compatible HTTP API: point any
OpenAI SDK (or curl, or the deeprelay CLI) at it and call chat completions,
embeddings, image generation, video generation, and the model catalog. You pay
per token (or per image / per video-second) — no instances to manage.
Base URL & authentication
| Base URL | https:/ |
| Auth | Authorization: Bearer deeprelay_live_… |
Get a key with deeprelay login (it stores a deeprelay_live_… key in
~/.config/deeprelay/credentials.json) or mint one in the dashboard. Scopes:
serverless:read lists models, serverless:write runs
chat/embeddings/image/video,
billing:read reads usage; a full_access key covers all three.
Every key you mint belongs to this production host. Any other deeprelay host
you may see in an older example is internal staging with its own key store,
so a production key gets a 401 there. /v1 is the
API version and the only one there is; the OpenAPI document's 1.0.0 is the
revision of that /v1 contract.
Calling from a browser
The /v1 API accepts cross-origin requests from any website, so browser-based
clients that bring your own key (TypingMind and similar chat front ends) can
call it directly. Requests authenticate with your API key, never with cookies,
and responses expose the request id, rate-limit, quota and error-code headers
to the page. Anyone who can read the page can read the key, so use a key with
only the scopes it needs, and a model allowlist or
monthly budget where it matters.
Trial keys
If someone at deeprelay sent you a trial key, it is a normal deeprelay_live_…
API key with trial credit already loaded — no account or sign-in needed. Use it
exactly like any other key against the base URL above:
export DEEPRELAY_API_KEY=deeprelay_live_… # the key you were sent
curl https://api.deeprelay.ai/v1/chat/completions \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/deepseek-v4-pro","messages":[{"role":"user","content":"Hello!"}]}'
Or with an OpenAI SDK, set base_url="https://api.deeprelay.ai/v1" and api_key
to the trial key. GET /v1/models lists every model and its per-token price
(it also answers without a key, with the same list);
the DeepSeek, GLM and Kimi families are the ones the trial is meant for.
What a trial key can and cannot do:
- Scope: serverless inference (
serverless:write) plus reading its own balance (billing:read). It cannot launch GPU instances or mint other keys. - Credit is the cap.
GET /v1/billing/balanceshows what is left. When the balance reaches zero, requests return402 insufficient_balance. - It expires on the date in the message you received (30 days by default). After that, inference calls (
/v1/chat/completions,/v1/modelsand the other OpenAI-compatible routes) return401with the OpenAI-style error codeunauthorized;GET /v1/billing/balancereturns the RFC 7807 problem codeinvalid_api_key. - Limits default to 10 requests/second (burst 20) and 20 requests open at once, enough for trying models by hand. If you need more, for a benchmark say, ask whoever sent you the key: they can mint one with a higher rate, more concurrency, or a tokens-per-minute cap per model. Going over the rate or concurrency limit returns
429. - To keep going after the trial, sign up at deeprelay.ai and mint your own key — trial credit does not transfer.
Plan coverage
Models the subscription covers carry "plan_covered": true in
GET /v1/models (and a PLAN/Plan marker in deeprelay models list /
deeprelay models get) — a subscriber's requests to those models draw on the plan's
monthly allowance first; everything else bills pay-as-you-go.
GET /v1/billing/subscription (CLI: deeprelay billing subscription) reports
which plan you are on and how much of its allowance is left.
There are two plans, covering the same models at the same factors: Base
($0.99/month, 500M input and 50M output weighted tokens a month) and
Plus ($4.99/month, 2.5B tokens a month: 2.5B input and 250M output). The
plans array on GET /v1/billing/subscription lists both with their
prices and allowances. Subscribe to either with
deeprelay billing subscribe --plan plus (or flat); move an existing
subscription up with deeprelay billing upgrade (POST
/v1/billing/subscription/upgrade), which charges the full Plus price at
once and starts a fresh billing period — and fresh meters — that moment.
You can also pay for a plan from your deposited balance instead of a card:
deeprelay billing subscribe --plan plus --from-balance,
deeprelay billing upgrade --from-balance, or POST
/v1/billing/subscription/pay-from-balance. Only deposited money can pay:
card and UPI deposits once they are 24 hours old, auto-pay top-ups and settled
crypto deposits. Free credit, such as referral bonuses, promo matches, credit
codes and post rewards, pays for usage but never for a plan, and usage spends
it first. The plan's full price must be covered; there is no split with a card.
A plan started from balance renews from balance each month while your
deposits cover it, otherwise your saved card is charged and your admins get an
email. Turn that on or off with deeprelay billing renew-from-balance on|off
(PUT /v1/billing/subscription/renew-from-balance). GET
/v1/billing/subscription shows the setting as renew_from_balance and what
your balance can pay as balance_payment.
Each covered model carries a usage factor, reported as usage_factor_milli
(×1000) on GET /v1/models and omitted for a model at the default 1.0×
(treat a missing field as 1000): a model at factor 12 draws twelve weighted tokens
from the allowance for every token it serves. The plans' roster, factors
and allowances are in the subscription tier spec.
Being subscribed does not make every model free. Every chat response reports
what it cost in usage.cost (see Cost in the response),
but that only tells you after the fact. To know before you send, ask:
GET /v1/inference/preflight?model= returns ok / warn / block for
that exact model, computed from the same gates that will judge the request —
plan coverage, entitlement, remaining quota, credit and spending caps. The
deeprelay CLI runs it automatically before chat, embeddings, image and
video create, warning when a call will bill pay-as-you-go and refusing when
it would be denied; deeprelay preflight asks it directly, and
--no-preflight turns the automatic check off.
Tiers — serverless (default) and economy
A model can have two tiers:
- serverless (default) — low latency, no cold start. Use the bare model id, e.g.
deeprelay/deepseek-v4.1-flash. - economy — cheaper, compute-priced, may cold-start ~30–60s. Opt in with the
:economysuffix, e.g.deeprelay/.:economy
Economy exists only where GET /v1/models lists the suffixed id as its own
entry. Check the live catalog before relying on it: a :economy id the
catalog does not list returns model_not_found, and there are times when no
model has an economy tier at all.
deeprelay models list shows both tiers as separate rows with their own pricing.
The serverless catalog is live
The serverless catalog is built from the models our upstream partners are
actually serving warm right now — not a hand-maintained list. It is
refreshed roughly hourly and probe-verified, so GET /v1/models always reflects
what you can call this minute. Each entry carries name, author (the model's
creator — e.g. Meta, Qwen, Black Forest Labs), category (mirrors
modality: chat, embeddings, image, or video), and pricing (the cheaper
option when a model is served by more than one partner). Chat
models are priced per 1M tokens (input_per_1m_tokens_cents /
output_per_1m_tokens_cents), plus an optional discounted rate for the
cache-hit part of the prompt (cached_input_per_1m_tokens_microcents — see
Prompt caching below). Embedding models are priced per 1M input
tokens only (input_per_1m_tokens_cents); they emit no output tokens, so
output_per_1m_tokens_cents is absent. Image models are priced per output
megapixel when the partner meters that way (per_mpxl_microcents, in
micro-cents — e.g. 270000 = $0.0027/Mpxl), otherwise with a representative
per-image "from" price (per_image_microcents). Video models are billed per
second of output video (per_video_second_microcents); the per-clip
per_video_microcents value is the representative "from" price for the
model's default clip. The set of authors we surface grows over time.
Because the catalog is live, a model can occasionally drop out between refreshes.
If you call one that just became unavailable you'll get a clear
model_not_found error asking you to try another — see Errors below.
Using the deeprelay CLI
# Discover models
deeprelay models list --modality chat
deeprelay models get deeprelay/deepseek-v4.1-flash
# Chat (streams tokens)
deeprelay chat deeprelay/deepseek-v4.1-flash "Explain recursion in one sentence"
# Embeddings (one vector per input; -o json for the full vectors)
deeprelay embeddings deeprelay/qwen3-embedding-8b "first sentence" "second sentence"
# Image generation (writes out.png)
deeprelay image "a watercolor fox in a misty forest" --model deeprelay/flux.2-dev
# Video generation (async: submit, poll, download)
deeprelay video create --model deeprelay/seedance-1.0-lite --prompt "ocean waves at sunset" --wait 10m
deeprelay video download <video-id> --out waves.mp4
# Usage / spend
deeprelay usage --modality chat --bucket month
# On a plan: which one, plus how much quota is left
deeprelay billing subscription
# Will this model draw on the plan, or on credit?
deeprelay preflight deeprelay/deepseek-v4.1-flash
# Start a subscription (prints a link to open)
deeprelay billing subscribe # Base; --plan plus for the bigger plan
# Cancel at the end of the paid period (undo with `billing resume`)
deeprelay billing cancel
# Cards and UPI IDs: what each pays for; add, remove, fix a failed renewal
deeprelay billing payment-methods
# Move an existing subscription from Base to Plus (charges the card on file)
deeprelay billing upgrade
# Refer a friend: when they deposit $50, you each get $25 in credit
deeprelay referral
See the per-command reference: chat, embeddings, image, video, models, usage, preflight, billing subscription, billing subscribe, billing cancel, billing payment-methods, referral (see the refer-a-friend guide).
OpenAI compatibility
The chat request and response shapes, streaming, tool calling and the error envelope match OpenAI's. Each OpenAI chat parameter falls into one of four groups:
- Forwarded to the model as sent.
- Gated per model. It is sent only to a model whose
GET /v1/modelsentry lists it insupported_parameters. Any other model gets a400unsupported_parameterbefore anything is billed, and the error message names the models that do support it. - Hints. Forwarded when the upstream serving your request accepts them, otherwise dropped. They are never rejected, and every drop is reported in the
x-deeprelay-ignored-paramsresponse header. - Rejected everywhere with a
400.
| Parameter | Handling |
|---|---|
model, messages | Forwarded. content may be a string, null, or an array of parts. Text parts ([{"type":"text","text":"…"}]) are joined with newlines. For image parts, see Image input. Roles are system, user, assistant and tool; developer is treated as system. |
temperature, top_p, max_tokens, stop, n, user | Forwarded. |
max_completion_tokens | Forwarded as max_tokens. If you send both, max_tokens wins. |
stream, stream_options | Forwarded. |
tools, tool_choice | Gated: tools (see Tool calling). finish_reason is tool_calls when the model makes a call. |
response_format | Gated: response_format for json_object, structured_outputs for a strict json_schema (see JSON mode & structured outputs). |
logprobs, top_logprobs | Gated: logprobs (see Log probabilities). |
image_url content parts | Gated: vision (see Image input). |
reasoning_effort, presence_penalty, frequency_penalty, seed, parallel_tool_calls | Hints (see Reasoning effort and sampling hints). |
logit_bias, function_call | Rejected: 400 unsupported_parameter. |
input_audio, file content parts | Rejected: 400 unsupported_content_part, param: "messages". |
Parameters outside this table are accepted and not sent to the model.
Completion ids. A chat completion's id is chatcmpl- followed by the
request id, the same value as the x-request-id response header, on both
sync and streaming responses. Quote either one when you contact support.
Check supported_parameters before you send a gated parameter. It is
per model, and it is backed by live probes of each model's upstreams rather
than copied from a model card. Suppose a model supports a parameter but none of
its upstreams that can take it is available right now. The request fails with
503 upstream_unavailable rather than going to an upstream that would
silently ignore it.
A dropped hint changes the model's behaviour, not whether the request
succeeds. Read x-deeprelay-ignored-params if the hint matters to you.
x-deeprelay-ignored-params
This header is present only when something you sent was not applied as sent. Its value is a comma-separated list of tokens:
| Token | Meaning |
|---|---|
reasoning_effort, presence_penalty, frequency_penalty, seed, parallel_tool_calls | The serving upstream does not accept this hint (or this value of it), so it was dropped. |
response_format:downgraded | A non-strict json_schema was served as json_object: the reply is valid JSON but not checked against your schema. |
parallel_tool_calls:enforced | You sent parallel_tool_calls: false to an upstream that can't honour it. deeprelay returned only the first tool call. |
image_url.detail | An image part carried detail. It is accepted for compatibility but never forwarded. |
The header describes the upstream that actually served the response. A fallback attempt that failed never adds tokens to it. The header appears on streaming responses too, because it is sent before the first chunk (but see slow starts below).
x-deeprelay-reasoning-effort
deeprelay never picks a reasoning effort for you. This header tells you which effort the model was actually sent, so you can tell a model that reasoned because you asked it to from one that reasoned because you set nothing.
| Value | Meaning |
|---|---|
model-default | No effort reached the model, so it used its vendor default. Either you sent no reasoning_effort, or the one you sent was dropped (then x-deeprelay-ignored-params lists reasoning_effort as well). |
none, minimal, low, medium, high, xhigh, max | The effort the serving upstream received. |
The header is sent on /v1/chat/completions, /v1/responses and
/v1/messages, on streaming responses too. It is left out for a model that
has no reasoning control (one whose GET /v1/models entry lists no
reasoning_efforts). See
When you don't set reasoning_effort
for what the default costs and how to change it.
When a stream starts slowly
If no upstream has started answering a streaming request after about 5
seconds, deeprelay sends the 200 and the SSE headers right away and writes
: keepalive comment lines, which every SSE client ignores, until the first
token arrives. A client with a first-byte timeout therefore keeps waiting
instead of giving up and resending the whole request. Switching to another
upstream, or to a backup model, still happens before the
first token. On such a stream:
- a failure arrives as an SSE
errorevent followed bydata: [DONE], with HTTP status200, exactly like a failure mid-stream. Errors that come back sooner (an invalid request, a rate limit) keep their usual HTTP status; x-deeprelay-ignored-paramslists only the parameters dropped on every upstream, and when a backup model could still take over,X-Deeprelay-Served-Modelis left out: themodelfield of every chunk names the model that answered;x-deeprelay-reasoning-effortis sent only when you set noreasoning_effort(it readsmodel-default, which holds on every upstream) and no backup model could still take over.
Using the OpenAI SDK
Because the API is OpenAI-compatible, the official SDKs work unchanged for
chat (within the table above). Just override base_url and api_key:
from openai import OpenAI
client = OpenAI(
base_url="https://api.deeprelay.ai/v1",
api_key="deeprelay_live_…",
)
# Chat (streaming)
stream = client.chat.completions.create(
model="deeprelay/deepseek-v4.1-flash",
messages=[{"role": "user", "content": "Explain recursion in one sentence"}],
stream=True,
)
for chunk in stream:
print(chunk.choices[0].delta.content or "", end="")
Controlling reasoning
You choose how much a model reasons, per request, with reasoning_effort.
Set it on any chat request: the OpenAI SDK, curl, the deeprelay CLI
(--reasoning-effort) and every OpenAI-compatible client pass it through.
resp = client.chat.completions.create(
model="deeprelay/deepseek-v4.1-flash",
messages=[{"role": "user", "content": "Is 9.11 bigger than 9.9?"}],
reasoning_effort="high", # or "none" | "low" | "medium" | "xhigh" | "max"
)
print(resp.choices[0].message.reasoning_content) # the model's reasoning
print(resp.choices[0].message.content) # the answer
curl https://api.deeprelay.ai/v1/chat/completions \
-H "Authorization: Bearer deeprelay_live_…" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/deepseek-v4.1-flash","reasoning_effort":"low",
"messages":[{"role":"user","content":"hi"}]}'
deeprelay chat deeprelay/deepseek-v4.1-flash "hi" --reasoning-effort none
- Which values a model takes: its
GET /v1/modelsentry lists them inreasoning_efforts.noneis listed only where it really turns reasoning off; on a model that always reasons it is dropped and reported inx-deeprelay-ignored-paramson Chat Completions, and rejected with a 400 on/v1/responses(as any unlisted effort is there). See Reasoning effort and sampling hints. - If you don't set it, the model reasons at its vendor default, which on most reasoning models means it thinks before it answers. Those reasoning tokens are billed as output. Pass
"none"(or"low") for a fast, cheap answer. See When you don't setreasoning_effort. - Where the reasoning text comes back:
message.reasoning_contenton a non-streaming response,delta.reasoning_contenton each chunk when you stream. - What was applied: the
x-deeprelay-reasoning-effortresponse header names the effort the model received, ormodel-defaultwhen none reached it. For benchmarks, setreasoning_effortexplicitly on every request and check this header, so every model runs at a known effort.
Coding agents
The same base URL and key work in coding agents that accept a custom OpenAI-compatible provider, such as Cline, Kilo Code, Roo Code, OpenCode, Aider, Continue, Zed, Cursor, Pi, Kimi Code, Deep Code, DeepSeek Harness and ZCode. Coding agents has the config for each and the models to pick for tool calling.
Reasoning sent back. Agents built for DeepSeek's thinking mode echo each
assistant turn's reasoning_content back on the next request. On models that
keep reasoning across turns (deeprelay/deepseek-v4.1-flash,
deeprelay/deepseek-v4-pro) that reasoning is passed to the model again, so
it continues from where it left off instead of re-reasoning every turn; it
counts as prompt tokens. Other models drop it quietly, and so does a backup
model that does not keep reasoning. reasoning_content is read only on
assistant messages.
Claude Code uses the Anthropic Messages API instead. Run
deeprelay setup claude-code, and see Claude Code and
Anthropic Messages API below.
SDKs and gateways
The same two settings work in the application-side SDKs and gateways that take an OpenAI-compatible provider. Each has its own guide with the exact configuration, tool calling, structured output and embeddings:
- Vercel AI SDK through
@ai-sdk/openai-compatible. - LiteLLM, SDK and proxy, with the
openai/model prefix. - Portkey as an OpenAI-compatible custom host.
Using curl
# List models
curl https://api.deeprelay.ai/v1/models \
-H "Authorization: Bearer deeprelay_live_…"
# Chat completion (non-streaming)
curl https://api.deeprelay.ai/v1/chat/completions \
-H "Authorization: Bearer deeprelay_live_…" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/deepseek-v4.1-flash","messages":[{"role":"user","content":"hi"}]}'
Anthropic Messages API
deeprelay also serves the Anthropic Messages API at POST /v1/messages, so
Claude Code and the Anthropic SDKs can use deeprelay models. For Claude Code,
run deeprelay setup claude-code. Claude Code is the full
guide. The Anthropic SDKs take the base URL without /v1
(https://api.deeprelay.ai).
curl https://api.deeprelay.ai/v1/messages \
-H "x-api-key: deeprelay_live_…" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/deepseek-v4-pro","max_tokens":256,"messages":[{"role":"user","content":"hi"}]}'
- Auth: send the key as
x-api-keyor asAuthorization: Bearer. - Models: use deeprelay model IDs. A
claude-*model ID is rejected with400(claude_model_not_served) and a message telling you to rundeeprelay setup claude-code. deeprelay doesn't alias Claude names to other models. - Supported: text, tools, streaming (with
pingkeep-alives), thinking, prompt caching and theweb_search_20250305server tool (see Web search).cache_controlmarkers are accepted, and caching happens automatically where the model supports it. - Thinking and reasoning effort: this API has no effort parameter.
thinking.typedecides whether thinking blocks come back in the response (adaptiveandenabledask for them,disabledand nothinkingfield leave them out). It is not sent to the model as an effort, so the model reasons at its vendor default either way and those tokens count as output tokens. Thex-deeprelay-reasoning-effortresponse header readsmodel-defaultto say so. It is left out when a thinking budget is forwarded to the model. - Not supported, each rejected with a
400:- every other server-side tool, such as web fetch, code execution and other versions of web search (
server_tool_unsupported; the message names the supported version). Use an MCP server in the client instead; mcp_serversandcontainer(server_side_feature_unsupported);- document and PDF blocks;
- a user image in the newest user message on a model without vision support (
unsupported_capability; the message names the models that accept images). Todaydeeprelay/deepseek-v4.1-flash,deeprelay/glm-5.3-flash,deeprelay/kimi-k3,deeprelay/kimi-k3.1-proanddeeprelay/qwen3.5-9baccept images on this endpoint.
- every other server-side tool, such as web fetch, code execution and other versions of web search (
- Images that are not rejected: on a model without vision, an image in an earlier turn or inside a
tool_resultis replaced by a text note saying an image was omitted. On a vision model, an image inside atool_resultis moved into user content right after the tool result, because most models take tool results as text only. The response headerx-deeprelay-ignored-paramsthen listsimage:omittedand/orimage:moved. - Stop sequences:
stop_sequencesare honoured, but when one ends the response the result saysstop_reason: "end_turn"withstop_sequence: null, because the models behind this endpoint do not report which sequence matched. - Token counting:
POST /v1/messages/count_tokensreturns an estimate, marked with the headerx-deeprelay-token-count: estimated. It is never billed. - Errors use the Anthropic envelope,
{"type":"error","error":{"type":"…","message":"…"},"request_id":"…"}. The deeprelay code rides in theX-Deeprelay-Error-Codeheader, from the same set of codes as the rest of the API (see Errors). - Billing is the same as a chat completion on the same model. Rejected requests are not billed.
OpenAI Responses API
deeprelay also serves the OpenAI Responses API at POST /v1/responses, so
Codex CLI and the OpenAI SDK's responses.create() can use
deeprelay models. For Codex, run deeprelay setup codex; Codex CLI
is the full guide. The base URL is the same as for chat
(https://api.deeprelay.ai/v1), and auth is Authorization: Bearer.
curl https://api.deeprelay.ai/v1/responses \
-H "Authorization: Bearer deeprelay_live_…" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/deepseek-v4-pro","input":"hi","store":false}'
- Sync and stream.
stream: truereturns the Responses event stream (response.created…response.completed), with keep-alive comments while the model is thinking. Without it you get oneresponseobject. The id isresp_plus the request id, andmodelis the deeprelay model ID. - Models: use deeprelay model IDs. An OpenAI model ID such as
gpt-5, or any ID that is not a chat model in the catalog, is a400model_not_found, with a message namingdeeprelay setup codexand a few models to use instead. deeprelay doesn't alias model names. - Input:
inputis a string or an array of items. Supported items aremessage,function_call,function_call_output,reasoningandweb_search_call; any other item type is a400unsupported_item_type. An item with aroleand notypeis amessage, as the OpenAI SDKs send it.input_textandinput_imageparts work (images on vision models only);input_fileandinput_audioparts are a400unsupported_content_part. - Tools:
functiontools work, and theircall_ids are minted by deeprelay. Tools grouped in anamespaceare flattened into ordinary function tools. The hostedweb_searchtool runs a live search whenexternal_web_accessistrueor omitted (see Web search). Withexternal_web_access: false, which is what Codex sends unless live search is turned on, it is dropped and reported as ignored, so a client that always declares it keeps working. Other hosted tools (web_search_preview,file_search,computer_use,image_generation,code_interpreter,mcp) and thelocal_shell,shell,apply_patchandcustomtool types are a400unsupported_tool_type. - Reasoning:
reasoning.efforttakes the values the model lists inreasoning_efforts(see Reasoning effort and sampling hints). Unlike chat'sreasoning_effort, a value the model does not list is a400naming the ones it takes, so a Codex user with an unsupportedmodel_reasoning_effortfinds out why. A listed value that the serving upstream cannot take is dropped and reported, as on chat. Leave it out and the model reasons at its vendor default; thex-deeprelay-reasoning-effortresponse header then readsmodel-default. Areasoningoutput item appears only when you ask for it: withreasoning.summaryset you get the model's own reasoning text as the summary (no extra summarisation, so every summary level gives the same text), and withinclude: ["reasoning.encrypted_content"]you get anencrypted_contentblob to send back on the next turn. Reasoning sent back is passed to the model again on models that keep reasoning across turns, and dropped quietly otherwise or when it came from another model. Reasoning tokens are reported inusage.output_tokens_details.reasoning_tokensand billed as output tokens. - Structured outputs:
text.formattakestext,json_objectandjson_schema, with the same per-model gating as chat'sresponse_format(see JSON mode & structured outputs). - Ignored fields: anything not applied as sent is listed in
x-deeprelay-ignored-params, for examplestore:ignoredandtools.web_search:ignored(theexternal_web_access: falseshape). Fields with no meaning here, such asparallel_tool_calls,truncation,service_tierand OpenAI's cache-routing hint, and unknown top-level fields, are accepted and ignored.
deeprelay is stateless on this endpoint. It stores no responses and no
conversations, so every request must carry the full conversation in input:
| You send | Result |
|---|---|
store: true (or store omitted) | Accepted, nothing is stored. store is echoed as false; store: true is listed as store:ignored in x-deeprelay-ignored-params |
previous_response_id, conversation, background: true | 400 stateless |
context_management | 400 compaction_unsupported. Compact on the client |
The routes that only make sense with stored responses answer cleanly instead of looking for one:
| Method | Path | Result |
|---|---|---|
GET | / | 404 stateless |
DELETE | / | 404 stateless |
POST | / | 404 stateless |
GET | / | 404 stateless |
POST | / | 400 compaction_unsupported |
Other behaviour to know:
- Errors use the OpenAI envelope, with the deeprelay code in
X-Deeprelay-Error-Codeas everywhere else (see Errors). Upstream overload, including a rate limit reported by the model's upstream, is a503upstream_rate_limitedwithRetry-After, never a429: a429on this endpoint is always about your own key or plan. A prompt that does not fit the model is a400context_length_exceeded. A failure after the stream started arrives as aresponse.failedevent. - Cost: a sync response carries
usage.costandusage.cost_details(see Cost in the response) and thex-deeprelay-costheader. A stream has no cost header; the cost is in theresponse.completedevent'susage.cost. - Rate-limit and quota headers are the OpenAI-format ones (
x-ratelimit-*, and the subscription quota headers). - Billing is the same as a chat completion on the same model. Rejected requests, including every sub-route above, are not billed.
Web search (server tool)
deeprelay runs web search for the model on POST /v1/messages and
POST /v1/responses. You declare the search tool and the model decides when
to search. deeprelay then runs the search, gives the results to the model and
streams the model's answer back, all within one request. This is what makes
Claude Code's WebSearch and Codex's live search work (see
Claude Code and Codex CLI). Chat completions
has no server tools.
- Models: any chat model that supports tool calling.
GET /v1/modelsshows"web_search": trueon these models. A search tool on any other model is a400with codeweb_search_unsupported_model, and the message names the model. - Citations: deeprelay returns the spec-shaped result blocks and items described below. It does not add citation objects. The model cites its sources in its own prose.
- The request stays
200. If a search fails, the model gets an in-band error result and answers without it. A provider error or timeout givesunavailable, and a rate limit givestoo_many_requests. The request itself still succeeds. - Searches have a time limit per request, 90 seconds by default. After it, further searches return
unavailableand the model gets one more step to answer from what it already found. Searches that ran before the limit are billed as usual.
On the Messages API
Declare web_search_20250305. It is the only version deeprelay runs: any
other version (for example web_search_20260209) is a 400
server_tool_unsupported naming the supported one.
"tools": [{
"type": "web_search_20250305",
"name": "web_search",
"max_uses": 5,
"allowed_domains": ["docs.python.org"],
"user_location": {"type": "approximate", "country": "GB"}
}]
nameisweb_searchor omitted. The tool may be declared once per request.max_uses(at least 1) limits searches in this request. deeprelay also applies a server ceiling of 10, and the lower of the two wins. Once the limit is reached, the model gets amax_uses_exceededresult and the turn continues.allowed_domains/blocked_domainsare always enforced: deeprelay filters the results itself, whatever the search provider did with the list. Use one list or the other; setting both is a400. An entry is a bare host such asexample.com, optionally followed by a/path. Subdomains match, soexample.comcoversdocs.example.com. Paths match regardless of case, soexample.com/Privatealso covers/private. An entry may not include a scheme or a wildcard host. Send internationalised names in theirxn--form. The two lists can hold at most 200 entries in total.user_location:typemust beapproximate.country(ISO 3166-1 alpha-2) is honoured.city,regionandtimezoneare accepted but not used, and are listed inx-deeprelay-ignored-params.- Response blocks: each search appears in
contentas aserver_tool_useblock (idsrvtoolu_…,nameweb_search,input.query), followed by aweb_search_tool_resultblock whosecontentis a list ofweb_search_resultitems (url,title,page_age,encrypted_content). A failed search instead carries{"type": "web_search_tool_result_error", "error_code": "…"}. The codes areunavailable,too_many_requests,max_uses_exceeded,query_too_longandinvalid_tool_input. When streaming, deeprelay sendspingevents while a search runs. encrypted_contentis opaque. It carries the result text, sealed to the model and the tool call. Send the blocks back unchanged on later turns, and deeprelay verifies its own blobs and gives the model the result text again. Blocks deeprelay did not issue, such as those from a session started on Anthropic's API, or blocks that fail verification are not rejected. Their visible title and URL are kept as context and the rest is dropped.tool_choice: the search tool counts as a declared tool.{"type": "any"}can be met by a search, and{"type": "tool", "name": "web_search"}makes the model search. A forcing choice applies to the model's first step only. After the search results come back, the model may answer instead of being forced to call a tool again.- Usage:
usage.server_tool_use.web_search_requestsis the number of billed searches in the response.
On the Responses API
Declare {"type": "web_search"}. It runs a live search when
external_web_access is true or omitted. With
external_web_access: false, the tool is dropped and listed as
tools.web_search:ignored, and nothing is searched or billed.
"tools": [{
"type": "web_search",
"filters": {"allowed_domains": ["docs.python.org"]}
}]
filters.allowed_domains(andfilters.blocked_domains) are always enforced, with the same entry format and 200-entry limit as on Messages.user_location.countryis honoured.search_context_sizeanduser_location.city/region/timezoneare accepted but not used, and are listed inx-deeprelay-ignored-params.- There is no
max_uses. The server ceiling of 10 searches per request applies. tool_choice:{"type": "web_search"}makes the model search, and"required"can be met by a search. Either needs a liveweb_searchtool intools; without one,{"type": "web_search"}is a400. As on Messages, a forcing choice applies to the model's first step only.- Output: each search is a
web_search_calloutput item withidws_…, astatus, and anactionof typesearchwith itsquery. When streaming, it comes with theresponse.web_search_call.in_progress,.searchingand.completedevents. Addinclude: ["web_search_call.action.sources"]to get the source URLs inaction.sources. - Sent back on a later turn, a
web_search_callitem is kept as context: the model sees its query and source URLs. Nothing on this endpoint is sealed. The result text itself is not re-sent, and there is noencrypted_contentslot on the item. - Usage:
usage.deeprelay_web_search_requestsis the number of billed searches. It is a deeprelay extension (the Responses spec has no such field), present on any response whose request declared a liveweb_searchtool.
Searches and your own tools in one turn
If the model calls web search and one of your own tools in the same turn, deeprelay runs the searches first. It then returns your tool calls to you as usual, with the search blocks or items earlier in the same response. After you send the tool results back, the model continues with both.
Pricing
Searches are billed per search at the list price, currently $2.00 per 1,000
searches, i.e. $0.002 each. The list price is reported as
pricing.per_search_microcents on GET /v1/models and shown in
usage.cost. Only searches that run are billed:
failed and duplicate searches are not billed; a search that succeeds is billed even with zero results.
A duplicate is an identical query repeated within the same request, which
is served from the first result.
- Result text is input. The search results the model reads are billed as ordinary input tokens at the model's price. That includes later turns, when your client sends the results back as conversation history.
- Result size is capped. A search gives the model at most 8 results, each cut to 1,200 characters, which bounds the input it adds.
- Rejected requests are never billed, including a
web_search_unsupported_model400.
Plan allowance
On a subscription plan, searches come out of a monthly allowance instead: Base includes 100 searches a month and Plus includes 500. It is a monthly window only, with no weekly search cap, and it resets with your billing period. Zero-result searches count against it. The result tokens count against the plan's token quota at the model's usage factor, like any other input.
- Headers: responses carry
x-deeprelay-quota-search-remainingandx-deeprelay-quota-search-limitnext to the other subscription quota headers.deeprelay quotashowsWeb searches N / M this month. - When it runs out, the search returns a
max_uses_exceededresult and the turn continues. The text the model receives names the allowance, the date it resets and how to turn on paid overflow. - If deeprelay cannot read your search count, the request still runs on your token quota. Its searches return
unavailable, or run as paid overflow if you turned that on, and the search quota headers are left off that response. A search is never run free of the allowance.
Paid overflow lets searches continue past the allowance, billed to your balance. It is off by default.
- Turning it on:
PUT /v1/search/settingswith{"overflow_enabled": true},deeprelay quota search-overflow on, or the toggle on the dashboard's Billing page.GET /v1/search/settingsshows the current setting. - Who can change it: an org admin, or a
full_accesskey. Every change is audited. - What is billed: only the per-search fee moves to your balance. Overflow searches are billed at cost: currently $1.00 per 1,000 searches, shown as
overflow_usd_per_thousandonGET /v1/search/settings; this is separate from the pay-as-you-go search price. - Tokens stay on the plan. Result tokens and every other token on the request still count against your token quota.
- Admission: each overflow search goes through the normal wallet checks: balance, org spend limits, the key's budget and member limits. If any of them refuses, the model gets the exhausted result instead, and the request does not fail.
- On the request: the request log shows the overflow count in
search_overflow_count(part ofsearch_count) and the fee insearch_overflow_fee_micro_cents. The fee is the request'scharged_amountinusage.cost_details; the rest of the request stays plan-covered.
Prompt injection
Search results are untrusted web content. deeprelay marks them as untrusted when it passes them to the model and caps their size, but a page can still contain instructions aimed at the model. A model with shell or file tools (Claude Code, Codex) can be influenced by them. Treat a session that has read search results like one that has read any other web page: review the commands it proposes, and use domain filters when you only need trusted sources.
Data handling
Web search sends the query the model writes to a third-party search provider. The query is written from your conversation, so it can contain your content. See the data policy's web search exception. The rest of the request is not sent to the search provider.
Endpoints
| Method | Path | Scope | Purpose |
|---|---|---|---|
GET | / (?modality=) | none (key optional) | List the model catalog (see Listing models without a key) |
GET | / | serverless:read | One model's record |
POST | / | serverless:write | Chat completion (supports stream:true) |
POST | / | serverless:write | Anthropic Messages API, for Claude Code (supports stream:true); see Anthropic Messages API |
POST | / | serverless:read | Estimated input-token count for a Messages request (local estimate, not billed) |
POST | / | serverless:write | OpenAI Responses API, for Codex CLI (supports stream:true); see OpenAI Responses API |
GET, DELETE | / | serverless:write | Always 404 stateless: deeprelay stores no responses |
POST | / | serverless:write | Always 404 stateless |
GET | / | serverless:write | Always 404 stateless |
POST | / | serverless:write | Always 400 compaction_unsupported: compact on the client |
POST | / | serverless:write | Text embeddings (OpenAI-compatible, synchronous) |
POST | / | serverless:write | Synchronous image generation (b64_json) |
POST | / | serverless:write | Create an async video job |
GET | / (?after= / ?limit=) | serverless:read | List your video jobs |
GET | / | serverless:read | One video job (poll for status) |
GET | / | serverless:read | Download the finished mp4 |
POST | / | serverless:write | Cancel an in-flight video job |
POST | / | serverless:write | Upload a batch input file (purpose=batch, multipart) |
GET | / (?purpose= / ?after= / ?limit=) | serverless:read | List your batch files |
GET | / | serverless:read | One batch file |
DELETE | / | serverless:write | Delete a batch file and its content now (409 file_in_use while its batch runs) |
GET | / | serverless:read | Download a batch file's JSONL |
POST | / | serverless:write | Create an off-peak batch |
GET | / (?after= / ?limit=) | serverless:read | List your batches, newest first |
GET | / | serverless:read | One batch (poll for status) |
POST | / | serverless:write | Cancel a batch |
GET | / | serverless:read | Your batch limits and current values |
POST | / | none | Always 400 message_batches_unsupported: use / with url: / |
GET | / (?modality= / ?model= / ?source= / ?batch_id=) | billing:read | Token/cost rollups |
GET | / | billing:read | Your credit balance (balance_cents, balance_dollars), auto-pay settings and billing_mode: prepaid, or invoice for an account billed by invoice, which also returns credit_limit_cents. burn_cents_per_hour does not include inference spend; use / for that |
GET | / | billing:read; PUT/DELETE need billing:write (org admin) | The org's monthly spending limit and optional daily cap, with today's spend (404 no_spending_limit when none is set) |
GET | / | billing:read | Subscription status, the plan you are on + its price and quota usage, and the offered plans (200 with subscribed:false when not subscribed) |
POST | / | billing:write (org admin) | Mint a Stripe Checkout URL to subscribe (plan_key flat or plus; a new plan needs "one_plan_confirmed": true, one plan per person per https://deeprelay.ai/terms#plans, else 400 one_plan_confirmation_required; 409 if already subscribed; 429 checkout_paused with Retry-After while new payments are paused after several declined cards). One paying identity holds one plan: a plan whose card, payer email or login already pays for a plan on another organization is cancelled and refunded when its checkout completes (the console also refuses such a checkout up front with 409 plan-identity-in-use); contact support if you genuinely run several organizations |
POST | / | billing:write (org admin) | Move the existing subscription to a bigger plan — full new price charged now, new period starts now (409 if not subscribed or not an upgrade, 402 if the card declines) |
POST | / | billing:write (org admin) | Start a plan, or upgrade, paid from deposited balance (plan_key; starting a plan needs "one_plan_confirmed": true, else 400 one_plan_confirmation_required; free credit never counts; 402 insufficient_balance when deposits don't cover the full price; 409 plan_identity_in_use when the card, email or login already pays for a plan on another organization, balance not charged) |
PUT | / | billing:write (org admin) | Renew the plan from deposited balance when it covers the price ({"enabled": true}); otherwise the card is charged |
POST | / | billing:write (org admin) | Mint a Stripe Billing Portal URL to cancel, resume or change card |
GET | / (?model=) | serverless:read | Would this model request be served, and at whose expense |
GET | / | serverless:read | The request log, newest first |
GET | / | serverless:read | One request, by X-Request-Id or body id |
GET | / | serverless:read | The request log as CSV |
GET, POST | / | keys:read; writes need keys:manage | List or create API keys (see Key controls) |
GET, PATCH, DELETE | / | keys:read; writes need keys:manage | Read, change or revoke one key |
GET, PUT | / | billing:read; PUT needs billing:write and an admin or full_access key | Alert settings |
GET, PUT | / | billing:read; PUT needs billing:write and an admin or full_access key | Web search paid overflow on or off ({"overflow_enabled": true}) |
Accounts billed by invoice. An account on invoice billing
(billing_mode is invoice) is metered the same way and billed monthly in
arrears. Its balance is minus the usage not yet invoiced and may run below
zero down to credit_limit_cents. Plans, top-ups, auto-pay, saved payment
methods, crypto deposits and referrals do not apply to it: those routes
return 403 invoice_billed_account. Reads and spending limits work as
usual.
Reading your usage and spend
Where your credit goes. Four reads, all with an API key, answer it from a script or dashboard of your own:
| Question | Endpoint | CLI |
|---|---|---|
| What is left? | GET / | deeprelay billing balance |
| What did each call cost? Model, input, output and cached tokens per request | GET / (CSV: GET /); see Request log | deeprelay requests list |
| Spend over time, per model | GET / (below) | deeprelay usage --modality chat |
| On a plan: how much allowance is used | GET / | deeprelay billing subscription |
To see one tool or coding agent on its own, give each tool its own API key
and filter the request log by key. Seeing other keys' rows needs an org
admin's key or a full_access key; any other key sees only its own requests.
GET /v1/usage returns your inference spend in time buckets (bucket=hour,
day, week or month; default day) over start/end (RFC 3339; default
the last 30 days). Pass modality and/or model — those filters are what
select serverless inference usage. Without either, the endpoint reads GPU
instance usage, which is always empty today.
# Chat spend per day for the last 30 days
curl "https://api.deeprelay.ai/v1/usage?modality=chat" \
-H "Authorization: Bearer $DEEPRELAY_API_KEY"
# One model, hourly, over an explicit window
curl "https://api.deeprelay.ai/v1/usage?model=<model-id>&bucket=hour&start=2026-09-01T00:00:00Z&end=2026-09-02T00:00:00Z" \
-H "Authorization: Bearer $DEEPRELAY_API_KEY"
modality is one of chat, image, video or embedding; model is an
exact model id from GET /v1/models. Each row covers one (bucket, modality,
model) and carries bucket_start, modality, model, prompt_tokens,
completion_tokens, image_count and cost_cents (plus gpu_seconds, always
0 on inference rows). Rows come newest bucket first, paginated with
limit/cursor like every other list. source=batch (or source=api)
and batch_id=batch_… narrow the rows to Batch API lines or
one batch, and also select the inference rows. A bad value for either is a
422 validation_failed here, while the request log
answers the same mistake with a 400. The CLI equivalent is
deeprelay usage --modality chat (or --model ), and the SDKs expose both
filters on listUsage / list_usage.
Request log
Every inference call writes one row to your request log: chat completions, messages, responses, embeddings, image generation and video creation. A call that deeprelay refused before it reached a model also gets a row, so a budget or allowlist denial shows up next to the calls that went through.
Finding a request. Every response carries an X-Request-Id header. The
id in the response body resolves to the same row: a chat completion's
chatcmpl-…, a message's msg_…, a response's resp_…, or a video's
deeprelay_med_… id. Pass any of them to GET /v1/requests/{id}.
Your own correlation id. Send X-Client-Request-Id on any inference call
and it is stored on the row, where you can filter on it. On /v1/responses
you can send it in the body as metadata.client_request_id instead. Without
either, an inbound X-Request-Id is kept as the client id. The response's own
X-Request-Id is always minted by deeprelay. The value is stored as opaque
text: surrounding whitespace and control characters are removed, and a value
longer than 128 characters is dropped rather than truncated.
curl https://api.deeprelay.ai/v1/chat/completions \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-H "X-Client-Request-Id: job-4812-step-3" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/deepseek-v4.1-flash","messages":[{"role":"user","content":"hi"}]}'
curl "https://api.deeprelay.ai/v1/requests?client_request_id=job-4812-step-3" \
-H "Authorization: Bearer $DEEPRELAY_API_KEY"
Listing. GET /v1/requests returns rows newest first.
- Filters:
key(an API key id),model,surface(chat,messages,responses,embeddings,image,video),status(ok,error,cancelled,rejected),error_code,client_request_id, afrom/totime range in RFC 3339,fallback=truefor only the requests where backup models were tried,source(apifor synchronous calls,batchfor Batch API lines) andbatch_idfor the lines of one batch. - Paging:
limitdefaults to 50 and is capped at 100. Passnext_cursorback ascursorfor the next page; it isnullon the last one. - Window: the log reaches back 90 days, and the page says so in
window_days: 90. Afromolder than that is moved up to the start of the window rather than refused. - Errors: a malformed filter (a
keythat is not a key id, an unknownstatus, a bad timestamp,tobeforefrom, asourceother thanapiorbatch, abatch_idthat is not a batch id) answers400validation_failed(/v1/usageanswers a badsourceorbatch_idwith422instead). Reads are rate-limited per key; over the limit you get429rate_limitedwithRetry-After.
Who sees what. An org admin's key and a full_access key see every row
in the organization. Any other key sees only the rows it made itself. A key
filter can only narrow that set. An id you
cannot see answers the same 404 as an id that does not exist, as does a row
older than 90 days.
What a row contains. The request id and your client id, the time, the
surface and model, the key's id, name and prefix (never the secret), the
status and HTTP status, the error code you received, the finish reason, token
counts (prompt, completion, cached, reasoning), subscription quota units, the
cost, whether the plan covered the call, time to first token for a stream,
the duration, ignored parameters, and the image count or video seconds for
media. When backup models were tried, the row also carries
requested_model, served_model, fallback_reason and an attempts trail;
model is then the model that served. Every row has source (api or
batch); a Batch API line also carries batch_id, your custom_id, the
rate_tier it was billed at (off_peak, batch or normal) and final,
which is false on an attempt that was retried, so the line's outcome is the
row with final: true. The cost is an exact decimal, a JSON
number, plus the exact integer in cost_micro_cents. Fields that do not
apply are omitted: an embeddings row has no completion tokens and a rejected
row has no tokens.
What cost means depends on plan_covered.
- Pay-as-you-go row (
plan_covered: false): the amount charged to your wallet, the same figure asusage.coston the response. - Plan-covered row (
plan_covered: true): the call priced at pay-as-you-go list rates, not an amount charged. Your subscription covered it andusage.coston the response was0(unless a paid overflow search fee applied, whichusage.costthen shows). It includes every web search the allowance covered, at the per-search list price (currently $0.002 each), so a covered request that searched shows a higher cost than its tokens alone even though nothing was charged. The one charged part of a covered request is a paid overflow search fee, shown separately insearch_overflow_fee_micro_centsand not included incost.
What a row never contains: your prompts or completions, the upstream that served the call, or any upstream timing. The backup-model trail names models only, never providers.
Statuses.
status | Meaning |
|---|---|
ok | The call completed. |
error | The call failed. error_code is the X-Deeprelay-Error-Code you received. |
cancelled | You closed the connection before the call finished. http_status is 499 and there is no error code. |
rejected | deeprelay refused the call before any model ran, for example api_key_budget_exceeded, member_spend_limit_reached, model_not_allowed_for_key, insufficient_balance or subscription_quota_exhausted. The cost is "0". Identical rejections from one key within 10 seconds share one row, and suppressed_count says how many were folded into it. |
CSV export. GET /v1/requests/export takes the same filters and the same
visibility rules and streams a CSV file. It counts the matching rows first: if
there are more than the export cap (100,000 rows by default), it answers 422
export_too_large with max_rows in the problem body and writes nothing.
Narrow the time range or add a filter, then export again. The columns end
with requested_model, served_model, fallback_reason, the web-search
columns (search_count, search_overflow_count, search_result_tokens,
search_overflow_fee) and the batch columns (source, batch_id,
custom_id, rate_tier, final). New columns are only ever appended. Cells that
start with a spreadsheet formula character are escaped. Exports have their own,
tighter rate limit.
From the CLI:
# Everything refused at admission this month
deeprelay requests list --status rejected --from 2026-10-01
# One request, by any id you hold
deeprelay requests get chatcmpl-...
# A week as CSV
deeprelay requests export --from 2026-10-01 --to 2026-10-08 --out requests.csv
See deeprelay requests.
In the dashboard, Cloud → Requests (/cloud/requests) shows the same rows
under the same visibility rules, with the same filters, a detail drawer per
row and a CSV export button. Billing transactions link to it with the filters
already applied.
Key controls
An API key can carry its own limits, so a key you hand to a CI job or an
agent can only spend, call and last as much as you decide. Manage keys with
/v1/api-keys, the deeprelay api-keys command, or Cloud → API Keys.
| Method | Path | Purpose |
|---|---|---|
POST | / | Create a key. The secret (key) is in this response only. |
GET | / | List keys with their limits and budget use |
GET | / | One key |
PATCH | / | Change the name or limits |
DELETE | / | Revoke the key now (204) |
The create response is sent with Cache-Control: no-store and is never
replayed from the idempotency cache, so the secret is returned exactly once.
Store it then; afterwards only the prefix and last four characters are shown.
# A key for a CI job: $5 a month, one model, expires at year end
deeprelay api-keys create --name ci-bot --scopes standard --budget 5 \
--allow-model deeprelay/deepseek-v4.1-flash --expires 2026-12-31
deeprelay api-keys list
deeprelay api-keys update <key-id> --budget 10
deeprelay api-keys revoke <key-id>
curl https://api.deeprelay.ai/v1/api-keys \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name":"ci-bot","scopes":{"standard":true},"budget_cents":500,
"allowed_models":["deeprelay/deepseek-v4.1-flash"],"expires_at":"2026-12-31T00:00:00Z"}'
Monthly budget
budget_cents caps what the key may charge to your wallet in one billing
month. It is billed cost: the same amount usage.cost reports.
- Plan-covered calls don't count. A call your subscription paid for adds nothing to the budget. A call that fell back to pay-as-you-go because the quota was spent does count.
- The month is your subscription's billing period if you have one, and the UTC calendar month if you don't.
budget_resets_aton the key says when it starts over, andbudget_used_micro_centsis the spend so far. - Admission uses the estimate. A call is refused when the spend so far, plus the estimated cost of the key's calls still in flight, plus that call's own estimated cost would go over the budget; landing exactly on it is allowed. Concurrent calls are judged together, so a burst cannot pass the budget by arriving at once. Because the real cost is only known when a call ends, a key can finish slightly over its budget by the difference between its calls' real and estimated costs.
- Keys minted by a key share its budget. When a key with
keys:managemints another key, the new key's spend also counts against the minting key's budget, and against the budget of every key above that one. A key'sbudget_used_micro_centsis the spend of the key and every key it minted, directly or further down. However many keys a budgeted key mints, together they cannot spend more than its budget. When the budget that runs out belongs to a key above the caller, the message says the key shares that budget, for exampleKey "worker-7" shares the $5.00 monthly budget of the key that minted it, and that budget is reached.Keys created in the dashboard are not minted by a key and are unaffected. - Refusal:
402api_key_budget_exceededwithx-should-retry: false. The message names only your key and the reset date, for exampleKey "ci-bot" reached its $5.00 monthly budget. It resets on Nov 1, 2026 (UTC).The refusal appears in the request log as arejectedrow. null(or nobudget_centsat create) means no budget.
Model allowlist
allowed_models limits the key to a list of model ids.
- Exact ids. Entries are normalised (lowercased, with any
:economytier suffix removed) and must exist in the catalog when you save them. Both tiers of an allowed model are allowed, and so is an alias that resolves to one.nullmeans every model; an empty list is refused. - Refusal: on every inference endpoint, a model off the list gets
403model_not_allowed_for_key: "The model does not exist or this API key may not use it". A model that does not exist gets the same answer, so a restricted key cannot use the error to probe the catalog. Keys without an allowlist keep the usual404model_not_found. - Listing. For a restricted key,
GET /v1/modelsreturns only the allowed models, andGET /v1/models/{id}answers the same403for any other id. This is the one place an authenticated listing differs from the keyless one./v1/inference/preflightanswersverdict: blockwith the same reason. - Stale entries. If an allowed model leaves the catalog, the entry is kept and listed in
stale_models; it matches nothing until the model returns.
Rate limit and expiry
rate_limit_rpsandrate_limit_burstset the key's own rate limit. Left out, they default to the platform limit (100 requests per second plus a burst of 200), or to the minting key's own limit when that is lower. The effective limit can be lower than what you set while your account is new: an account younger than 7 days or one that has never paid is held to a lower limit for every key.expires_atmakes the key stop authenticating at that time.nullmeans never.
Who can manage keys
Creating, updating and revoking keys needs the keys:manage capability. A key
without it gets 403 keys_manage_required on every write; reading keys
needs only keys:read.
- On for
full_accesskeys, for a granular key granted{"keys": "write"}, and for the keydeeprelay loginkeeps for the CLI's own use. - Off for
standardandread_onlykeys. - Never give it to a key a tool or coding agent uses.
deeprelay setupanddeeprelay auth tokenonly ever hand out the CLI's separate inference key, which is astandardkey.
A key can never mint a key stronger than itself:
- Scopes it does not hold answer
403scope_exceeds_caller. - Only an org admin can mint a
full_accesskey; a member gets403forbidden. - If the minting key has a budget, an allowlist, a rate limit or an expiry, the new key must have one too, no larger or later. Breaking that answers
422validation_failedwith afieldnaming the limit.PATCHfollows the same rule, so it cannot widen a key beyond its caller's limits. The new key's spend also counts against the minting key's budget (see Monthly budget). - A key minted through the API can have at most 4 keys above it. A key that deep cannot mint further keys: the mint answers
403forbidden. Mint from a key higher up, or from the dashboard.
PATCH changes only the fields you send; an explicit null clears
budget_cents, allowed_models, fallback_models (see
Backup models) or expires_at. Scopes cannot be changed
after a key is created, and an unknown field is refused with 422. A member
can change and revoke only the keys they created. Every key change is
recorded in the org audit log with the actor and source IP, and removing a
member from the organization revokes every key they hold.
Member spending limits
An org admin can give a member a monthly spending limit in the dashboard. It
is one number covering all billed spend on the account by that member's keys
in the billing month, summed across every key they created. When a call would
take the member over it, the call is refused with 402
member_spend_limit_reached and x-should-retry: false, even if each key is
under its own budget. A limit set to notify only never refuses a call.
The checks run in this order, and the first one that fails answers: the key's budget (and the budget of every key above it), then the member's limit, then the organization's balance and its daily and monthly spending caps. The organization-wide daily and monthly caps count serverless inference spend billed to your balance (calls covered by your plan are excluded). Key budgets and member limits narrow that further, per key and per member.
Every one of these checks counts the calls still in flight as well as the
spend already recorded, so many calls sent at once are judged together rather
than each against the same headroom. The balance check also counts usage that
is recorded but not yet deducted from your balance (deductions are batched
about once a minute), so the balance a call is admitted against is what is
left after everything already spent. A call is estimated from everything
that is sent to the model as input: the messages, the tools definitions,
earlier tool_calls and their arguments, tool_choice, a response_format
JSON schema and stop sequences, plus max_tokens (or the model's maximum
output when it is not set).
When a call is refused only because your other calls still in progress are
using the rest of the balance, budget or limit (the spend already recorded plus
this call alone would fit), the 402 keeps the same code but says so, and it
is retryable: x-should-retry: true with a short Retry-After. Retry once
those calls finish. A call that would not fit even on its own keeps the plain
non-retryable 402.
Backup models
A request names one model. deeprelay already moves it between that model's providers when one fails. Backup models add a second step: if every provider for the requested model fails before the first token, the request is retried on the next model in a list you choose. The response still arrives on the same connection, and it tells you which model served it.
Backup models are off until you set them. Nothing changes for a key or a request without a list.
Setting the list
There are three ways to set it. A list given with the request replaces the key's list for that request; the two are never merged.
- On the API key.
fallback_modelsholds up to 3 model ids in priority order and applies to every model the key calls. Set it when you create or update the key, withdeeprelay api-keys update, in Cloud → API Keys, or by answering yes in--fallback-model … deeprelay setup claude-code/setup codex.nullturns it off. An empty list, more than 3 models, or a model that is not a chat model in the catalog is refused with422validation_failednamingfallback_models. On a key with a model allowlist every entry must be on the allowlist. - On one request, as a header.
X-Deeprelay-Fallback-Modelstakes a comma-separated list of up to 3 model ids and works on/v1/chat/completions,/v1/messagesand/v1/responses. The valuenone(or an empty value) turns fallback off for that request even when the key has a list. - On one chat request, OpenRouter style.
/v1/chat/completionsaccepts the OpenRoutermodelsarray.modelis the requested model andmodelslists the backups in order; ifmodelis empty, the first entry ofmodelsis the requested model."models": []turns fallback off for that request. Code written for OpenRouter's model fallback works unchanged.modelsis read only on chat completions; use the header on the other two endpoints.
# Key list: these backups apply to every request the key makes
deeprelay api-keys update <key-id> \
--fallback-model deeprelay/glm-5.3 --fallback-model deeprelay/deepseek-v4.1-flash
deeprelay api-keys update <key-id> --no-fallback # turn it off
# One request, OpenRouter style
curl https://api.deeprelay.ai/v1/chat/completions \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/kimi-k3",
"models":["deeprelay/glm-5.3","deeprelay/deepseek-v4.1-flash"],
"messages":[{"role":"user","content":"hi"}]}'
# One request, any of the three endpoints
curl https://api.deeprelay.ai/v1/messages \
-H "x-api-key: $DEEPRELAY_API_KEY" \
-H "X-Deeprelay-Fallback-Models: deeprelay/glm-5.3,deeprelay/deepseek-v4.1-flash" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/kimi-k3","max_tokens":256,
"messages":[{"role":"user","content":"hi"}]}'
A request-level list is checked when the request arrives. More than 3 models,
a malformed id, none mixed with model ids, or models and the header on the
same request is a 400 invalid_request whose param names the field.
Order. The requested model goes first, then the backups in list order. An entry naming the requested model, or a model already tried on this request, is skipped. So a request for the first model on the list falls through to the second, and a request for a model not on the list walks the whole list.
Each backup passes the same checks a direct call would. Before a backup is
tried, deeprelay checks it against the key's model allowlist, the request's
billing mode (below), the key budget, member limit and spending caps at that
backup's price, and what the request needs (tools, images, structured output,
reasoning parameters). A backup that fails any check is skipped, not used, and
the skip is recorded in the request log. A request-level list
therefore can never reach a model the key could not call directly. A skipped
backup is not a refused request: it writes no rejected row and does not set
off an alert.
When a backup is tried
A backup is tried only when the requested model failed before the first token and every one of its providers was tried:
- every provider was unavailable, timed out, was rate limited upstream, or stalled with no first token;
- every route to the model is paused because its providers are failing;
- the upstream no longer serves the model, or deeprelay's own account with the provider failed (
upstream_error); - the input did not fit the model's context window (
context_length_exceeded). In this case only a backup whose context window is larger than the requested model's, and large enough for the request, is tried; the others are skipped.
A backup is never tried for:
- a mistake in your request (any other
400,404on a model id that does not exist, an unsupported parameter); - your own limits: quota, balance, spending caps, key budget, member limit, allowlist, rate limit;
- a content or safety result;
- anything that happens after the first token. Once tokens have reached you, the model never changes. A failure mid-stream ends the stream as it would without backups.
One time budget for the whole chain. All models in the chain share the
time a single request has to start answering (3 minutes by default), counted
from when the request arrives; a stalled model does not reset it. While a
backup is left, a model that has produced no first token is given up on after
the usual first-token wait (90 seconds). A backup is started only if at least
about 20 seconds of the budget remain. If less is left, the chain stops and you
get the requested model's error; the request log records the remaining
backups as deadline_exhausted.
Billing never changes mode
A backup is billed at its own price and usage factor, and the request log, the
usage block and your bill all name the model that served. What does not
change is how the request is paid for:
- Plan-covered request. If the requested model is on your subscription's plan roster and the plan covered the request, only other plan-roster models can back it up, each at its own usage factor. A backup off the roster is skipped as
wallet_onlyand is never charged to your balance. If the plan quota runs out before a plan-covered backup is tried, that backup is skipped assubscription_quota_exhausted: it is not moved to pay-as-you-go billing the way a direct call would be. If no other backup serves, you get the requested model's original error and status (for example503upstream_unavailable), not a429. The skip shows in the request log's attempts trail. - Request billed to your balance (pay-as-you-go, or a subscriber's request to a model the plan does not cover, or a subscriber whose quota was spent and whose request was billed to the balance on arrival): any chat model the key may call can back it up, and every backup is billed to your balance, even a plan-roster model.
- Pricier backups are allowed. The key's budget, the member's limit and your spending caps are checked at each backup's own price, so a backup that would take the key over its budget is skipped as
api_key_budget_exceeded. In Cloud → API Keys anddeeprelay api-keys get, each backup shows its current price, with a marker when it costs more than the model the key uses most.
The subscription quota headers describe the model that served.
What the response tells you
The body's model is the model that served the request, on all three
endpoints. These headers say what happened:
| Header | When | Value |
|---|---|---|
X-Deeprelay-Served-Model | every response that a model served | the model that served it |
X-Deeprelay-Requested-Model | every response once the model id is resolved, errors included | the model the request asked for |
X-Deeprelay-Fallback-Reason | only when a backup served | why the requested model was passed over, as an error code: upstream_timeout, upstream_unavailable, upstream_rate_limited, context_length_exceeded, … |
X-Deeprelay-Fallback-Attempted | only when backups were tried and none served | how many models were dialled, the requested one included |
The two model headers are equal when no backup was needed. The model is only ever switched before the first byte, so all four are accurate on streamed responses too.
curl -si https://api.deeprelay.ai/v1/chat/completions \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-H "X-Deeprelay-Fallback-Models: deeprelay/glm-5.3" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/kimi-k3","messages":[{"role":"user","content":"hi"}]}'
HTTP/2 200
x-deeprelay-requested-model: deeprelay/kimi-k3
x-deeprelay-served-model: deeprelay/glm-5.3
x-deeprelay-fallback-reason: upstream_timeout
…
{"id":"chatcmpl-…","model":"deeprelay/glm-5.3", … }
When nothing serves. If the requested model and every backup fail, you get
the requested model's error: its status, its error code and its retry
headers, exactly as without backups. The message adds that fallback was
attempted, how many models were tried, and your request id, and the response
carries X-Deeprelay-Fallback-Attempted. Retry logic written for a single
model keeps working.
In the request log. The request has one row, for the model that served
(or the requested model, when none did), and it is billed once. The row carries
requested_model, served_model and fallback_reason, and an attempts
trail listing each model in order with its outcome (ok, failed or
skipped), the reason, how long it took and how many upstream tries it made.
Providers are never named. GET /v1/requests?fallback=true (CLI:
deeprelay requests list --fallback; dashboard: Fallback only) returns only
these rows, and the CSV export gains requested_model, served_model and
fallback_reason columns. See Request log.
Published model statistics count each model's own attempts: a requested model that failed counts as a failure for that model even when a backup then served your request.
Liquid
Backup models are not applied to Liquid (inference deeprelay serves on the
Liquid Inference exchange). A Liquid job is always served by exactly the model
it was awarded to, so a Liquid request that carries models or
X-Deeprelay-Fallback-Models is refused with 400. The dashboard and CLI note
this next to every key list.
When a backup leaves the plan or the catalog
Lists are never rewritten for you. If a backup model leaves the subscription
plan roster, the entry stays on the key, shows as wallet only, and
plan-covered requests skip it. Each affected organization gets one email
listing its affected keys, and a
plan_roster.model_removed webhook
event. If a backup leaves the catalog entirely, the entry shows as
unavailable and is skipped; no notice is sent.
Backup models in coding agents
deeprelay setup claude-code, setup codex and the other setup targets ask
whether to turn on backup models for the CLI's inference key, after the agent
is configured. The default answer is no. In a script, pass
--fallback-models a,b,c or --no-fallback. Setup edits the key itself and
writes no header into the agent's config, so a later change in Cloud → API Keys
applies to the agent straight away, without re-running setup. Every tool that
uses the same key shares the list, which is why setup --remove asks before
clearing it. See Claude Code and
Codex.
Prompt caching (cached input tokens)
When an upstream partner serves part of your prompt from its prompt cache, we pass the split straight through and bill the cached part at a lower rate.
In the response. A chat completion's usage block carries
prompt_tokens_details.cached_tokens whenever the upstream reported a non-zero
cache hit — the same field name and shape the OpenAI SDKs already read, on both
streaming and non-streaming calls:
"usage": {
"prompt_tokens": 4096,
"completion_tokens": 128,
"total_tokens": 4224,
"prompt_tokens_details": { "cached_tokens": 3840 }
}
cached_tokens is a subset of prompt_tokens, never an addition:
prompt_tokens remains the full prompt. When there were no cache hits the
prompt_tokens_details object is omitted entirely.
In the catalog. A model with a cached-input rate exposes it in pricing as
cached_input_per_1m_tokens_microcents (micro-cents per 1M tokens, the exact
figure — cached rates are routinely sub-cent) alongside a rounded
cached_input_per_1m_tokens_cents. Treat the micro-cents field as the
presence signal: it is absent only when the model has no cached rate (no
discount — every prompt token bills at input_per_1m_tokens_cents), while the
rounded cents field is also omitted whenever the exact rate rounds below half
a cent, which for cached rates is the routine case.
How a chat call is billed.
cost = (prompt_tokens - cached_tokens) × input_rate
+ cached_tokens × cached_input_rate
+ completion_tokens × output_rate
All rates are per 1M tokens. Usage is metered in micro-cents and settled
against your credit balance once a minute: each settlement charges whole cents
rounded down and carries the sub-cent remainder into the next settlement,
so you are never billed above metered usage and there is no per-request
minimum.
cached_tokens is clamped to prompt_tokens, so an over-reporting upstream can
never produce a negative cache-miss count. Prompt caching is a partner-side
optimisation — we don't control which prefixes get cached, and a call that hits
no cache simply bills exactly as it did before.
Where the cached rate comes from. A model's cached-input rate is taken from
the serving partner's published cache-hit price (the same listing its input and
output rates come from), served as-is, or from the pricing
policy set for the model when one is enrolled. It is visible everywhere the
model's price is: GET /v1/models, deeprelay models list / deeprelay models get, the
public model pricing pages and the console's model
catalog. A model that shows no cached rate has none — its partner publishes no
cache-hit price — and bills every prompt token at the input rate.
Peak and off-peak pricing
A few models are priced by time of day: their upstream charges more inside
peak hours. Today that is DeepSeek V4.1 Flash, whose peak hours are
Monday to Friday, 01:00-04:00 and 06:00-10:00 UTC (09:00-12:00 and
14:00-18:00 Beijing time). Every other hour, and all of Saturday and Sunday,
is off-peak, where its rate is half of peak. For those models pricing
carries the whole picture:
"pricing": {
"currency": "usd",
"input_per_1m_tokens_cents": 14,
"output_per_1m_tokens_cents": 54,
"cached_input_per_1m_tokens_microcents": 270000,
"period": "peak",
"peak_windows_utc": [
{"start": "01:00", "end": "04:00", "days": [1, 2, 3, 4, 5]},
{"start": "06:00", "end": "10:00", "days": [1, 2, 3, 4, 5]}
],
"peak": {"input_per_1m_tokens_microcents": 13500000, "cached_input_per_1m_tokens_microcents": 270000, "output_per_1m_tokens_microcents": 54000000, "...": "..."},
"off_peak": {"input_per_1m_tokens_microcents": 6750000, "cached_input_per_1m_tokens_microcents": 140000, "output_per_1m_tokens_microcents": 27000000, "...": "..."}
}
- The flat fields (
input_per_1m_tokens_cents,output_per_1m_tokens_cents,cached_input_per_1m_tokens_microcents) are the rates in effect at the moment you read the catalog, andperiodsays which side of the schedule that is (peakoroff_peak). A client that reads only the flat fields always sees the price a request sent right now is billed at. peak_windows_utcis the schedule in UTC — start inclusive, end exclusive,"24:00"allowed as an end, and a range whose end sorts before its start wraps midnight.peakandoff_peakcarry both full rate triples so you can price a call you will make later.days(optional) limits a range to those ISO weekdays of the UTC date it starts on:1is Monday and7is Sunday. A range withoutdaysapplies every day. A range that wraps midnight belongs to the day it started on, so a Friday-only22:00-02:00range also covers the first two hours of Saturday. Weekdays are UTC weekdays:[1, 2, 3, 4, 5]means Monday to Friday in UTC.- A request is billed at the rate in effect when it arrives (its UTC arrival minute is checked against the windows). A long streamed response that straddles a boundary is priced entirely at the arrival rate.
- Models without time-of-day pricing omit all four fields; their flat rates apply around the clock.
The rates above are illustrative; the catalog is the source of truth.
Every place deeprelay shows a price shows both sides for such a model, not
just the side in effect when you happened to look: the pricing
page gives it an off-peak row and a peak row
with the peak hours, the model pages and the
console list both rates on every line ($0.27 off-peak, $0.54 peak / 1M) with
a "Peak hours" line, the console's model cards and playground say which side is
in effect now and what the other costs, deeprelay models list prints both in
its PRICE column, and deeprelay models get shows the period, the windows
and both triples. The Batch API runs a batch for such a model only in its
off-peak hours.
Balance checks and usage rollups. The pre-flight balance check assumes
zero cache hits, so it stays conservative: a cached call can only cost less
than the amount reserved. GET /v1/usage and the Stripe input-token meter keep
counting the full prompt_tokens — the cache discount shows up in the cost,
not in the token counts.
Batch API
Submit now; deeprelay runs the batch in the model's next off-peak window and bills each request at the rate in effect when it runs. Use it for work that does not need an answer right away: evaluations, labelling, backfills, embeddings-style sweeps over chat models. The batch runs only off-peak, so every line is billed at the off-peak rate, half of peak.
Batch is offered on models with a peak schedule, which today is DeepSeek V4.1
Flash, and on any model deeprelay has enabled for batch at its normal rate.
pricing.batch.eligible in GET /v1/models says which models take a batch;
a batch for any other model is refused at submit with 400
batch_validation_failed.
The API is OpenAI's Batch API: the same file format, the same endpoints and
the same batch object, so the OpenAI SDKs work unchanged with
base_url="https://api.deeprelay.ai/v1". deeprelay adds a deeprelay
sub-object to the batch object with the schedule, the rate and the cost.
Quick start
1. Write a JSONL file, one request per line. Every line has a custom_id
you choose, method: "POST", the url of the endpoint, and the body you
would send to that endpoint synchronously:
{"custom_id": "q-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "deeprelay/deepseek-v4.1-flash", "messages": [{"role": "user", "content": "Summarise the plot of Hamlet in one sentence."}], "max_tokens": 200}}
{"custom_id": "q-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "deeprelay/deepseek-v4.1-flash", "messages": [{"role": "user", "content": "Name three prime numbers above 100."}], "max_tokens": 200}}
2. Upload it, create the batch, wait, download the results with the OpenAI Python SDK:
import time
from openai import OpenAI
client = OpenAI(base_url="https://api.deeprelay.ai/v1", api_key="$DEEPRELAY_API_KEY")
batch_file = client.files.create(file=open("requests.jsonl", "rb"), purpose="batch")
batch = client.batches.create(
input_file_id=batch_file.id,
endpoint="/v1/chat/completions",
completion_window="24h",
)
print(batch.id, batch.status)
while batch.status not in ("completed", "expired", "cancelled", "failed"):
time.sleep(60)
batch = client.batches.retrieve(batch.id)
if batch.output_file_id:
client.files.content(batch.output_file_id).write_to_file("output.jsonl")
if batch.error_file_id:
client.files.content(batch.error_file_id).write_to_file("errors.jsonl")
Or with curl:
# Upload (purpose must be "batch")
curl https://api.deeprelay.ai/v1/files \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-F purpose=batch -F file=@requests.jsonl
# Create the batch
curl https://api.deeprelay.ai/v1/batches \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"input_file_id": "file-…", "endpoint": "/v1/chat/completions", "completion_window": "24h"}'
# Poll it
curl https://api.deeprelay.ai/v1/batches/batch_… \
-H "Authorization: Bearer $DEEPRELAY_API_KEY"
# Download the results once output_file_id is set
curl https://api.deeprelay.ai/v1/files/file-…/content \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" -o output.jsonl
Lines for each endpoint
A batch runs lines against one of three endpoints. The body is exactly what
that endpoint takes synchronously.
Chat completions ("url": "/v1/chat/completions"), as above.
Anthropic Messages ("url": "/v1/messages"): the body is an Anthropic
Messages request, wrapped in the same OpenAI batch line:
{"custom_id": "m-1", "method": "POST", "url": "/v1/messages", "body": {"model": "deeprelay/deepseek-v4.1-flash", "max_tokens": 300, "messages": [{"role": "user", "content": "Write a haiku about tides."}]}}
Responses ("url": "/v1/responses"):
{"custom_id": "r-1", "method": "POST", "url": "/v1/responses", "body": {"model": "deeprelay/deepseek-v4.1-flash", "input": "List two uses of a lever.", "max_output_tokens": 300}}
Create the batch with the matching endpoint (/v1/messages or
/v1/responses).
Anthropic Message Batches (/v1/messages/batches) is not supported —
use the OpenAI-format batch with url: /v1/messages. A request to
/v1/messages/batches answers 400 message_batches_unsupported in the
Anthropic envelope.
Rules
- Who sees a batch. An admin key or a
full_accesskey sees every batch and batch file in the organization. Any other key sees, downloads, cancels and deletes only the batches and files it created, the same rule as the request log; another key's batch or file answers404. - One model and one endpoint per batch. Every line's
urlmust equal the batch'sendpoint, and every line must use the samemodel. This is a difference from OpenAI, which allows mixed models; split a mixed file into one batch per model. - No streaming. A line with
"stream": trueis rejected. - No server tools. Web search and other server-side tools are rejected in a batch. Your own function tools are fine.
custom_idis 1 to 64 characters ofA-Z a-z 0-9 _ . : -and must be unique within the file. It is how you match results to requests: output lines are not in input order.- No backup models. A batch line runs on its own model only; backup models on the key are not tried.
- The whole file is checked before anything runs. Each line goes through the same validation a synchronous request gets. If any line is invalid, the upload or the submit is rejected whole with
400batch_validation_failed, and the message names the line numbers and what is wrong (the first 100, then a count). Fix the lines and upload again; nothing was stored or billed. completion_windowmust be"24h". It is a target, not a promise: see Scheduling.
Limits
| Limit | Default |
|---|---|
| Lines per input file | 50,000 |
| Input file size | 200 MiB |
| One line | 8 MiB |
| Batches not yet finished, per organization | 10 |
| Stored input files, per organization | 500 |
| Estimated tokens queued across your unfinished batches | 20,000,000 |
| Time from submit until a batch expires | 72 hours |
| How long batch files are kept after the batch finishes | 30 days |
GET /v1/batches/limits returns every limit with your current value, and
deeprelay batches limits prints the same table. A file or submit over a
limit answers 400 batch_limit_exceeded, and the message names the limit,
its value and where you are.
Scheduling
- When it starts. A batch for a model that is off-peak right now starts at once. Otherwise it waits for the model's next off-peak window. DeepSeek V4.1 Flash is off-peak all weekend and outside its weekday peak hours (see Peak and off-peak pricing), so a batch submitted on a Saturday starts immediately. A model that is at peak every hour can never run off-peak, so a batch for it is refused at submit with
400batch_validation_failed. - Pause and resume. Lines still queued when a window closes wait for the next one. The batch stays
in_progress;deeprelay.pause_reasonispeak_windowanddeeprelay.next_window_atsays when it resumes. Lines that already finished are already billed. A batch never runs at peak. - Order. When a window opens, paused batches resume first, then the oldest submits, then new batches. Batch traffic is rate-limited to run below interactive traffic.
- Timing fields.
deeprelay.scheduled_foris when the batch starts (or started),deeprelay.current_windowis the off-peak run it is in now, anddeeprelay.estimated_completion_atis an estimate from the batch's place in the queue, the window schedule and the observed drain rate. It isnulluntil there is a drain rate to estimate from, and it is never a promise. - Expiry. A batch expires 72 hours after submit (
deeprelay.expires_at). Lines that have not run by then are written to the error file with codebatch_expiredand are not billed. The batch endsexpired, and its output file still holds every line that finished. completion_window: "24h"is a target, not a promise. Most batches finish inside it; one submitted just as a window closes, or into a long queue, may take longer, up to the 72-hour expiry.
Check where a batch stands with GET /v1/batches/{id}. This one was
submitted on a Monday at 00:30 UTC, ran until the 01:00 peak hour began, and
resumes at 04:00:
{
"id": "batch_8f2c41d07a9be3615c0d2e7f",
"object": "batch",
"endpoint": "/v1/chat/completions",
"model": "deeprelay/deepseek-v4.1-flash",
"status": "in_progress",
"request_counts": {"total": 2000, "completed": 1450, "failed": 3},
"deeprelay": {
"scheduled_for": 1794184200,
"current_window": null,
"next_window_at": 1794196800,
"estimated_completion_at": 1794199200,
"expires_at": 1794443400,
"pause_reason": "peak_window",
"rate_tier": "off_peak",
"batch_price": {"input_per_1m_microcents": 15090000, "cached_input_per_1m_microcents": 57000, "output_per_1m_microcents": 44310000},
"estimated_cost": {"microcents": 61200000},
"cost": {"microcents": 40180000},
"request_counts": {"cancelled": 0, "expired": 0, "remaining": 547},
"...": "..."
},
"...": "..."
}
Pricing
Every line is billed at the rate in effect when it runs, never when you submitted it.
| Model | Batch rate today |
|---|---|
| DeepSeek V4.1 Flash | Off-peak rate, half of peak |
| A model enabled for batch without a peak schedule | The model's normal rate |
Models with a peak schedule only run off-peak in a batch, so their lines bill
at the off-peak rate. A model can also carry its own batch price, never above
its synchronous rate. GET /v1/models
shows what a batch line for each model bills at under pricing.batch
(rate_tier is off_peak, batch or normal, with the per-1M rates in
micro-cents and a schedule_url), and the batch object states its
rate_tier and batch_price before any line runs.
Billing
- Pay-as-you-go only. Batch lines are never covered by a subscription plan and never count toward plan quota, even when the key belongs to a subscriber. They are debited from your prepaid balance, and every output line says
"plan_covered": false. - The same limits as synchronous calls. The key's monthly budget, the member spending limit, the organization spending limit and the daily limit all apply. Batch lines do not use the key's request-rate or concurrency limits.
- The estimate is not a hold. At submit, deeprelay estimates the batch's cost as its input tokens plus each line's
max_tokensat the batch rate, and checks it against your balance and limits. If the estimate does not fit, the submit answers402with the matching code (insufficient_balance,api_key_budget_exceeded,member_spend_limit_reached,spending_limit_reachedordaily_limit_reached) and a message stating the estimated cost. Nothing is reserved: the estimate is shown asdeeprelay.estimated_cost, and each line is checked again when it runs. Setmax_tokenson your lines to lower the estimate; a line without it is estimated at the model's maximum output. - Running out mid-batch. Lines are charged as they finish. If your balance or a limit runs out while the batch is running, the batch pauses with that code as its
pause_reasonand resumes by itself after a top-up, a raised limit or the next period. If it is still paused at its expiry, the rest of its lines expire unbilled.
Results
When a batch finishes, output_file_id and error_file_id are set. Download
them with GET /v1/files/{id}/content. Each is JSONL, one line per request,
in no particular order:
{"id": "batch_req_3c9e0f6a1b2d4e5f60718293", "custom_id": "q-1", "response": {"status_code": 200, "request_id": "deeprelay_inf_7d1e…", "body": {"id": "chatcmpl-…", "object": "chat.completion", "choices": [{"index": 0, "message": {"role": "assistant", "content": "…"}, "finish_reason": "stop"}], "usage": {"prompt_tokens": 21, "completion_tokens": 38, "total_tokens": 59, "cost": 0.00002001}}}, "error": null, "deeprelay": {"rate_tier": "off_peak", "plan_covered": false}}
{"id": "batch_req_9a8b7c6d5e4f30211f0e0d0c", "custom_id": "q-2", "response": null, "error": {"code": "batch_expired", "message": "This request could not be executed before the batch expired."}, "deeprelay": {"plan_covered": false}}
response.bodyis what the synchronous endpoint returns, including the cost fields (usage.coston chat and responses,usage.deeprelay_coston messages), with one difference: the names of the infrastructure providers deeprelay routes to are replaced with "the provider" wherever they appear in the model's text (message content, thinking and reasoning text, tool-call arguments andtool_useinput values; tool-call arguments are treated as JSON, so their keys stay as they are, and an arguments string with a replacement comes back re-encoded the same way as the body). Brand names inside an address (a subdomain such asapi., an e-mail domain or a file path) are kept; a bare brand domain is replaced. Tool and function names, ids, URLs and the fields echoed from your request (.io metadata,instructions,tools) are never changed, and ordinary words are left alone. Two exceptions:logprobstokens are returned as the model produced them, and athinkingblock that had a name replaced no longer matches itssignature, so it is dropped if you send it back in a later request. A body with a replacement is re-encoded: the same values and numbers, with keys in sorted order and no extra whitespace. Every other body is byte for byte what the synchronous call returns.response.request_idis the request-log id. Every line that ran has a row in the request log withsource: batch, thebatch_id, yourcustom_idand itsrate_tier, soGET /v1/requests?batch_id=batch_…lists the batch line by line. The line costs add up exactly todeeprelay.coston the batch object.- The error file holds lines the endpoint answered with an error (the endpoint's own error is in
response.body) and lines that never ran:batch_expired,batch_cancelled,model_withdrawn,model_not_allowed_for_key,key_revoked,insufficient_scope,input_unavailable,internal_error(deeprelay failed while running the line; it was not billed), orbatch_result_lost(the line ran but its result could not be stored; it was not billed). Lines that never ran are not billed.model_withdrawnmeans the model was taken off batch; a model that is briefly unavailable leaves its lines queued until it returns or the batch expires. request_countsfollows OpenAI (total,completed,failed), anddeeprelay.request_countsaddscancelled,expiredandremaining.
Cancelling
POST /v1/batches/{id}/cancel stops the batch's queued lines at once. Lines
already running finish and are billed. The batch moves to cancelling and
then cancelled; its output file holds every completed line, and the error
file lists the rest as batch_cancelled. Cancelling a batch that is already
finishing or finished returns it unchanged.
Notifications
Subscribe a webhook to batch.paused,
batch.resumed, batch.completed, batch.expired and batch.cancelled
instead of polling.
Retention and deletion
Batch files are the one place deeprelay stores your request content, so they have a fixed lifetime and a real delete:
- Files are encrypted at rest and kept 30 days after the batch finishes (
expires_aton each file object), then deleted. DELETE /v1/files/{id}deletes a file and its content immediately. There are no versioned or replicated copies, so nothing is left to purge.- The input file of a batch that is still queued or running cannot be deleted:
409file_in_use. Cancel the batch first. - An input file must outlive the batch: a submit is refused when the input file expires within 7 days and 1 hour, which only happens if you uploaded it with a short custom
expires_after.
See the data policy for exactly what is stored and where.
Endpoints and access
The batch and file endpoints are listed under Endpoints. Writes
(upload, delete, create, cancel) need serverless:write; reads need
serverless:read. An admin or full_access key reaches every batch and
batch file in the organization; any other key only the ones it created (see
"Who sees a batch" above).
From the CLI: deeprelay files upload --file requests.jsonl, then
deeprelay batches create --input-file file-… --endpoint /v1/chat/completions,
deeprelay batches get and deeprelay batches results .
Image generation
POST /v1/images/generations is synchronous and OpenAI-compatible. v1 returns
images as base64 only — data[].b64_json carries the bytes, and
response_format:"url" is rejected with an invalid_request_error. The response
adds a usage.image_count field (the metered unit).
curl https://api.deeprelay.ai/v1/images/generations \
-H "Authorization: Bearer deeprelay_live_…" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/flux.2-dev","prompt":"a watercolor fox","n":1,"size":"1024x1024"}'
{ "created": 1733800000, "data": [{ "b64_json": "iVBORw0KGgo…" }], "usage": { "image_count": 1 } }
The deeprelay image CLI decodes the base64 and writes the file(s) for you:
deeprelay image "a watercolor fox in a misty forest" --model deeprelay/flux.2-dev --out fox.png
Generation time. Nothing comes back until the image exists. Most models
take 5 to 30 seconds; the GPT image models and large sizes take 30 to 60
seconds, and longer under load. deeprelay waits up to 4 minutes for one
request, then answers 504 upstream_timeout. Set your client timeout above
that (the OpenAI SDKs default to 10 minutes; the deeprelay image CLI waits
up to 5).
Upstream rate limits. When the upstream throttles a model, deeprelay waits
out the upstream's advised reset (when it is a few seconds) and retries, then
tries another provider for the model if there is one. If the throttle
persists you get 429 rate_limit_exceeded with Retry-After and
retry-after-ms set to the upstream's advised wait, so the OpenAI SDKs back
off on their own. Bursts of simultaneous requests to one model are the usual
cause; spacing them a couple of seconds apart avoids it.
n. Some models generate one image per request (for example
deeprelay/gemini-3-pro-image). On those, n above 1 is rejected with 400
upstream_rejected_request; send separate requests instead.
Video generation
Video generation is asynchronous. POST /v1/videos returns a job in the
queued state immediately; poll GET /v1/videos/{id} until the status reaches a
terminal value, then download the mp4 from GET /v1/videos/{id}/content.
Lifecycle. A job moves queued → in_progress → completed (or failed /
cancelled / expired). While in_progress the job carries a progress
value (0–100); some models report no granular progress and stay at 0 until
they complete.
Parameters. Each model declares the request parameters it accepts in its
catalog entry (parameters on GET /v1/models) — typically seconds (clip
length; bounds and default come from the descriptor). Parameters a model does
not declare are rejected with an invalid_request_error rather than silently
ignored: live video models generate at their default output resolution, so
most do not accept size. Omitting seconds uses the model's default clip
length.
Spend checks. A create is checked like any other paid call: against your
balance, the key's budget, the member's spending limit and the organization's
daily and monthly spending caps, on the clip's estimated cost (the model's
per-second price times seconds). A refusal is the matching 402
(insufficient_balance, api_key_budget_exceeded,
member_spend_limit_reached, daily_limit_reached or
spending_limit_reached) and no job is created.
Failures. A failed job carries a canonical code in error
(invalid_parameters, content_policy, upstream_error,
artifact_unavailable) and, when the upstream supplied a reason, a
human-readable error_message explaining it. Prefer error for branching and
error_message for display. The distinction that matters operationally is
invalid_parameters versus upstream_error: the first means the request itself
was rejected and will fail identically on every retry (for example a seconds
value outside the model's supported range), so fix the request rather than
retrying; the second may be transient. Failed jobs are never billed.
Billing. You're charged by seconds of output video, measured when the
job completes. Jobs that never complete — failed, cancelled, or expired
before finishing — are never billed. The authoritative charge is the
cost_cents field on the job object; note that a completed (billed) job
reports status: "expired" once its 24-hour artifact window lapses, with
cost_cents still attached.
Idempotency. Send an Idempotency-Key header on POST /v1/videos so a retry
of the same request returns the original job instead of starting (and charging
for) a second one.
Retention. Completed videos are retained for 24 hours — the job object
carries an expires_at (unix seconds). After that the artifact is gone and
GET /v1/videos/{id}/content returns 410 Gone with an expired error code.
Cancel. Stop an in-flight job with POST /v1/videos/{id}/cancel (a cancel
verb, not DELETE). Cancellation is idempotent — a terminal job is returned
unchanged, and a job whose output is already committed can no longer be cancelled.
# Create (idempotent) — returns a queued job
curl https://api.deeprelay.ai/v1/videos \
-H "Authorization: Bearer deeprelay_live_…" \
-H "Content-Type: application/json" \
-H "Idempotency-Key: 9f1c2b7e-…" \
-d '{"model":"deeprelay/seedance-1.0-lite","prompt":"ocean waves at sunset","seconds":5}'
# Poll until completed
curl https://api.deeprelay.ai/v1/videos/<video-id> -H "Authorization: Bearer deeprelay_live_…"
# Download the mp4
curl https://api.deeprelay.ai/v1/videos/<video-id>/content -H "Authorization: Bearer deeprelay_live_…" -o waves.mp4
# Cancel an in-flight job
curl -X POST https://api.deeprelay.ai/v1/videos/<video-id>/cancel -H "Authorization: Bearer deeprelay_live_…"
{ "id": "vid_…", "object": "video", "model": "deeprelay/seedance-1.0-lite",
"status": "completed", "progress": 100, "seconds": 5, "cost_cents": 18,
"created_at": 1733800000, "completed_at": 1733800240, "expires_at": 1733886640 }
The deeprelay video CLI wraps this lifecycle: create --wait polls to completion,
and download streams the mp4.
Embeddings
POST /v1/embeddings is synchronous and OpenAI-compatible. Pass input as
a single string or an array of up to 2048 strings (bounded so the response
stays under 64 MiB — about 680 inputs at 4096 dimensions; see Limits); the
response carries one vector per input, in request order, with data[].index
matching the input's position.
Find the served embedding models with GET /v1/models?modality=embedding — ids
have the usual deeprelay/{slug} form (e.g. deeprelay/qwen3-embedding-8b).
curl https://api.deeprelay.ai/v1/embeddings \
-H "Authorization: Bearer deeprelay_live_…" \
-H "Content-Type: application/json" \
-d '{"model":"deeprelay/qwen3-embedding-8b","input":["hello","world"]}'
{ "object": "list",
"data": [ { "object": "embedding", "index": 0, "embedding": [-0.019, 0.0071, …] },
{ "object": "embedding", "index": 1, "embedding": [0.004, -0.026, …] } ],
"model": "deeprelay/qwen3-embedding-8b",
"usage": { "prompt_tokens": 4, "total_tokens": 4 } }
The OpenAI SDK works unchanged:
from openai import OpenAI
client = OpenAI(base_url="https://api.deeprelay.ai/v1", api_key="deeprelay_live_…")
resp = client.embeddings.create(
model="deeprelay/qwen3-embedding-8b",
input=["first sentence", "second sentence"],
)
print(len(resp.data[0].embedding))
Billing. Embeddings are billed on input tokens only, at the model's
listed input_per_1m_tokens_cents rate. An embeddings call produces no
completion tokens, so the usage block carries prompt_tokens and
total_tokens only (no completion_tokens field): the metered cost is
usage.prompt_tokens × the input rate, in micro-cents. Like chat, usage is
settled once a minute in whole cents rounded down, with the sub-cent remainder
carried to the next settlement — there is no per-request minimum, so a small
call costs exactly its share. A single call takes up to 2048 inputs. Rollups
are available from
GET /v1/usage?modality=embedding.
Limits and unsupported parameters.
- Up to 2048 inputs per request, bounded so the response stays under 64 MiB — about 680 inputs at 4096 dimensions, fewer at a larger
dimensionsvalue. An over-limit batch is rejected with a400whose message states the limit, before any processing. A single input is capped at 32 KiB, the inputs combined at 1 MiB, and the whole request body at 2 MiB + 64 KiB (413). encoding_formatsupportsfloatonly.base64is rejected with400/invalid_request_error/unsupported_parameter.inputmust be text — a single string or an array of strings. Pre-tokenized token-id arrays are not supported.dimensionsis passed through, but only models that support truncated (Matryoshka) embeddings honour it.- A chat model id on this endpoint returns
404 model_not_found: the id is valid, but not on this surface.
Audio generation
Not yet available. The serverless catalog currently serves chat, embedding, image, and video models only — there is no audio (text-to-speech or music) endpoint, and generated videos do not include an audio track. If audio matters for your workload, tell us at support@deeprelay.ai.
Tool calling
tools and tool_choice are supported on the chat models that advertise
them. The model does not execute anything — it returns the call it wants
made, and running the function and feeding the result back is your loop.
Check support first. Tool calling is per-model, not account-wide. Look for
tools in the model's supported_parameters:
curl -s https://api.deeprelay.ai/v1/models?modality=chat \
| jq -r '.data[] | select(.supported_parameters | index("tools")) | .id'
Today every chat model in the catalog lists tools, and each one was verified
with a live tool-call probe. The catalog, not this sentence, is the source of
truth.
Sending tools to a model that does not list it fails cleanly with a 400
unsupported_parameter that names the models that do support tools. Nothing
reaches the upstream and nothing is billed. parallel_tool_calls: false is
covered in Parallel tool calls.
Making a call
curl https://api.deeprelay.ai/v1/chat/completions \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deeprelay/deepseek-v4-pro",
"messages": [{"role": "user", "content": "What is the weather in Paris?"}],
"tools": [{
"type": "function",
"function": {
"name": "get_weather",
"description": "Current weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
}
}],
"tool_choice": "auto"
}'
The reply carries finish_reason: "tool_calls" and a null content:
{
"choices": [{
"index": 0,
"message": {
"role": "assistant",
"content": null,
"tool_calls": [{
"id": "call_07db14bq3p5fkdbnv7fbsppj",
"type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}
}]
},
"finish_reason": "tool_calls"
}]
}
Two things about arguments that bite people:
- It is a JSON-encoded string, not an object. Parse it.
- A model can emit malformed JSON in it. Handle the parse failure rather than assuming it succeeds — this is the single most common source of a crash in a first tool-calling integration.
Closing the loop
Run the function yourself, then send the result back as a role: "tool"
message carrying the tool_call_id it answers. The assistant turn that made
the call must be replayed too, or the model has no record of having asked:
curl https://api.deeprelay.ai/v1/chat/completions \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "deeprelay/deepseek-v4-pro",
"messages": [
{"role": "user", "content": "What is the weather in Paris?"},
{"role": "assistant", "content": null, "tool_calls": [{
"id": "call_07db14bq3p5fkdbnv7fbsppj",
"type": "function",
"function": {"name": "get_weather", "arguments": "{\"city\": \"Paris\"}"}
}]},
{"role": "tool", "tool_call_id": "call_07db14bq3p5fkdbnv7fbsppj",
"content": "{\"temp_c\": 14, \"condition\": \"light rain\"}"}
],
"tools": [{"type": "function", "function": {"name": "get_weather",
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}}}}]
}'
Omitting tool_call_id on the tool message is a 400 from us, before the
request costs you anything.
Streaming
Tool calls stream as fragments, and a fragment is not independently
useful. The opening chunk carries id, type and function.name with empty
arguments; every chunk after it appends a slice of the arguments string:
data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"call_pem…","type":"function","function":{"name":"get_weather","arguments":""}}]}}]}
data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"city\": \""}}]}}]}
data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"Paris"}}]}}]}
data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"}"}}]}}]}
data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}
Accumulate by the index field, never by position in the tool_calls
array. A model can request several calls at once and their fragments
interleave; keying by position splices two different calls' arguments together
and produces JSON that parses cleanly and is wrong.
tool_choice
| Value | Effect |
|---|---|
"auto" | The model decides. The default when tools is present. |
"none" | Never call a tool. The only value valid with no tools array. |
"required" | Must call at least one tool. |
{"type":"function","function":{"name":"…"}} | Must call that specific function. |
Anything else is a 400 naming tool_choice.
deeprelay/glm-5.3 accepts "auto" only. Its upstream rejects the other
modes, so "none", "required" or a named function on glm-5.3 is a 400
naming tool_choice before anything is billed. Omit tool_choice or send
"auto". If you need to force a call, deeprelay/glm-5.2 supports every
mode.
From the CLI
deeprelay chat deeprelay/deepseek-v4-pro "What is the weather in Paris?" \
--tool '{"name":"get_weather","parameters":{"type":"object","properties":{"city":{"type":"string"}},"required":["city"]}}'
See deeprelay chat for --tool @file.json,
loading a whole toolset from one file, and --output json to pipe the calls
into your own dispatcher.
Coding agents depend on tool calling. To use one of these models from Cline, Roo Code, Aider, Zed or another agent, see Coding agents.
JSON mode & structured outputs
response_format is supported per model, and deeprelay never emulates it by
prompting. A response you get back with response_format set was constrained
by the upstream's sampler, or the request failed.
| You send | Needs in supported_parameters | What you get |
|---|---|---|
{"type":"json_object"} (JSON mode) | response_format | A single valid JSON object. |
{"type":"json_schema","json_schema":{…,"strict":true}} (structured outputs) | structured_outputs | A reply that matches your schema. |
{"type":"json_schema",…} without strict: true | structured_outputs, or response_format | Enforced where the upstream supports schemas. Otherwise it is served as JSON mode and reported as response_format:downgraded in x-deeprelay-ignored-params. |
{"type":"text"} | none | The default; the same as leaving it out. |
Send it to a model without the capability and you get a 400 that names the
models that have it, with nothing billed:
{ "error": { "message": "deeprelay/<model> does not support response_format json_schema with strict: true. Models that support it: deeprelay/…, deeprelay/…", "type": "invalid_request_error", "param": "response_format", "code": "unsupported_parameter" } }
Find the models that support it with the catalog:
curl -s https://api.deeprelay.ai/v1/models?modality=chat \
| jq -r '.data[] | select(.supported_parameters | index("structured_outputs")) | .id'
The schema is forwarded byte-for-byte. It may be at most 64 KiB and nested
at most 32 levels deep. A larger or deeper schema gets a 400
unsupported_parameter with param: "response_format". If the upstream
itself rejects a schema that passed those checks (a keyword it does not
support, say), you get a 400 upstream_rejected_request. The message is
fixed guidance pointing at this model's supported_parameters; the upstream's
own error body is never echoed. Fix the schema; retrying the same request
will not help.
from openai import OpenAI
client = OpenAI(base_url="https://api.deeprelay.ai/v1", api_key="deeprelay_live_…")
resp = client.chat.completions.create(
model="deeprelay/deepseek-v4.1-flash",
messages=[{"role": "user", "content": "What is the capital of France?"}],
response_format={
"type": "json_schema",
"json_schema": {
"name": "answer",
"strict": True,
"schema": {
"type": "object",
"properties": {"capital": {"type": "string"}},
"required": ["capital"],
"additionalProperties": False,
},
},
},
)
print(resp.choices[0].message.content) # {"capital": "Paris"}
print(resp.usage.cost) # what this call cost, in USD
function_call (the legacy form of tools) and logit_bias stay rejected with
400 unsupported_parameter. Use tools and tool_choice instead of
function_call.
Fallback: prompted JSON on models without response_format
On a chat model that lists neither response_format nor
structured_outputs, you can still ask for JSON in the prompt, then parse and
validate it yourself and retry on failure. This is best-effort: the
sampler does not constrain the model, so some responses will need the retry.
Prefer a model with native support when you can.
curl https://api.deeprelay.ai/v1/chat/completions \
-H "Authorization: Bearer deeprelay_live_…" \
-H "Content-Type: application/json" \
-d '{
"model": "deeprelay/<model>",
"temperature": 0,
"messages": [
{"role": "system", "content": "Reply with a single JSON object and nothing else. No prose, no markdown fences. Schema: {\"capital\": string}."},
{"role": "user", "content": "What is the capital of France?"}
]
}'
import json
from jsonschema import ValidationError, validate
from openai import OpenAI
client = OpenAI(base_url="https://api.deeprelay.ai/v1", api_key="deeprelay_live_…")
SCHEMA = {
"type": "object",
"properties": {"capital": {"type": "string"}},
"required": ["capital"],
"additionalProperties": False,
}
SYSTEM = (
"Reply with a single JSON object and nothing else. "
"No prose, no markdown fences. "
f"It must validate against this JSON Schema: {json.dumps(SCHEMA)}"
)
def structured(question: str, attempts: int = 3) -> dict:
"""Best-effort structured output: prompt for JSON, parse, validate, retry."""
last_error = None
for _ in range(attempts):
resp = client.chat.completions.create(
model="deeprelay/<model>",
temperature=0,
messages=[
{"role": "system", "content": SYSTEM},
{"role": "user", "content": question},
],
)
text = resp.choices[0].message.content.strip()
# Models sometimes wrap JSON in a fence despite the instruction.
if text.startswith("```"):
text = text.strip("`").removeprefix("json").strip()
try:
data = json.loads(text)
validate(instance=data, schema=SCHEMA)
return data
except (json.JSONDecodeError, ValidationError) as err:
last_error = err
raise RuntimeError(f"no valid JSON after {attempts} attempts: {last_error}")
print(structured("What is the capital of France?"))
Replace deeprelay/ with a chat model from GET /v1/models?modality=chat.
temperature: 0 and a
short, explicit schema in the system prompt materially cut the retry rate;
jsonschema can be swapped for pydantic if you already model your responses
there.
Log probabilities
logprobs: true returns per-token log probabilities in choices[].logprobs,
in OpenAI's shape. top_logprobs: N adds the N most likely alternatives for
each token. Both are gated on logprobs in the model's
supported_parameters. top_logprobs needs logprobs: true, and each model
has its own maximum, up to 20. A larger value gets a 400 that states that
model's limit (top_logprobs must be ≤ 5 for deeprelay/…).
Streaming responses carry each chunk's log probabilities on that chunk. Non-streaming responses carry the whole sequence on the choice.
Log probabilities are not comparable across upstreams or precisions. They are the serving upstream's own numbers. Two upstreams serving the same model, or the same weights at different numeric precision, give different values for the same text. Compare them within one response, not across requests or models.
Reasoning effort and sampling hints
reasoning_effort, presence_penalty, frequency_penalty and seed are
hints. Each one is forwarded when the upstream serving your request accepts
it, and otherwise dropped and reported by name in x-deeprelay-ignored-params.
A hint never causes a 400.
reasoning_effort: the values in use arenone,minimal,low,medium,high,xhighandmax(DeepSeek V4 models; on DeepSeek V4.1 Flashmaxis its deepest reasoning mode, abovexhigh). Which ones a model accepts varies by model and by upstream. A model'sGET /v1/modelsentry lists the efforts it takes inreasoning_efforts(absent when the catalog lists none). A value the serving upstream does not accept is dropped, and the model thinks at its default effort. Leaving it out has the same effect: see When you don't setreasoning_effort.presence_penalty,frequency_penalty:-2to2. A value outside that range is dropped rather than rejected.seed: best-effort determinism on the upstream that honours it. The same seed is not guaranteed to reproduce output across upstreams.
When you don't set reasoning_effort
deeprelay does not choose an effort for you, and it does not turn reasoning
off to save you tokens. A request without reasoning_effort reaches the
model without one, and the model behaves exactly as it does on its vendor's
own API. For nearly every model that lists reasoning_efforts, that default
is to reason before answering.
That matters for cost and latency. Reasoning tokens are billed at the output
rate, they are part of completion_tokens, and they are generated before the
first visible token. A one-number answer to a simple arithmetic question
measured 161 output tokens with no effort set, 155 of them reasoning, and 3
output tokens with reasoning_effort: "none".
Three places show you what happened on a request:
usage.completion_tokens_details.reasoning_tokensin the response body is how many of the output tokens were reasoning.- The
x-deeprelay-reasoning-effortresponse header readsmodel-defaultwhen no effort reached the model. deeprelay chatprints a note to stderr when you set no effort and the model reasoned.
To change it, send the effort you want:
{
"model": "deeprelay/deepseek-v4.1-flash",
"messages": [{"role": "user", "content": "What is 17 * 23?"}],
"reasoning_effort": "none"
}
none turns reasoning off where the model allows it, and low keeps it
short. A few models always reason. On those, none is dropped like any other
value the upstream does not take: x-deeprelay-ignored-params lists
reasoning_effort, and x-deeprelay-reasoning-effort still reads
model-default. Check both headers once when you adopt a model, rather than
assuming the value was applied.
An answer with no visible text
Reasoning tokens count toward max_tokens (or max_completion_tokens) and
are billed as output. If the cap is reached while the model is still
reasoning, it never starts the answer. The response then has:
finish_reason: "length",- empty
content, usage.completion_tokens_details.reasoning_tokensequal tocompletion_tokens.
The model did the work, so the request is billed, or counts toward your plan
allowance, like any other. The console's recent requests list marks it
"no answer text". To get an answer, raise max_tokens /
max_completion_tokens, or lower reasoning_effort (low, or none where
the model allows it).
Parallel tool calls
parallel_tool_calls: false asks the model for at most one tool call per
turn. Where the serving upstream supports the flag it is forwarded. Where it
doesn't, deeprelay enforces it: the reply carries only the model's first tool
call, on streaming and non-streaming responses alike, and the response
reports parallel_tool_calls:enforced in x-deeprelay-ignored-params. The
call you receive is byte-for-byte what the model produced, and finish_reason
is unchanged. parallel_tool_calls: true (the default) is a hint. It is
dropped where the upstream does not accept it.
Image input
Chat models whose GET /v1/models entry lists vision in
supported_parameters accept OpenAI image_url content parts:
{
"model": "deeprelay/kimi-k3",
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": "What is in this picture?"},
{"type": "image_url", "image_url": {"url": "https://example.com/cat.png"}}
]
}]
}
- Which models: today that is
deeprelay/deepseek-v4.1-flash,deeprelay/glm-5.3-flash,deeprelay/kimi-k3,deeprelay/kimi-k3.1-proanddeeprelay/qwen3.5-9b. The catalog is the source of truth, so checksupported_parametersforvisionrather than relying on this list. Any other model returns400unsupported_parameter(param: "messages"), naming the models that accept images, and nothing is billed. - URLs: an
https://URL, or a data URI of the formdata:image/{png,jpeg,webp,gif};base64,…. Any other scheme or media type is a400. deeprelay never fetches the image itself; the upstream does. An https URL must therefore be publicly reachable. - Limits: 20 MiB per image (decoded) and 8 KiB per URL. The whole request body is capped at 32 MiB, and a larger body gets
413request_too_large. There is no fixed count limit on inline (data URI) images, so a coding agent can keep its screenshot history. Images given as https URLs are capped at 32 per request (400too_many_images), because the upstream fetches each one. - Per-model image limits: some models' upstreams accept fewer images per request than others. deeprelay routes a request only to a host that can take its image count. If none can, the request fails with
400too_many_images, and the message names the model's limit. Drop older images from the conversation to get under it. detail(auto/low/high) is accepted but not forwarded. Its presence is reported asimage_url.detailinx-deeprelay-ignored-params.- Cost: image tokens are billed as prompt tokens at the model's input rate, as the upstream counts them. Before the request is admitted, each inline image is estimated from its pixel size (about one token per 28×28 pixels, so an 800×500 screenshot counts as about 540 tokens) toward the spend and context checks. An image given as an https URL counts as 1,600 tokens.
Audio and file parts are still rejected with 400 unsupported_content_part.
Cost in the response
Every chat completion reports what it cost, in USD, inside usage:
"usage": {
"prompt_tokens": 1200, "completion_tokens": 300, "total_tokens": 1500,
"prompt_tokens_details": {"cached_tokens": 1024},
"cost": 0.00041,
"cost_details": {
"list_price_equivalent": 0.00041,
"plan_covered_amount": 0,
"charged_amount": 0.00041,
"quota_units_used": null,
"cache_savings": 0.00023
}
}
| Field | Meaning |
|---|---|
cost | The amount charged to your wallet for this call. Always equal to charged_amount, so it is 0 when the flat subscription covered the call. |
list_price_equivalent | The call priced at the model's pay-as-you-go rates actually applied: cached-input rates for cache hits, and peak rates inside a peak window. |
plan_covered_amount | The part the flat subscription covered. |
charged_amount | The part charged to your wallet. |
quota_units_used | Subscription quota consumed, in weighted tokens (the units of the quota headers). 0 for a subscriber call billed pay-as-you-go. null for a pay-as-you-go organization. |
cache_savings | What the prompt cache saved: the same call at the uncached input rate, minus list_price_equivalent. null when the upstream did not report cache usage. It can be negative on a model whose cached rate is not a discount. |
plan_covered_amount + charged_amount = list_price_equivalent, exactly. A call
is either fully covered by the subscription or fully charged, never split.
The one exception is web search overflow: when it is on,
the overflow search fee is charged and the rest of the call stays covered.
cache_savings sits outside that sum.
- Format: amounts are JSON numbers with up to 8 decimal places, rendered exactly from the integer ledger value. A nonzero cost never shows as
0. - Where it appears: non-streaming responses carry it in the body and in an
x-deeprelay-costheader with the same value. Streaming responses carry it only in the final usage chunk (stream_options.include_usage, on by default), never in a header. prompt_tokens_details.cached_tokensis present whenever the upstream reported cache usage, even when the count is0. It is absent when the upstream didn't report it.- Invoices come from the billing ledger, not from these fields. The response is computed by the same pricing function from the same inputs, and tests pin the two to the micro-cent. Use
usage.costfor per-request accounting andGET /v1/usagefor the totals you are billed on.
Subscription quota headers
When your organization is on a subscription plan, every response to your keys carries its remaining allowance — the allowance of the plan you are on, Base or Plus — so a client or a status line can show it without a second call:
| Header | Meaning |
|---|---|
x-deeprelay-quota-input-remaining | Monthly input quota left |
x-deeprelay-quota-output-remaining | Monthly output quota left |
x-deeprelay-quota-reset | When the monthly meters reset (the end of the billing period), RFC 3339 |
x-deeprelay-quota-weekly-input-remaining | What is left in this week's input cap |
x-deeprelay-quota-weekly-input-limit | The weekly input cap |
x-deeprelay-quota-weekly-output-remaining | What is left in this week's output cap |
x-deeprelay-quota-weekly-output-limit | The weekly output cap |
x-deeprelay-quota-weekly-reset | When both weekly caps reset, RFC 3339 |
x-deeprelay-quota-search-remaining | Web searches left this month |
x-deeprelay-quota-search-limit | The monthly web-search allowance (Base 100, Plus 500) |
- Units are weighted tokens: tokens × the model's usage factor, except the two search headers, which count searches.
GET /v1/modelsreports the factor asusage_factor_milli(×1000, omitted at the default 1.0×). These are the same units asusage.cost_details.quota_units_used. - Values are as of the start of the request. They don't include the call they arrive on, because on a stream the headers go out before any tokens are counted. A streaming and a non-streaming response to the same request carry identical values.
- Both weekly caps reset together, once a week, at
x-deeprelay-quota-weekly-reset. Your week is fixed: it resets on the weekday and at the time of day your subscription started (for example every Thursday at 10:14 UTC), not with the billing period. The input and output caps are independent: either one can run out first. - A cap that isn't set is omitted rather than reported as a number. Remaining values stop at
0. - Pay-as-you-go keys get none of these headers.
- The headers also appear on quota and spend denials.
Only plan-covered calls draw on the quota. That leaves out calls to models the
plan does not cover, and calls that fell back to pay-as-you-go because the
quota was spent. A subscriber request whose estimated input or output would
overshoot what is left in the tighter of the monthly and weekly
windows also falls back to pay-as-you-go instead of consuming it. The input
estimate counts everything sent to the model as input (the messages and also
tools definitions, earlier tool_calls, tool_choice and a
response_format schema), so a request with a large tools array reaches
input_overshoot sooner than its message text alone would suggest. The output
estimate is the completion bound: max_tokens, or the model's declared
maximum when you don't set one. If the wallet cannot pay for that fallback
either, the 429 carries param: input_overshoot or param: output_overshoot
rather than a gate name. When less than 1% of that window is left, the
message says the cap is effectively used up, because no ordinary request
fits. Otherwise the request alone is too big for what is left: send a
smaller request (or a smaller max_tokens), or add credits.
From the CLI, deeprelay quota prints the same numbers, and
deeprelay quota --short prints one line for a status bar with five meters:
monthly input, monthly output, weekly input, weekly output and the usage
backstop. The line ends in
payg when calls were billed to the wallet in the last 24 hours, followed
by search= when the plan includes web searches. See
deeprelay quota.
Rate limits
Each API key may send a fixed number of requests per one-second window: its
requests per second plus its burst allowance (by default 100 + 200, so 300
requests in any one second). The counter starts over at the next second.
Every response that passed the limiter reports where you stand, on success
and on a 429 alike:
/v1/chat/completions and the other OpenAI-format endpoints | /v1/messages | Meaning |
|---|---|---|
x-ratelimit-limit-requests | anthropic-ratelimit-requests-limit | Requests the key may send per one-second window |
x-ratelimit-remaining-requests | anthropic-ratelimit-requests-remaining | Requests left in the current window, this one counted. Stops at 0 |
x-ratelimit-reset-requests | anthropic-ratelimit-requests-reset | When the window ends and the full limit is back: a duration such as 300ms on the OpenAI format, an RFC 3339 time on / |
- This is a per-second window, not a token bucket. The limit is the whole window's allowance, and remaining drops by one per request until the window ends.
- This limiter sends no token headers. It counts requests, not tokens.
x-ratelimit-*-tokensandanthropic-ratelimit-tokens-*belong to the per-minute token allocation of an enterprise account. Subscription quota is reported separately, in the quota headers above. - A
429rate_limit_exceededalso carriesRetry-After(whole seconds, rounded up) andretry-after-ms(exact). Both are the time until one request is allowed again, which for a per-second window is the start of the next window. The official OpenAI and Anthropic SDKs preferretry-after-ms, so they retry after a few hundred milliseconds rather than a full second. - If the limiter can't be reached, requests are let through and these headers are left off rather than guessed.
Per-minute token allocations
An enterprise account can hold a tokens-per-minute allocation for a model,
whether it is billed by invoice (see Endpoints) or pays up
front from its credit balance. On /v1/chat/completions,
/v1/messages, /v1/responses and /v1/embeddings, the allocation is then
the one throughput limit for that model: those requests are not counted
against the key's per-second rate limit or its concurrent-stream cap, and
their responses report the allocation in place of the request headers above:
| OpenAI-format endpoints | /v1/messages | Meaning |
|---|---|---|
x-ratelimit-limit-tokens | anthropic-ratelimit-tokens-limit | The allocation, in tokens per minute |
x-ratelimit-remaining-tokens | anthropic-ratelimit-tokens-remaining | Tokens left in the current clock minute. Stops at 0 |
x-ratelimit-reset-tokens | anthropic-ratelimit-tokens-reset | When the minute ends: a duration such as 42s on the OpenAI format, an RFC 3339 time on / |
Tokens are counted as they are billed, prompt plus completion, in the clock
minute a request finishes in. Once the minute's count reaches the allocation,
further requests for that model get a 429 rate_limit_exceeded with
Retry-After and retry-after-ms set to the time left in the minute:
{ "error": { "message": "You have reached your allocation of 1000000 tokens per minute for deeprelay/glm-5.3. Retry after the indicated interval, or request a larger allocation from Billing in the console.", "type": "rate_limit_error", "code": "rate_limit_exceeded" } }
An organization admin can request a larger allocation from Billing in the
console. Models the account holds no allocation for keep the per-key limits
above. On a model with an allocation, a request falls back only to
backup models the account also holds an allocation for; a
backup model's tokens count toward its own allocation. A backup model whose
own allocation is used up for the minute is passed over, and the request log
shows it skipped as rate_limit_exceeded.
Listing models without a key
GET /v1/models works without an API key and returns exactly the same body
as an authenticated request: pricing, context length, supported_parameters,
plan_covered, the published metrics
and, where it applies, weights_verification.
The one exception is a key with a model allowlist, which
sees only its allowed models.
curl https://api.deeprelay.ai/v1/models?modality=chat
- Caching: an anonymous response is
Cache-Control: public, max-age=60with a strongETag. Send it back asIf-None-Matchto get a304. An authenticated response isCache-Control: private, and errors areno-store. - Limits: anonymous requests are rate-limited per client IP (
429rate_limit_exceededwithRetry-After). An authenticated request uses your key's limit instead. A key that is sent but invalid gets a401; the request does not fall back to anonymous access. - Fields:
owned_byis the model's author (the same value asauthor), ordeeprelaywhen the author is unknown.createdis always present and currently0.plan_covered: truemeans "included in the flat subscription". It is a fact about the model, the same for every caller, and says nothing about your own plan. Economy-tier notes are no longer included. - Coding agents:
recommended_for: ["coding-agents"]marks the models deeprelay has tested with coding agents, andcoding_agent_rankorders them, 1 first.deeprelay setupwrites these models, and makes the rank-1 model the agent's default. Both fields are omitted on every other model. - Limits and reasoning:
max_completion_tokensis the model's maximum output in tokens, andreasoning_effortslists thereasoning_effortvalues it accepts. Each is omitted when the catalog lists none.tierisserverlessoreconomy(see "Tiers" above). GET /v1/models/{id}still requires a key. For a key with a model allowlist, an id off the list answers403model_not_allowed_for_key.
Published speed and reliability
Every model in GET /v1/models (with or without a key) and
GET /v1/models/{id} carries a metrics object: how fast and how reliably
deeprelay served that model to customers over the last 7 days.
"metrics": {
"window_days": 7,
"as_of": "2026-10-09T14:00:00Z",
"sample_count": 18342,
"stream_sample_count": 15210,
"min_samples": 100,
"min_stream_samples": 20,
"ttft_p50_ms": 412,
"tokens_per_second_p50": 96.4,
"success_rate": 0.9962,
"insufficient_data": false,
"precision": "unverified"
}
| Field | Meaning |
|---|---|
window_days, as_of | The figures cover the 7 days before as_of, the hour they were computed for. They are recomputed every hour. |
sample_count | Requests behind success_rate: successes plus failures. |
stream_sample_count | Successful streamed requests behind the two speed figures. |
min_samples, min_stream_samples | How many samples a figure needs before it is published (100 and 20). |
success_rate | Successes ÷ (successes + failures), between 0 and 1. |
ttft_p50_ms | Median time to first token, in milliseconds, over successful streamed requests. |
tokens_per_second_p50 | Median decode rate after the first token, over successful streamed requests: completion tokens ÷ (duration − time to first token). |
insufficient_data | true when sample_count is below min_samples. |
precision | What deeprelay can state about the numeric precision the model is served at (below). |
Definitions.
- Success: the request completed, or you cancelled it after the first token arrived.
- Failure: a server error,
upstream_unavailable, or a timeout. - Excluded: errors caused by the request itself (a bad parameter, a context that is too long, a request the upstream refused as invalid), requests refused before they reached a model, and requests you cancelled before the first token. They count as neither success nor failure.
- Chat traffic only: chat completions, messages and responses.
Too few samples. Below its minimum, a figure is left out of the object,
never published as 0. Below min_samples, insufficient_data is true and
there is no success_rate; below min_stream_samples there is no
ttft_p50_ms or tokens_per_second_p50. The counts and minimums are always
present so you can see why.
Precision.
precision | Meaning |
|---|---|
full | Every route serving the model runs at full precision. |
mixed | At least one route serves the model at reduced (quantized) precision. |
unverified | deeprelay has not verified the precision of every route. This is the default, and today every model reports it. |
Methodology. Figures are measured from real customer traffic over the last 7 days and refreshed hourly. Staff, CI and probe traffic is excluded. Success rate counts requests that completed or that you cancelled after the first token; failures are server errors and timeouts, and errors caused by the request itself are excluded.
Verified weights
A chat model whose open weights the latest public verification run verified
carries a weights_verification object in GET /v1/models (with or without
a key) and GET /v1/models/{id}, after metrics. The run samples the same
prompts from deeprelay and from independent deployments of the same
weights (the vendor's own API among them) and judges them with Model
Equality Testing (Gao, Liang, Guestrin, ICLR 2025), a published two-sample
test run through its authors' package; a top-k logprob fingerprint
corroborates where a host returns log-probabilities. verified means the
relay's completions were judged to come from the same model as those
references, so a lower price was not bought with different or quantized
weights. The check runs once a day from the public harness repository, so
the mark reflects the latest daily run, and the field is withdrawn when
that run is older than 14 days. Anyone can rerun the harness against
api.deeprelay.ai with their own DeepSeek, Alibaba, Z.ai, Together or
Fireworks keys and get the same verdict.
"weights_verification": {
"status": "verified",
"weights": "deepseek-ai/DeepSeek-V4.1-Flash",
"verified_at": "2026-11-03T21:10:00Z",
"run_id": "19876543210",
"run_url": "https://github.com/deeprelay-dev/model-fingerprint/actions/runs/19876543210",
"harness_version": "2026.11.10",
"references": 2,
"method_url": "https://github.com/deeprelay-dev/model-fingerprint"
}
| Field | Meaning |
|---|---|
status | Always verified. The object is absent in every other case. |
weights | The Hugging Face repo the served weights were verified against. |
verified_at | When the run that made the finding finished. |
run_id, run_url | The public GitHub Actions run. Its report and job log hold every number behind the verdict. |
harness_version | The version of the measuring code that run used. |
references | How many independent deployments of the same weights deeprelay was compared against. |
method_url | The public harness repository that defines the method and runs it. |
Absence is the only negative. The key is omitted for a model the latest
run did not verify, whatever the reason: closed weights, a model outside the
run's matrix, a run that was inconclusive or did not have enough data, an
image, video or embedding model, or a latest run older than 14 days. deeprelay
never publishes a failing verdict here; the full per-run reports are on
GET /v1/benchmarks/latest (see benchmarks).
The object is derived from the newest run the harness published, through a
short cache, so a new run reaches the catalog within about a minute. The CLI
shows it as the WEIGHTS column of deeprelay models list and the
Weights verified and Verification run rows of deeprelay models get.
Balance and quota alerts
deeprelay can tell you before a balance, a plan allowance, a key budget or a member limit runs out. Alerts are worked out in the background after each call, never in the request path, and arrive by email and as webhook events.
| Alert | Fires at | Emailed to | Webhook event |
|---|---|---|---|
| Low balance | the wallet falls below your threshold (default $5.00) | org admins | balance.low |
| Subscription quota | 80% and 100% of each allowance: monthly input, monthly output, weekly input, weekly output | org admins | subscription_quota.threshold |
| Key budget | 80% and 100% of a key's monthly budget | org admins and the key's creator | api_key_budget.threshold |
| Member spend | 80%, 95% and 100% of a member's spending limit | org admins and the member | member_spend.threshold |
- Once per crossing. Each threshold fires once when it is crossed. It re-arms when the period resets or when the value falls back below the threshold, for example after a top-up.
- Every alert states the cap, the current value, the limit and the reset time, and links to the request log filtered to that period (and key).
- Subscribers don't get low-balance alerts while the plan covers all their calls: the alert arms once a call in the billing month is charged to the wallet. The 100% quota alert states the wallet balance, because further calls bill the wallet, or fail if the balance is zero.
Settings. GET /v1/alerts/settings returns the low-balance threshold and
an email on/off switch for each of the four alerts. PUT /v1/alerts/settings
replaces them all at once and needs an org admin's key or a full_access key
(403 forbidden otherwise), plus the billing:write scope.
curl -X PUT https://api.deeprelay.ai/v1/alerts/settings \
-H "Authorization: Bearer $DEEPRELAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"balance_threshold_cents":1000,
"email":{"balance_low":true,"subscription_quota":true,"api_key_budget":true,"member_spend":true}}'
From the CLI, deeprelay alerts get shows the settings and deeprelay alerts set
changes only the fields you pass, for example
deeprelay alerts set --balance-threshold 10; see
deeprelay alerts.
The switches only turn off the org-level emails. A member always receives the emails about their own spending limit. Webhook delivery is set per endpoint when you subscribe it to the events; see Webhooks.
Errors
Errors use the OpenAI envelope, so SDK error handling works as-is (the /v1/messages endpoints use the Anthropic envelope instead; see Anthropic Messages API):
{ "error": { "message": "…", "type": "invalid_request_error", "code": "model_not_found" } }
Error responses also carry an X-Deeprelay-Error-Code header set to the same
code (for example model_not_found, rate_limit_exceeded,
insufficient_balance). The header uses one set of codes across every endpoint,
so you can branch on or count errors without parsing the body. (An error that
arrives mid-stream as an SSE error event, including after a
slow start, carries its code in the event body
only.)
Model availability. The serverless catalog is live, so a model id that worked
earlier can stop being served. When that happens you get a model_not_found
(404) with a "Try another model" message — re-fetch GET /v1/models for the
current list and pick another. On the streaming endpoint this arrives as the
final SSE error event before [DONE].
Concurrent-stream cap. Each API key may have a limited number of inference
requests open at once. If you exceed it you get a 429 with code
stream_limit_exceeded:
{ "error": { "message": "Too many concurrent streams open for this API key — close existing streams or retry shortly.", "type": "rate_limit_error", "code": "stream_limit_exceeded" } }
Close any streams you are no longer reading, or retry shortly — the slot frees
as soon as an in-flight request finishes. This is separate from the per-second
rate limit (rate_limit_exceeded), which bounds request rate rather than the
number of simultaneously-open requests.
Upstream temporarily unavailable. If a model's serving capacity is degraded,
requests may return a 503 with code upstream_unavailable:
{ "error": { "message": "Upstream service temporarily unavailable.", "type": "api_error", "code": "upstream_unavailable" } }
This is returned promptly (no long wait) while capacity recovers — retry after a
short interval. The platform automatically routes around a degraded endpoint and
resumes serving it once it recovers, so a 503 here is transient.
Account frozen. If your organization's account has been frozen (for
nonpayment or a terms violation), every billable endpoint (chat, embeddings,
images, videos, responses, messages, fine-tuning job creation and file upload)
returns a 403 with code account_frozen:
{ "error": { "message": "Your organization's account is frozen and cannot run inference. Contact support to restore access.", "type": "permission_denied", "code": "account_frozen" } }
Topping up does not clear this state: contact support. The cancel routes
(POST /v1/videos/{id}/cancel, POST /v1/fine_tuning/jobs/{id}/cancel) stay
available so you can still stop running jobs. On the /v1/messages surface
the same denial arrives in the Anthropic envelope (permission_error) with
x-should-retry: false.
Request errors from chat.
| Status / code | When |
|---|---|
400 unsupported_parameter | A gated parameter sent to a model without the capability. The message names the models that have it. Also returned for logit_bias, function_call, an out-of-range top_logprobs, and a json_schema or tool function.parameters schema over 64 KiB or 32 levels deep (param is tools for the latter). |
400 upstream_rejected_request | The upstream refused a request that passed deeprelay's checks, for example a schema keyword it does not support. The message is fixed guidance (check the model's supported_parameters); the upstream's own error body is never echoed. Not retryable as-is. |
400 context_length_exceeded | Your input does not fit the model's context window. Shorten the input (or lower max_tokens); retrying the same request will not help. |
404 model_not_found | Also returned when you send a non-chat model id (an image, video or embedding model) to /, and when the upstream itself no longer serves the model. Pick another model; GET / has the current list. |
403 model_not_allowed_for_key | The key has a model allowlist and the model is not on it, or does not exist. Returned on every inference endpoint. |
413 request_too_large | The request body is over 32 MiB. |
408 request_body_timeout | Your request body stopped arriving: no data reached us for 60 seconds, or the upload took longer than 30 minutes in total. A network problem between you and us, not your JSON; retry. A slow connection is fine as long as data keeps flowing. |
502 upstream_error | deeprelay's own credential, entitlement or balance with the upstream provider failed. This is our fault, never yours: your API key is fine and nothing is billed. It usually clears once we fix the provider account or routing; retry later. |
503 upstream_unavailable | Also returned when the model supports what you asked for but none of its upstreams that can serve it is available right now. |
504 upstream_timeout | The upstream stopped producing output: no first token in time, or no new tokens for 2 minutes once the response had started. When the model has another provider, a stalled first token is handed to it before you see anything, so this means every provider tried stalled. Nothing is billed for a stalled attempt. Transient; retry. |
Any of the above, with X-Deeprelay-Fallback-Attempted: | Backup models were tried and none served. The status, code and retry headers are the requested model's own; the header says how many models were dialled, and the message says fallback was attempted and quotes the request id. The request log row lists every attempt. Retry as you would for the code alone. |
Long responses are not cut off. There is no fixed time limit on a
response that is still producing tokens. Long reasoning answers and large
generations stream for as long as they need, up to 30 minutes per request.
What ends a request early is silence: an upstream that sends no new tokens
for 2 minutes is treated as stalled and fails with upstream_timeout.
When the request has backup models left, a stream is held until its first token arrives, so that a stall on the requested model can still move to a backup before you see anything. Nothing is lost by the hold, but a client with a short read timeout may wait longer for the first byte than it would without backups (up to the 90-second first-token wait per model, inside the chain's shared time budget). The last model in the chain is not held.
A failed request to a model does not count against that upstream's health. Bad parameters and unknown models are your request's problem, not an outage, so they never cause other customers' requests to be shed.
Governance errors. These come from the limits you set on keys, members
and key management. Each carries its code in X-Deeprelay-Error-Code, and the
refused inference calls appear as rejected rows in the
request log.
| Status / code | When |
|---|---|
402 api_key_budget_exceeded | The call would take the key past its monthly budget. The message names the key and the reset date. |
402 member_spend_limit_reached | The call would take the key's creator past their member spending limit. The message names the reset date. |
403 model_not_allowed_for_key | The key's allowlist does not include the model, or the model does not exist. The same answer for both. |
403 keys_manage_required | A key without keys:manage tried to create, change or revoke a key. |
Batch API errors. These come from /v1/files, /v1/batches and
/v1/messages/batches; see Batch API.
| Status / code | When |
|---|---|
400 batch_validation_failed | One or more lines of the file are invalid (bad JSON, a bad or duplicate custom_id, a url that differs from the batch endpoint, stream: true, more than one model, or a body the endpoint itself rejects). The message lists the line numbers. Also: the model has no off-peak time, or the input file expires too soon. Nothing is stored or billed. |
400 batch_limit_exceeded | The file, a line, your stored files, your unfinished batches or your queued tokens are over a limit. The message names the limit and your value. |
400 invalid_purpose | POST / with a purpose other than batch. |
400 invalid_completion_window | completion_window is anything but "24h". |
400 server_tool_unsupported | A line uses web search or another server tool. |
400 message_batches_unsupported | POST / (Anthropic envelope). Use / with url: /. |
402 insufficient_balance, api_key_budget_exceeded, member_spend_limit_reached, spending_limit_reached, daily_limit_reached | The batch's estimated cost does not fit. The message states the estimate. It is not a hold. |
409 file_in_use | DELETE / on the input of a batch that is still queued or running. Cancel the batch first. |
410 expired | The file is past its expires_at. |
413 request_too_large | The upload is over the file-size limit. |
Retries
The headers tell a client whether a retry can succeed. The official OpenAI and Anthropic SDKs read them, so their automatic retries do the right thing unchanged.
| Response | Headers | Retry? |
|---|---|---|
429 rate_limit_exceeded | Retry-After (whole seconds, rounded up, never 0) plus retry-after-ms: the time until one request is allowed. See Rate limits. On / it can also be the upstream throttling the model; the wait is then the upstream's advice (see Image generation). | Yes, after the wait |
503 upstream_unavailable | Retry-After plus retry-after-ms. The wait is jittered between 2 and 2.5 seconds, so clients don't retry in lockstep. | Yes, after the wait |
408 request_body_timeout | none | Yes: the request body arrived too slowly; the OpenAI and Anthropic SDKs retry 408 automatically |
504 upstream_timeout | none | Yes: the upstream missed its deadline once; a retry usually lands on a healthy attempt |
502 upstream_error | none | Later: this is deeprelay's provider credential or balance failing, not your request. An immediate retry hits the same fault; retry after a pause while we fix the account or route around it |
429 subscription_quota_exhausted | x-should-retry: false, no Retry-After | No: wait for the reset, top up, or upgrade to Plus (deeprelay billing upgrade) |
402 insufficient_balance, daily_limit_reached, spending_limit_reached | x-should-retry: false, no Retry-After | No: top up or raise the limit. Exception: when only your other calls in progress caused it, x-should-retry: true with Retry-After (see Member spending limits) |
403 account_frozen | x-should-retry: false (Anthropic envelope), no Retry-After | No: contact support; topping up does not clear a freeze |
402 api_key_budget_exceeded, member_spend_limit_reached | x-should-retry: false, no Retry-After | No: wait for the reset date in the message, or raise the budget or limit. Exception: when only your other calls in progress caused it, x-should-retry: true with Retry-After |
403 model_not_allowed_for_key | x-should-retry: false, no Retry-After | No: call a model on the key's allowlist, or use another key |
403 keys_manage_required | no Retry-After | No: use a key with keys:manage |
403 account_frozen | x-should-retry: false (Anthropic envelope), no Retry-After | No: contact support; topping up does not clear a freeze |
A subscriber whose quota is spent is not refused while the wallet can pay. The
call falls back to pay-as-you-go, and usage.cost_details shows it
(quota_units_used: 0, charged_amount = the list price).
subscription_quota_exhausted means the fallback could not be paid for
either.
On the OpenAI envelope, the param of a 429 subscription_quota_exhausted
says why:
monthly_input_tokens: the monthly input token quota is used up.monthly_output_tokens: the monthly output token quota is used up.weekly_input_tokens: the weekly input cap is reached. The error also carriesquota_frees_at(below).weekly_output_tokens: the weekly output cap is reached. The error also carriesquota_frees_at.max_usage: the monthly usage backstop is reached.input_overshoot: the estimated input of this one request exceeds what is left in the tighter of the monthly and weekly input allowances. If less than 1% of that window is left, the message says the cap is effectively used up. Otherwise a smaller request is admitted right away. When the tighter window is the weekly one, the error also carriesquota_frees_at.output_overshoot: the estimated output of this one request (max_tokens, or the model's declared maximum) exceeds what is left in the tighter of the monthly and weekly output allowances. The same 1% rule applies, and otherwise a smallermax_tokensis admitted right away. It carriesquota_frees_aton the same terms asinput_overshoot.
Every one of them sends x-should-retry: false. The /v1/messages
envelope has no param, so tell the cases apart from stable signals, not
from the message:
X-Deeprelay-Error-Code: subscription_quota_exhausted(on both envelopes) says the denial is a quota one. It is the same for every gate.- The quota headers on the same response are the request-start readings, and a remaining header that reads
0names an exhausted window. Take the first in gate order:x-deeprelay-quota-input-remaining(monthly input),x-deeprelay-quota-output-remaining(monthly output),x-deeprelay-quota-weekly-input-remaining,x-deeprelay-quota-weekly-output-remaining. When none reads0, the denial is an overshoot (this request is bigger than what is left) or the monthly usage backstop, which has no header. quota_frees_atinsideerror, when present, is when the weekly caps reset (below).
The message is written to be read on its own, by you or by an agent. It
names the window in plain words, with figures in weighted tokens rounded
down (124.9M of 125M weighted input tokens). It states when the window
resets as a UTC time (2026-10-18 00:30 UTC). It links your
dashboard's billing page, where adding credits lets requests continue at
pay-as-you-go list rates, and says what your plan-covered traffic so far
this billing period would have cost at those rates ($2.28 at
pay-as-you-go list rates), read off the same ledger as /v1/requests.
When part of your input was cache reads it says how much, and what the
same traffic would have cost without the cached-input rate: the plan counts
cached input in full, pay-as-you-go bills it at the model's cached rate
(see Prompt caching), so on agent
workloads the pay-as-you-go figure is usually far below what the token
counts suggest. On Base it also offers Plus, with Plus's figure
for the same window; you can upgrade there or with deeprelay billing
upgrade. A model with a usage factor says so. The message is human-readable and its
wording may change: match on param, the error code, the quota headers and
quota_frees_at, never on the text. The billing page in the dashboard
shows the same state: a banner naming the cap, when it resets, and the
same two ways to keep going.
When the gate that tripped is a weekly cap (param: weekly_input_tokens or
param: weekly_output_tokens on the OpenAI envelope), the error object also
carries quota_frees_at: the RFC 3339 time your weekly caps reset and calls
ride the plan again. Both weekly caps reset at the same moment, so it is the
same time as x-deeprelay-quota-weekly-reset. On an input_overshoot or
output_overshoot whose tighter window is the weekly one, it is the same
reset, when a fresh week has room for that request; it is left out when the
request is bigger than the whole cap. The message names the same time. It
sits inside error on both /v1/chat/completions and /v1/messages:
{"error": {"message": "Subscription quota exhausted: you've used 12.5M of 12.5M weighted output tokens in your plan's weekly output cap. This organization has no pay-as-you-go balance to fall back on. Your weekly cap resets at 2026-10-01 10:14 UTC. To keep going now, add credits at https://deeprelay.ai/cloud/billing and requests continue at pay-as-you-go list rates. Or upgrade to Plus (62.5M weighted output tokens a week) on the same page, or with `deeprelay billing upgrade`.",
"type": "insufficient_quota", "param": "weekly_output_tokens",
"code": "subscription_quota_exhausted",
"quota_frees_at": "2026-10-01T10:14:00Z"}}
It can be days away, which is why this 429 has no Retry-After and keeps
x-should-retry: false. Don't auto-retry: wait until quota_frees_at, or
add credits to continue at pay-as-you-go list rates now. Monthly quota,
backstop and monthly-window overshoot denials don't carry the field (their
reset is x-deeprelay-quota-reset, and the message names it).