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
- Create an account. It comes with its own organization, for teammates and budgets later.
- Create an API key under Console → API keys. Keys start with
sk-rh-and are shown once. - 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/echois free for testing. - Send a request to
https://api.routehaven.ai/v1with 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
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"
claudeClaude 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
# ~/.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
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.
Example response:
{
"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.
{
"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.
{
"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 bydata: [DONE]. The usage chunk may precede the error event; when it does, its counts are what was billed. - Anthropic Messages: an
event: errorwhose 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 beforemessage_stop, the gateway sends one witherror.typestream_interrupted. The Anthropic SDKs raise it as an exception. - Responses: a
response.failedevent (the response so far withstatus: "failed"anderror) followed by anerrorevent; when the provider closes the stream beforeresponse.completed, the gateway appends anerrorevent namingstream_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.
Other endpoints
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.
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-routeheader and stored with the request (Activity → request details).requested_modelstaysroutehaven/autoin usage;modelin 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/automay 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.
{
"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 theretry-afterseconds (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 inmodels, 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 isupstream_errororupstream_unavailablecomes 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
modelandproviderreported on the response. A chain stops starting new attempts once 240 s have passed (chain_time_budget_exhaustedin 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_disconnectedin 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_tokensbounded. The worst-case charge is reserved from it before every attempt: a large cap can turn intoinsufficient_balanceor 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:
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 /balancehas its own limit of 120 reads per minute per key, independent of the request limit, and answers 429rate_limit_exceededwithretry-afterbeyond it. Readusage.costfrom each response instead of polling the balance.GET /modelsis 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 carryCache-Control: public, max-age=60, responses with a keyprivate, no-storebecausepermittedandpermission_reasonare per key.GET /keyandGET /generationare 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
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.
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.