Documentation

Build against one endpoint

Everything you need to call every model through HanlinRouter — protocol compatibility, routing, billing and agent setup.

Overview

HanlinRouter is an AI API gateway. You call one endpoint with one API key; we route the request to the selected model provider, meter the tokens it reports, charge your balance and return the answer in the same protocol you sent it in.

OpenAI-compatible

https://hanlinrouter.site/v1

Anthropic-compatible

https://hanlinrouter.site/api

Gemini-compatible

https://hanlinrouter.site/v1beta

Quick start

  1. Create an account and an API key in Dashboard → API Keys.
  2. Add balance in Billing (minimum $5).
  3. Point your SDK at the gateway and send a request.
terminal
export HANLIN_API_KEY="hr_live_..."

curl https://hanlinrouter.site/v1/chat/completions \
  -H "Authorization: Bearer $HANLIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.1",
    "messages": [{"role": "user", "content": "Say hello in one sentence."}]
  }'

Authentication

Every request needs a key. Send it as Authorization: Bearer hr_live_…, as x-api-key (Anthropic style), or as ?key= for Gemini-compatible calls. Keys are stored as HMAC-SHA256 hashes and can be revoked at any time.

  • Scoped by spend limit, model allowlist, IP allowlist and expiry.
  • Requests that fail authentication return HTTP 401 and never reach a provider.
  • Never ship a key in a browser bundle — proxy requests from your backend.

OpenAI compatibility

Base URL https://hanlinrouter.site/v1. Works with the official OpenAI SDKs, LangChain, Vercel AI SDK and any OpenAI-compatible client. Supported endpoints: POST /v1/chat/completions, GET /v1/models, GET /v1/models/{id}.

python
from openai import OpenAI

client = OpenAI(api_key=0, base_url=1)

response = client.chat.completions.create(
    model=2,
    messages=[{3: 4, 5: 6}],
)
print(response.choices[0].message.content)

Streaming usage: the final chunk contains a usage object (we always request stream_options.include_usage upstream), so accurate token accounting works for streams too.

Anthropic compatibility

Point the Anthropic SDK or Claude Code at https://hanlinrouter.site (calls /v1/messages) or https://hanlinrouter.site/api. Supported: POST /v1/messages, streaming events, tool_use blocks and POST /v1/messages/count_tokens.

python
import anthropic

client = anthropic.Anthropic(
    api_key=0,
    base_url=1,
)

message = client.messages.create(
    model=2,
    max_tokens=1024,
    messages=[{3: 4, 5: 6}],
)
print(message.content[0].text)

Gemini compatibility

Base URL https://hanlinrouter.site/v1beta. Supports generateContent and streamGenerateContent with ?alt=sse, and GET /v1beta/models.

gemini.sh
curl "https://hanlinrouter.site/v1beta/models/gemini-2.5-flash:generateContent" \
  -H "x-goog-api-key: $HANLIN_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"contents":[{"parts":[{"text":"Summarize CAP theorem"}]}]}'

Streaming

Set "stream": true for OpenAI and Anthropic protocols. The gateway proxies upstream SSE without buffering and emits the same event shape your SDK expects. Cross-protocol streams are translated event-by-event (for example an Anthropic stream rendered as OpenAI chunks).

If the client disconnects mid-stream, the request is still billed for the tokens that were generated before the disconnect.

Tool calling

Tool definitions and tool results are translated between OpenAI tools / tool_calls and Anthropic tool_use / tool_result blocks. That means a Claude-format agent can fall back to a GPT model and keep its tool loop intact.

openai request
{
  "model": "auto",
  "messages": [{"role": "user", "content": "What's the weather in Berlin?"}],
  "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"
}

Smart routing

Send "model": "auto" and the router scores every eligible model by quality, latency and blended cost, filtered by context window, tool support and vision. Bias the decision with the X-Hanlin-Router-Mode header: cost, speed, quality or balanced (default).

Every response tells you what happened: x-hanlin-model, x-hanlin-provider, x-hanlin-cost-usd and, when a retry occurred, x-hanlin-fallback-from.

Automatic fallback

If a provider returns 408, 429 or 5xx (or the connection fails), the gateway retries on the next eligible model — preferring a different provider — up to FALLBACK_MAX_ATTEMPTS (default 2 total attempts). Fallbacks never happen after bytes have been sent to a streaming client, so responses are never duplicated.

Models and pricing

GET /v1/models returns the live catalog with context windows and prices in the hanlin object. Prices are per 1M tokens in USD. Cached input tokens are billed at the cache-read rate and reported in prompt_tokens_details.cached_tokens (OpenAI) or cache_read_input_tokens (Anthropic).

Browse the full list in Models or in the dashboard.

Rate limits and quotas

Default limits: 120 requests/minute and 200,000 tokens/minute per API key, configurable by an administrator. Rate-limit responses include retry-after and x-ratelimit-* headers.

Independent of rate limits, requests are refused with HTTP 402 when your balance cannot cover the estimated cost, and with HTTP 429 when a daily, monthly or per-key spending cap is reached.

Errors

Gateway errors use the envelope of the protocol you called. OpenAI-style clients receive {"error": {"message", "type", "code"}}; Anthropic-style clients receive {"type": "error", "error": {…}}.

StatusCodeMeaning
401invalid_api_keyKey missing, revoked or unknown
402insufficient_quotaBalance cannot cover the request
403model_not_allowed / ip_not_allowedKey restrictions
404model_not_foundUnknown model id
429rate_limit_exceededRPM/TPM or spend limit exceeded
502provider_unavailableAll fallbacks failed
503provider_not_configuredNo upstream key configured for the provider

Claude Code

Set two environment variables and run Claude Code as usual:

terminal
export ANTHROPIC_BASE_URL="https://hanlinrouter.site"
export ANTHROPIC_AUTH_TOKEN="hr_live_..."
export ANTHROPIC_MODEL="claude-sonnet-4-5"
export ANTHROPIC_SMALL_FAST_MODEL="claude-haiku-4-5"

claude

Use a dedicated key with a spend limit — coding agents can generate a lot of tokens. Streaming, tool use and prompt caching are supported.

Codex CLI

Codex supports custom OpenAI providers. Add a provider pointing at the gateway:

~/.codex/config.toml
model_provider = "hanlin"
model = "gpt-5.1-codex"

[model_providers.hanlin]
name = "HanlinRouter"
base_url = "https://hanlinrouter.site/v1"
env_key = "HANLIN_API_KEY"
wire_api = "chat"

Cursor, Cline and Continue

These tools accept an OpenAI-compatible base URL: set it to https://hanlinrouter.site/v1, the API key to your hr_live_… key, and pick any model id from the catalog. For Anthropic-style integrations use https://hanlinrouter.site.

Billing

Balance is prepaid USD credit. Each request is charged after its usage is known — for streams, when the stream ends. Charges are recorded to the micro-dollar in Transactions alongside the matching request log.

Card payments are processed by YooKassa and credited only after the provider confirms settlement. Manual invoices are confirmed by an administrator. There is no overdraft: at zero balance requests stop.

Security

Provider keys are encrypted at rest with AES-256-GCM, password hashes use scrypt with per-password salts, sessions are opaque server-side tokens in httpOnly cookies, and every mutating endpoint validates the origin. Administrative routes are protected by role checks on the server.

Documentation · HanlinRouter