Skip to content

Latest commit

 

History

History
203 lines (165 loc) · 9.77 KB

API.md

File metadata and controls

203 lines (165 loc) · 9.77 KB

Gateway API reference

Base URL: http://127.0.0.1:20125

All /v1/* endpoints require a gateway API key. Both header styles are accepted:

Authorization: Bearer okr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
x-api-key: okr-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

Only Bearer is accepted in Authorization; any other scheme (Basic …) is treated as no credential and rejected with 401 missing_api_key.

Response headers:

Header Set on Meaning
x-opencode-router-request-id every /v1/* response gateway request id (same id as in the Logs tab)
x-opencode-router-provider proxied/failed-attempt responses id of the provider that served (or failed) the request
x-opencode-router-name proxied/failed-attempt responses display name of that provider
x-opencode-router-attempts proxied/failed-attempt responses number of upstream attempts (1 = first provider worked)
retry-after 429 all_providers_rate_limited seconds to wait before retrying (min 1)
x-opencode-router-cooldown-until 429 all_providers_rate_limited epoch milliseconds when the smallest provider cooldown expires

Errors raised before an upstream attempt (auth, routing, validation) carry x-opencode-router-request-id only.

Upstream response headers are relayed to the client: retry-after, request-id, x-request-id, openai-processing-ms, openai-version, anthropic-version, x-ratelimit-*, anthropic-ratelimit-* and x-stainless-*. Router headers, content-type and content-length win, and content-encoding is never forwarded.

Error envelope follows the client surface: OpenAI style {"error":{"message","type","param","code"}} for chat/responses, Anthropic style {"type":"error","error":{"type","message"}} for messages.

HTTP code Meaning
401 missing_api_key no Authorization: Bearer/x-api-key header (non-Bearer schemes count as missing)
401 no_api_key_configured no gateway key exists yet → create one in the dashboard
401 invalid_api_key unknown, disabled or revoked key
400 model_required request body has no model
404 model_not_found model missing/disabled in the registry
404 unknown_endpoint authenticated request to an unknown /v1/* path
405 method_not_allowed known /v1/* path called with an unsupported method (carries Allow)
413 payload_too_large request body exceeds BODY_LIMIT
503 no_provider_configured no enabled provider
503 no_models_configured model registry empty
429 all_providers_rate_limited every attempt hit a rate limit (carries Retry-After)
502 all_providers_failed every attempt failed (network/5xx)
502 upstream_body_failed a 2xx upstream body could not be read (truncated/RST)
502 upstream_frame_too_large an unterminated SSE frame exceeded the 1 MiB cap
502 upstream_response_too_large a buffered response exceeded upstream_response_max_bytes
502 invalid_provider_credentials the stored provider key cannot be encoded as an HTTP header value
504 upstream_timeout every candidate timed out (aggregated after exhaustion)

The router retries the next provider for 408, 409, 425, 429, every 5xx (incl. 529) and network/timeout errors, up to the configured retry budget (Dashboard → Settings → Routing). A timed-out attempt is logged, cools its provider down and fails over like any other retryable failure; the 504 upstream_timeout is only returned after all candidates are exhausted. Client errors (400/401/403/404/422) are returned immediately without burning other providers.

Unknown /v1/* paths (and bare /v1) require a valid gateway key, are logged as one request_logs row and answer 404 with code unknown_endpoint in the surface-appropriate error envelope. A known path called with an unsupported method answers 405 with an Allow header listing the supported methods (also one log row).

Upstream requests

Request bodies are forwarded byte-for-byte from the raw client bytes (invalid UTF-8 included); a JSON body is only re-serialized when reasoning normalization, model-id trimming or the stream_options.include_usage injection actually changed it. The client's raw query string is forwarded unchanged (?beta=true stays on the upstream request), and a provider baseUrl that already carries a query string keeps it. Provider credentials (Authorization, x-api-key), host, content-length and connection always come from the router, while the client's anthropic-beta, anthropic-version, anthropic-dangerous-direct-browser-access, openai-beta, openai-organization, openai-project, http-referer, x-title, x-stainless-*, accept and trace headers are forwarded through an allowlist. anthropic-version: 2023-06-01 is only defaulted for the messages/count_tokens surfaces, and a streaming request without an accept header is forwarded as text/event-stream. Upstream redirects are refused (redirect: 'manual'): a 3xx response is a fatal upstream error instead of being followed with the provider key.


POST /v1/chat/completions

OpenAI Chat Completions, forwarded to {provider}/chat/completions.

curl http://127.0.0.1:20125/v1/chat/completions \
  -H "Authorization: Bearer okr-..." -H 'content-type: application/json' \
  -d '{
    "model": "opencode/flint-40b-free",
    "messages": [
      {"role": "system", "content": "You are terse."},
      {"role": "user", "content": [
        {"type": "text", "text": "What is in this image?"},
        {"type": "image_url", "image_url": {"url": "data:image/png;base64,..."}}
      ]}
    ],
    "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",
    "reasoning_effort": "high",
    "stream": true
  }'
  • reasoning_effort: none | minimal | low | medium | high | xhigh | max, normalized to the closest effort the selected model supports. Removed automatically for non-reasoning models.
  • Streaming: the gateway injects stream_options.include_usage = true when absent, so token usage is always visible to clients and recorded in the Logs tab.

POST /v1/responses

OpenAI Responses API, forwarded to {provider}/responses.

curl http://127.0.0.1:20125/v1/responses \
  -H "Authorization: Bearer okr-..." -H 'content-type: application/json' \
  -d '{"model":"opencode/flint-40b-free","input":"Summarize SSE in one line.",
       "reasoning":{"effort":"low"},"stream":false}'

POST /v1/messages

Anthropic Messages API, forwarded to {provider}/messages.

curl http://127.0.0.1:20125/v1/messages \
  -H "x-api-key: okr-..." -H "anthropic-version: 2023-06-01" -H 'content-type: application/json' \
  -d '{
    "model": "opencode/flint-40b-free",
    "max_tokens": 1024,
    "thinking": {"type": "enabled", "budget_tokens": 4096},
    "tools": [{"name": "get_weather", "description": "Weather", "input_schema": {"type": "object", "properties": {"city": {"type": "string"}}}}],
    "stream": true,
    "messages": [{"role": "user", "content": "Weather in Hanoi?"}]
  }'

POST /v1/messages/count_tokens

Pass-through to the provider's token counter. Returns {"input_tokens": <number>}.

GET /v1/models

Lists the enabled models from the registry in OpenAI format, enriched with capability + reasoning metadata:

{
  "object": "list",
  "data": [
    {
      "id": "opencode/flint-40b-free",
      "object": "model",
      "created": 1792540800,
      "owned_by": "opencode-router",
      "name": "Flint 40B Free",
      "context_length": 262144,
      "max_output_tokens": 65536,
      "capabilities": {"tools": true, "input": ["text"], "output": ["text"], "temperature": true},
      "reasoning": {"supported": true, "efforts": ["low", "medium", "high", "xhigh", "max"], "default_effort": "medium"},
      "status": "active",
      "enabled": true
    }
  ]
}

GET /v1/models/:id returns a single entry or 404 model_not_found.

Like every other /v1/* request, GET /v1/models and GET /v1/models/:id write one request_logs row per request (successes and rejections alike).

GET /health

{"status":"ok","name":"OpenCode Router","version":"1.0.0","uptimeMs":86400000,
 "startedAt":1765000000000,"providers":1,"models":12,"apiKeys":true}

uptimeMs is the real process uptime (now - startedAt), not a placeholder.

Streaming

All three surfaces stream as text/event-stream when stream: true is set. Bytes are forwarded as they arrive from the upstream provider (Cache-Control: no-cache, X-Accel-Buffering: no). Frames are decoded only to extract token usage and to strip provider-internal x_opencode metadata, so invalid UTF-8 and a leading BOM reach the client unchanged. Every blank-line frame boundary is recognized (\n\n, \r\n\r\n, \r\n\n, \n\r\n, \r\r), and a frame with several data: lines is decoded as one payload so multi-line x_opencode objects are stripped too.

request_timeout_ms (Dashboard → Settings → Routing) is a total deadline that covers the streamed body, and stream_idle_timeout_ms (default 120000, min 1000) cuts off an upstream that goes silent between frames/reads. An unterminated SSE frame is capped at 1 MiB: the upstream is aborted and the request fails with 502 upstream_frame_too_large. Client aborts terminate the upstream request and are logged with client_aborted (status 499). A retryable upstream retry-after (delta seconds or HTTP-date) is honoured, capped at one hour, and the provider cooldown becomes max(provider_cooldown_ms, retryAfter); an existing longer cooldown is never shortened by a later failure.