Skip to content

Documentation

RouteHaven exposes OpenAI-compatible Chat Completions and Responses endpoints and an Anthropic-compatible Messages endpoint behind one API key. Change the base URL in the SDK you already use; routehaven/auto picks a model per request.

Base URL https://api.routehaven.ai/v1 · Anthropic-format root https://api.routehaven.ai · OpenAPI https://routehaven.ai/api/openapi.json · Interactive API reference

Quickstart

  1. Create an account. It comes with its own organization, for teammates and budgets later.
  2. Create an API key under Console → API keys. Keys start with sk-rh- and are shown once.
  3. Pick a model from the catalog: Platform models are billed to your balance (add credits under Billing); BYOK models need your own provider key under BYOK; sandbox/echo is free for testing.
  4. Send a request to https://api.routehaven.ai/v1 with any of the samples below.
curl https://api.routehaven.ai/v1/chat/completions \
  -H "Authorization: Bearer $ROUTEHAVEN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
  "model": "routehaven/auto",
  "messages": [{"role": "user", "content": "Summarize the last request latency numbers in one sentence."}],
  "stream": true
}'

Authentication

Send the key as a bearer token: Authorization: Bearer sk-rh-…. The Anthropic-format endpoint also accepts x-api-key. Keys are stored only as SHA-256 hashes and can be revoked instantly from the console. Optional X-Title or HTTP-Referer headers label requests in your Activity log.

SDK and tool setup

Every integration uses one RouteHaven key. Replace the model ids with any model from the catalog, or use routehaven/auto.

OpenAI SDKs

Set baseURL / base_url to https://api.routehaven.ai/v1 and apiKey to your RouteHaven key. Chat Completions, Responses and streaming work unchanged. Fallbacks go in the models array (TypeScript) or extra_body (Python).

Anthropic SDKs

Set base_url to https://api.routehaven.ai; the SDK appends /v1/messages. Any catalog model works, not only Claude.

Claude Code

shell
export ANTHROPIC_BASE_URL="https://api.routehaven.ai"
export ANTHROPIC_API_KEY="sk-rh-..."          # sent as x-api-key (ANTHROPIC_AUTH_TOKEN also works)
export ANTHROPIC_MODEL="anthropic/claude-sonnet-5.5"
export ANTHROPIC_SMALL_FAST_MODEL="anthropic/claude-haiku-5.5"
claude

Claude Code calls /v1/messages and /v1/messages/count_tokens relative to the base URL. Sessions appear in Activity; key spend limits and model allow-lists apply as usual.

Codex CLI

config.toml
# ~/.codex/config.toml
model = "openai/gpt-6.1-sol"
model_provider = "routehaven"

[model_providers.routehaven]
name = "RouteHaven"
base_url = "https://api.routehaven.ai/v1"
env_key = "ROUTEHAVEN_API_KEY"   # export ROUTEHAVEN_API_KEY=sk-rh-...
wire_api = "responses"

Cursor

Settings → Models → OpenAI API Key: paste your RouteHaven key, enable Override OpenAI Base URL and set it to https://api.routehaven.ai/v1, then add the model ids you want (for example anthropic/claude-sonnet-5.5, routehaven/auto) as custom model names. Cursor uses the Chat Completions format.

Vercel AI SDK

route.ts
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
import { streamText } from "ai";

const routehaven = createOpenAICompatible({ name: "routehaven", baseURL: "https://api.routehaven.ai/v1", apiKey: process.env.ROUTEHAVEN_API_KEY! });

const result = streamText({ model: routehaven("routehaven/auto"), prompt: "Summarize this ticket: ..." });
for await (const part of result.textStream) process.stdout.write(part);

LangChain

import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="anthropic/claude-sonnet-5.5", base_url="https://api.routehaven.ai/v1", api_key=os.environ["ROUTEHAVEN_API_KEY"])
print(llm.invoke("Explain vector clocks in two sentences.").content)

Browser-side use is possible (CORS allows the SDK headers), but keep keys on the server in production.

Chat Completions

POST https://api.routehaven.ai/v1/chat/completions accepts the OpenAI Chat Completions body.

FieldNotes
modelRequired. A model id such as openai/gpt-6.1-sol, or routehaven/auto. See GET /models.
modelsOptional ordered list of fallback model ids (at most 8 including model).
messagessystem, developer, user (text and image_url parts, see Image input), assistant (with tool_calls), tool (with tool_call_id).
streamServer-sent events in the OpenAI chunk format, terminated by data: [DONE]. See Streaming for the usage chunk and how a failed stream ends.
max_tokens / max_completion_tokensOutput cap. Anthropic requires one; RouteHaven applies a default if omitted and may lower it to fit your available balance (x-max-tokens-capped). The worst-case charge is reserved from it, so keep it bounded.
temperature, top_p, stop, seed, presence_penalty, frequency_penaltyForwarded when the target model accepts them; removed for endpoints that reject sampling parameters.
tools, tool_choice, parallel_tool_callsOpenAI function-calling format, converted for other providers. See Tool calling.
response_formatjson_object, or json_schema with name, schema and strict (see Structured outputs); honoured where the model supports it.
reasoning_effortMapped to the provider's effort or thinking control where available.
providerRouting preferences: order, only, ignore, allow_fallbacks, sort.
userEnd-user identifier forwarded to the provider for abuse monitoring.

Example response:

200 OK
{
  "id": "gen-2xYq…",
  "object": "chat.completion",
  "model": "anthropic/claude-sonnet-5.5",
  "provider": "anthropic",
  "choices": [{ "index": 0, "message": { "role": "assistant", "content": "…" }, "finish_reason": "stop" }],
  "usage": { "prompt_tokens": 21, "completion_tokens": 118, "total_tokens": 139,
             "prompt_tokens_details": { "cached_tokens": 0 }, "cost": 0.000035 }
}

Structured outputs

Ask for JSON that matches a schema with response_format. { "type": "json_object" } requests any valid JSON object; json_schema with strict: true constrains the output to your schema.

request body
{
  "model": "openai/gpt-6.1-sol",
  "messages": [{"role": "user", "content": "Extract the invoice number and total: Invoice 2026-0412, total EUR 1,240.00"}],
  "response_format": {
    "type": "json_schema",
    "json_schema": {
      "name": "invoice",
      "strict": true,
      "schema": {
        "type": "object",
        "properties": {
          "invoice_number": {"type": "string"},
          "total": {"type": "number"},
          "currency": {"type": "string"}
        },
        "required": ["invoice_number", "total", "currency"],
        "additionalProperties": false
      }
    }
  }
}

// choices[0].message.content → {"invoice_number":"2026-0412","total":1240,"currency":"EUR"}

The format is forwarded to the provider and converted where it has its own syntax. Whether a model honours json_schema and strict depends on the model: check supported_parameters for the model in GET /models, and validate the parsed output in your code, because a model without schema support may answer with free text or a schema-shaped answer that is not exact. Keep schemas small, name the expected fields in the prompt as well, and remember that routehaven/auto treats structured output as a hard requirement when it chooses a model.

Image input

Send images as image_url content parts next to text. The URL can be an https address the provider fetches, or a data: URL with the bytes inline (base64); parts are converted to the provider's format where needed.

request body
{
  "model": "google/gemini-3.8-flash",
  "messages": [{
    "role": "user",
    "content": [
      {"type": "text", "text": "What is the total on this receipt?"},
      {"type": "image_url", "image_url": {"url": "https://example.com/receipt.jpg"}},
      {"type": "image_url", "image_url": {"url": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA…"}}
    ]
  }]
}

Only models whose architecture.input_modalities includes image in GET /models accept image parts (the catalog's Image input filter lists them), and routehaven/auto only considers those models when a request contains an image. Images count toward the prompt tokens the provider reports.

Streaming

Set "stream": true. Chat Completions sends chat.completion.chunk objects as data: lines; a final chunk with an empty choices array carries usage including cost, and data: [DONE] ends the stream. The Responses and Messages endpoints stream their native events (response.*, and message_start … message_stop with usage in message_delta).

How a stream ends on failure

Failover between models, endpoints and credentials happens before the first byte is sent. Once a stream has started the HTTP status is already 200, so a failure is reported inside the stream. When the provider reports an error or closes its stream before its terminal event, the stream ends with an explicit error:

  • Chat Completions: data: {"error":{"message":"…","type":"upstream_error","code":"stream_interrupted","request_id":"gen-…"}} followed by data: [DONE]. The usage chunk may precede the error event; when it does, its counts are what was billed.
  • Anthropic Messages: an event: error whose data has the same shape as a non-streaming error, {"type":"error","error":{"type":"…","message":"…"}}. Provider error events are forwarded unchanged; when the provider closes the stream before message_stop, the gateway sends one with error.type stream_interrupted. The Anthropic SDKs raise it as an exception.
  • Responses: a response.failed event (the response so far with status: "failed" and error) followed by an error event; when the provider closes the stream before response.completed, the gateway appends an error event naming stream_interrupted.

When the connection to the provider breaks mid-stream, or the stream reaches the gateway's time limit (285 s by default), the response ends without its terminal event ([DONE], message_stop or response.completed) and your client sees a connection error; treat that as interrupted as well. In both cases billing covers only the tokens generated before the failure, the request appears in Activity with code stream_interrupted, and the stream cannot be resumed: retry as a new request, and keep max_tokens bounded so generations finish within the limit.

data: {"id":"gen-7f3a…","object":"chat.completion.chunk","created":1762500000,"model":"anthropic/claude-sonnet-5.5","provider":"anthropic","choices":[{"index":0,"delta":{"role":"assistant","content":"Median latency"},"finish_reason":null}]}

data: {"id":"gen-7f3a…","object":"chat.completion.chunk","created":1762500000,"model":"anthropic/claude-sonnet-5.5","provider":"anthropic","choices":[{"index":0,"delta":{"content":" was 412 ms"},"finish_reason":null}]}

data: {"id":"gen-7f3a…","object":"chat.completion.chunk","created":1762500001,"model":"anthropic/claude-sonnet-5.5","provider":"anthropic","choices":[],"usage":{"prompt_tokens":21,"completion_tokens":7,"total_tokens":28,"prompt_tokens_details":{"cached_tokens":0},"cost":0.000168}}

data: {"error":{"message":"The provider closed the stream before its terminal event.","type":"upstream_error","code":"stream_interrupted","request_id":"gen-7f3a…"}}

data: [DONE]

The usage chunk reports what was billed for the partial answer; the error event is the last JSON before [DONE].

The OpenAI SDKs yield the usage chunk like any other chunk and raise the error event as APIError, with code and request_id taken from the event; a dropped connection surfaces as APIConnectionError, a subclass of APIError. The raw sample shows the framing to parse yourself.

import os
from openai import OpenAI, APIError

client = OpenAI(base_url="https://api.routehaven.ai/v1", api_key=os.environ["ROUTEHAVEN_API_KEY"])

try:
    stream = client.chat.completions.create(
        model="routehaven/auto",
        messages=[{"role": "user", "content": "Summarize the last request latency numbers in one sentence."}],
        stream=True,
    )
    for chunk in stream:
        if chunk.usage:  # final chunk: empty choices, token counts and the charged cost (USD)
            print(f"\n{chunk.usage.completion_tokens} output tokens, cost {getattr(chunk.usage, 'cost', None)}")
        elif chunk.choices:
            print(chunk.choices[0].delta.content or "", end="", flush=True)
except APIError as e:
    # Either the stream ended with an error event ({"error": {"code": "stream_interrupted", "request_id": "gen-…", …}})
    # or the connection dropped before [DONE] (APIConnectionError). Tokens streamed before the failure were billed;
    # a retry is a new request.
    body = e.body if isinstance(e.body, dict) else {}
    print(f"\nstream failed: {e.code} (request {body.get('request_id')})")

Tool calling

Declare functions in tools (OpenAI format, converted for other providers). When the model wants to call one, the assistant message carries tool_calls and finish_reason is tool_calls. Run the function yourself and send the result back as a tool message whose tool_call_id matches the call, keeping the assistant message and its ids unchanged, then call again for the answer:

import json
import os
from openai import OpenAI

client = OpenAI(base_url="https://api.routehaven.ai/v1", api_key=os.environ["ROUTEHAVEN_API_KEY"])

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Current weather for a city",
        "parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
    },
}]
messages = [{"role": "user", "content": "What is the weather in Paris?"}]

# Turn 1: the model asks for a tool call (finish_reason "tool_calls").
first = client.chat.completions.create(model="google/gemini-3.8-flash", messages=messages, tools=tools)
call = first.choices[0].message.tool_calls[0]
args = json.loads(call.function.arguments)  # {"city": "Paris"}

# Run the tool yourself, then return its result with the same tool_call_id.
result = {"city": args["city"], "temperature_c": 18, "sky": "overcast"}
messages.append(first.choices[0].message)  # keep the assistant turn; tool-call ids unchanged
messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps(result)})

# Turn 2: the model answers with the result.
second = client.chat.completions.create(model="google/gemini-3.8-flash", messages=messages, tools=tools)
print(second.choices[0].message.content)

tool_choice accepts auto, none, required or a named function. Some models do not accept a forced choice; for those RouteHaven downgrades required or a named tool to auto. Models without tool support reject requests that include tools (tools_not_supported), and automatic routing skips them. In streams, tool calls arrive as delta.tool_calls fragments whose arguments are partial JSON strings to concatenate per index. sandbox/echo emits a tool call when tools are supplied and the message mentions a tool, so the round trip can be tested for free.

Responses API

POST https://api.routehaven.ai/v1/responses keeps native input items, provider-supported tools, reasoning, response ids and streaming events. previous_response_id must reference a response created by your organization, and the next turn is served by the same provider channel. Stored history and built-in tools depend on the provider and model. Background responses and WebSocket connections are not available.

Read the request's cost and status through x-routehaven-generation-id and GET /generation?id=…; non-streaming responses also carry x-routehaven-cost-usd.

Anthropic Messages

POST https://api.routehaven.ai/v1/messages accepts the Anthropic Messages body and returns Anthropic-shaped messages, streaming events and errors, through the same pipeline (limits, holds, routing, billing). Any catalog model can be addressed, including routehaven/auto.

SupportedNotes
system, messages, max_tokens, thinking, output_configNative fields are retained for compatible providers and models.
Content blocks, thinking / signature history, cache_controlSent natively. Cross-provider conversion depends on the selected model.
Function and provider-side toolsAvailability depends on provider and model. Sandbox supports function tools only.
temperature, top_p, top_k, stop_sequences, metadata, streamProvider compatibility rules still apply.
POST /v1/messages/count_tokensReturns an estimate without calling a provider; never billed.
models (fallbacks), provider (preferences)RouteHaven extensions, same semantics as Chat Completions.

Other endpoints

GET /modelsPublic catalog with pricing, context, modalities, supported parameters and access type; with a key each entry also reports permitted and permission_reason for that key. The list is shared for 60 s (see Rate limits).
GET /keyThe calling key: label, prefix, usage, limit, rate limit, allowed models, expiry and organization balance.
GET /balanceAvailable balance (balance + credit line − holds), month-to-date spend and the key's and team's remaining budgets. Limited to 120 reads per minute per key.
GET /generation?id=Tokens, cost, latency, status and the attempt chain for one request id of your organization (the attempt markers are explained under Errors).
POST /messages/count_tokensToken estimate for an Anthropic-format request; never billed.

All paths are relative to https://api.routehaven.ai/v1. The OpenAPI 3.1 document at https://routehaven.ai/api/openapi.json describes everything on this page; the interactive reference renders it with every schema and lets you send requests.

Automatic routing

Use routehaven/auto as the model and the gateway chooses one per request. The request is classified from its own content (task type, complexity, and hard requirements such as tools, images, structured output and prompt size), then every model your organization can actually use is scored on capability tier, the expected cost of this request, and measured 24-hour latency and reliability. The winner plus two fallbacks (preferring a different vendor) become the attempt chain.

ModelOptimizes for
routehaven/autoCheapest model that is capable enough (balanced).
routehaven/auto:fastLowest latency and cost; accepts one tier lower than balanced.
routehaven/auto:bestHighest capability tier available to you, vendor-diverse fallbacks.
shell
curl https://api.routehaven.ai/v1/chat/completions -H "Authorization: Bearer $ROUTEHAVEN_API_KEY" -H "Content-Type: application/json" -d '{
  "model": "routehaven/auto",
  "messages": [{"role": "user", "content": "Refactor this function and add tests: ..."}]
}'
# → x-routehaven-route: balanced; task=coding; complexity=2; chosen=anthropic/claude-sonnet-5.5; fallbacks=openai/gpt-6.1-sol,google/gemini-3.8-flash
  • The decision is returned in the x-routehaven-route header and stored with the request (Activity → request details). requested_model stays routehaven/auto in usage; model in the response is the model that answered, billed at its own price.
  • Automatic routing never widens access: key allow-lists and the organization model policy apply to the candidates. A key allowed only routehaven/auto may use any model the organization can use.
  • Capability tiers (1 economy … 5 frontier) are a judgement about class, not a benchmark. Validate on your own prompts, for example with compare mode in the Workspace.

Failover and provider preferences

For each request RouteHaven builds an ordered list of attempts: every model in [model, ...models], every active endpoint for that model, and every credential you hold for that provider. It moves to the next attempt on HTTP 401/403 (bad key), 404, 408, 429, 5xx, timeouts and network errors. Validation errors (400/422) are returned immediately.

request body
{
  "model": "sandbox/unavailable",
  "models": ["anthropic/claude-haiku-5.5", "sandbox/echo"],
  "provider": { "order": ["anthropic"], "allow_fallbacks": true, "sort": "latency" },
  "messages": [{"role": "user", "content": "hi"}]
}

Endpoints whose circuit breaker is open (repeated 5xx/429/timeouts in the last minutes) are tried last. provider.sort accepts price, latency (measured time to first token) and throughput (measured output tokens per second). Set provider.allow_fallbacks to false to pin the first choice.

Retries and idempotency

  • 429 rate_limit_exceeded: wait the retry-after seconds (the window is one minute), then retry. Nothing was charged.
  • 5xx (upstream_error, upstream_unavailable, no_available_provider, billing_unavailable, server_error): nothing was charged. The gateway has already tried every fallback in models, every endpoint and every credential it could, so retry with exponential backoff and jitter rather than immediately, and add a fallback from another vendor if you have none. A 429 whose code is upstream_error or upstream_unavailable comes from the provider (every attempt was rate limited upstream), not from your key.
  • Failover never double-bills. The balance reserved for an attempt that fails before producing output is released; only the attempt that produces the response is metered, and it is the model and provider reported on the response. A chain stops starting new attempts once 240 s have passed (chain_time_budget_exhausted in the attempt list) and returns the last real error.
  • A client retry is a new request. There is no idempotency key. If your client times out or aborts a non-streaming request, the attempt is cancelled and nothing is charged (client_disconnected in Activity); an aborted or interrupted stream is billed for the tokens generated so far. The retry gets its own request id and charge, so set client timeouts above the expected generation time, stream long outputs, and reconcile duplicates by request id in Activity.
  • Keep max_tokens bounded. The worst-case charge is reserved from it before every attempt: a large cap can turn into insufficient_balance or a lowered cap (x-max-tokens-capped), and a bounded cap limits what any retry can cost.
  • Do not retry other 4xx errors. Validation, permission and billing errors return the same answer until the request or the account changes.

Platform models and BYOK

Models marked Platform in the catalog are served with RouteHaven's provider agreements and billed to your organization balance at the provider list price plus your plan's platform fee. Models marked BYOK need a provider key you add under Console → BYOK; the provider then bills you directly and RouteHaven charges only its BYOK service fee (see Pricing), from your prepaid balance. A request for a BYOK model without a usable credential returns byok_required.

Provider keys are encrypted with AES-256-GCM, bound to your organization, and only their last four characters are ever displayed. When you hold several keys for a provider they are tried in priority order; a key that fails with 401/403 is marked and skipped.

Keys, budgets and policies

  • Per-key rate limit (requests per minute), defaulting to your plan; see Rate limits for the headers and the separate limits on reads.
  • Per-key spend cap, optional model allow-list and expiry date.
  • Organization model policy (allow and deny lists) set in the Control Center; deny always wins and key allow-lists can only narrow it. Blocked requests return 403 model_not_allowed.
  • Organization monthly spend limit and team monthly budgets, checked before every request (402 when reached).
  • Prepaid balance: the worst-case charge is reserved before the call and released when the response settles. Requests that cannot be covered return 402 insufficient_balance, or run with a lowered output cap (x-max-tokens-capped).

Rate limits

Each key has a requests-per-minute limit, set on the key and defaulting to your plan, that applies to Chat Completions, Responses and Messages requests and is counted in fixed one-minute windows. Every response to those requests reports the state:

HeaderMeaning
x-ratelimit-limitThe key's requests-per-minute limit.
x-ratelimit-remainingRequests left in the current window.
x-ratelimit-resetUnix timestamp (seconds) at which the window ends.
retry-afterOnly on 429: seconds to wait before retrying.

Over the limit, the request is refused with 429 rate_limit_exceeded before any routing or provider work, nothing is charged, and the body carries request_id like every error. Requests are not queued; wait retry-after seconds and send again.

  • GET /balance has its own limit of 120 reads per minute per key, independent of the request limit, and answers 429 rate_limit_exceeded with retry-after beyond it. Read usage.cost from each response instead of polling the balance.
  • GET /models is not counted against the key limit. The list is shared across all callers for 60 s, so catalog changes appear within a minute; anonymous responses carry Cache-Control: public, max-age=60, responses with a key private, no-store because permitted and permission_reason are per key.
  • GET /key and GET /generation are not counted against the key limit either.

Usage and cost

Tokens come from the provider's usage report. If a provider omits usage (for example on an interrupted stream), RouteHaven estimates it and flags the record usage_estimated. Cost is computed from the list price per 1M tokens for uncached prompt, cached prompt and completion tokens, plus the applicable fee; conditional provider rates (long context, time of day, cache writes) are applied at request time. Every request is visible in Activity and exportable as CSV, and queryable through GET /generation.

Prompt caching

Providers with a cached-input price bill repeated prompt prefixes at a fraction of the input price. RouteHaven forwards each provider's caching behaviour unchanged and reports cache reads per request as usage.prompt_tokens_details.cached_tokens (cache_read_input_tokens on the Anthropic endpoint); charges use the cached price for those tokens.

  • Put the stable part first: system prompt, tool definitions, reference documents, then the changing user turn.
  • Keep the prefix byte-identical between requests; any change before the cached region invalidates it.
  • The Cost Optimizer shows your cache hit rate per model and what a higher rate would have saved on your own traffic.

Response headers

HeaderMeaning
x-request-idRouteHaven request id (gen-…), also returned as request_id in every error body. Use it with GET /generation, in Activity and when writing to support.
x-routehaven-generation-idSame id on relayed Responses / Messages requests.
x-routehaven-routeAutomatic routing decision: mode, task, complexity, chosen model and fallbacks.
x-routehaven-cost-usdCharged amount in USD on non-streaming responses; streaming responses carry usage.cost in the final chunk.
x-max-tokens-cappedPresent when the output cap was lowered to fit your available balance; value is the cap used.
x-ratelimit-limit / -remaining / -resetThe key's requests-per-minute limit, requests left in the current one-minute window, and the window's end as a Unix timestamp (seconds). On every model request.
retry-afterSeconds to wait, on 429 responses (the key's limit and GET /balance).
cache-controlGET /models: public, max-age=60 without a key (the list is shared for 60 s); private, no-store with a key, because permitted / permission_reason are per key.

Errors

Chat Completions and Responses return the OpenAI shape; the Messages endpoint returns the Anthropic shape with the same codes. Every error body carries request_id, equal to the x-request-id header: quote it when writing to support, and use it with GET /generation and in Activity. Codes are stable; messages may change.

HTTP/1.1 402 Payment Required
content-type: application/json
x-request-id: gen-7f3a…

{
  "error": {
    "message": "Insufficient balance. Add credits under Billing to continue.",
    "type": "insufficient_balance",
    "code": "insufficient_balance",
    "request_id": "gen-7f3a…"
  }
}

Attempts

The attempt chain of every request (model, provider, credential source, status, error, latency) is stored and returned by GET /generation; errors that end a chain may also include it as error.attempts. Two markers need explaining. chain_time_budget_exhausted means a fallback was skipped because the whole chain had reached its time budget (240 s by default), so the last real error was returned instead of starting another attempt. An entry with status: null and an error of the form code: message is a provider setup failure (a channel or credential problem) recorded before any provider was called, after which the next credential or provider was tried. Setup failures and skipped candidates do not count against a provider's health statistics.

HTTPcodeMeaning and what to do
400invalid_request_errorMalformed body or unsupported parameter. Fix the request; nothing was charged.
400byok_requiredThe model needs your own provider key. Add one under BYOK, or pick a Platform model.
400tools_not_supportedThe model cannot take tools. Remove them or choose a model with tool support.
400no_auto_candidatesAutomatic routing found no usable model for this request's requirements and your policy.
401authentication_errorMissing, invalid, revoked or expired key.
402insufficient_balanceAvailable balance (balance + credit line − holds) cannot cover the worst-case charge. Add credits, or lower max_tokens.
402key_spend_limit_exceededThis key reached its spend cap. Raise it or use another key.
402org_monthly_limit_exceededThe organization monthly limit was reached.
402team_monthly_limit_exceededThe key's team reached its monthly budget.
403billing_country_requiredThe organization has no billing country yet. Set it in the console (Overview); until then every model request (chat completions, messages, messages/count_tokens, responses) is declined, including the free sandbox. GET /models, /key, /balance and /generation still answer.
403model_not_allowedBlocked by the organization model policy or the key's allow-list.
403permission_errorThe organization is suspended, or the caller's role cannot do this.
403region_not_supportedRouteHaven is not available in the caller's region.
404model_not_foundUnknown model id. Check GET /models.
404not_foundThe referenced resource (for example previous_response_id) is not yours or does not exist.
409previous_response_unavailableThe previous response's provider channel is no longer available; start a new conversation.
429rate_limit_exceededThe key's requests-per-minute limit, or the separate 120 reads per minute on GET /balance. Wait retry-after seconds; nothing was charged.
499client_disconnectedYou closed the connection before the response finished. A non-streaming request is cancelled and not charged; a stream is billed for the tokens generated so far. A retry is a new request.
502upstream_errorEvery attempt failed at the provider (error responses, timeouts, 5xx or 429 upstream); a provider's own 4xx rejection is returned with its status and not retried. GET /generation lists the attempts; retry with backoff or add fallbacks in models.
502upstream_unavailableEvery attempt failed with a retryable provider error (timeouts, 5xx, 429); see error.attempts. Same handling as upstream_error.
200stream_interruptedThe provider failed after the stream had started (the HTTP status was already 200): sent as the last event when the provider reports an error or closes early; a stream that ends without its terminal event means the same. Tokens generated before the failure are billed. Retry as a new request.
503no_available_providerNo active endpoint could serve the request.
503billing_unavailableBalance could not be reserved; nothing was charged. Retry shortly.
500server_errorUnexpected failure inside RouteHaven; nothing was charged. Quote request_id to support.

Sandbox models

sandbox/echo and sandbox/unavailable never call a provider and are never billed. echo repeats your last message, streams word by word and emits a tool call when tools are supplied and the message mentions a tool. unavailable always fails with 503 so you can test failover.

Found something inaccurate? The behaviour documented here is covered by the gateway's integration tests; tell us and we will fix the page or the test.
Documentation · RouteHaven