API

API reference#

Look up what the gateway serves on OpenAI ResponsesOpenAI Chat CompletionsAnthropic MessagesGemini GenerateContent: its endpoints, where your API key goes, the headers it reads and returns, and what it does with each request field.

Method and pathDoes
POST /v1/responsesCreates a response

With "stream": true, the reply is server-sent events, each an event: line naming the type and a data: line, from response.created to response.completed, response.incomplete or response.failed, with no [DONE] line. Retrieving, deleting or cancelling a stored response, listing its input items, counting input tokens and compacting return 404.

Method and pathDoes
POST /v1/chat/completionsCreates a completion

With "stream": true, the reply is data: lines, each a chat.completion.chunk, ending with data: [DONE]. The stored-completion endpoints, such as GET /v1/chat/completions/{completion_id}, return 404.

Method and pathDoes
POST /v1/messagesCreates a message
POST /v1/messages/count_tokensCounts the input tokens of the same body and headers without generating, and returns {"input_tokens": <count>}. It takes a request from the key's rate limit and spends no budget

With "stream": true, the reply is server-sent events, each an event: line naming the type and a data: line, from message_start to message_stop. /v1/messages/batches returns 404.

Method and pathDoes
POST /v1/models/{model}:generateContentGenerates a response from the model the path names
POST /v1/models/{model}:streamGenerateContent?alt=sseStreams it as data: lines, each a GenerateContentResponse
POST /v1/models/{model}:countTokensCounts the input tokens of {"contents": […]}, or of a whole {"generateContentRequest": {…}}, without generating, and returns {"totalTokens": <count>}. It takes a request from the key's rate limit and spends no budget
GET /v1/models, GET /v1/models/{model} with x-goog-api-keyLists the Gemini models your key can call, or one of them, as Gemini API Models, all on one page. Without that header, GET /v1/models is the OpenAI-format list every API shares
POST /upload/v1beta/files with x-goog-api-keyStarts a resumable upload, as the SDK's files.upload() does, and answers with the gateway's own upload URL for the bytes. It is the one v1beta path served, because the SDK always uploads there
GET /v1/files, GET /v1/files/{file}, DELETE /v1/files/{file} with x-goog-api-keyLists, reads or deletes the files your key uploaded, as Gemini API Files. Another key's file returns 404. Without that header, /v1/files is not served

The paths take no other query string: a key parameter, or a stream request without alt=sse, returns 404, as do other model methods such as :embedContent, in Google's envelope. In the Google Gen AI SDK, set the base URL to the gateway's address and the API version to v1. The gateway serves Gemini only under Google's stable v1: a /v1beta path, which the SDK uses by default, returns 404 in Google's envelope with a message naming that setting. Context caches, embeddings and batches are not served.

An upload goes to Google under the gateway's own Google key, in the SDK's own chunks, each no larger than the gateway's request limit. Google keeps a file for 48 hours; each key's files count against limits the operator sets with TOKEDEX_FILES_MAX_FILES_PER_KEY and TOKEDEX_FILES_MAX_BYTES_PER_KEY, and an upload past them returns 413. Every Files call takes a request from the key's rate limit and spends no budget. A prompt may name in fileData.fileUri only a file your key uploaded through the gateway: any other URI on Google's API host returns 403, and such a prompt is served only by a model on that Google key.

The gateway ties files and unfinished uploads to the Google API key that opened them. After changing that key, upload again even if both keys belong to the same Google Cloud project. If the original key is restored, its unexpired files and uploads become available again. Files and uploads recorded before the gateway started tracking the Google key also need to be uploaded again.

Use the exact public model ID from discovery in {model}, such as google/gemini-3.5-flash-lite. The slash may be literal, as Google's SDK sends it, or encoded once as uppercase %2F, as the Tokedex SDK sends it. The same rule applies to model lookups. The gateway decodes once and matches the installed ID exactly: it does not infer a maker, retain retired bare IDs as aliases, or change case. Double or mixed encoding, empty or extra components, and dot-segment model components are rejected. Explicitly installed custom model atoms remain addressable; these public URL rules do not rename provider-native wire models.

You need: an API key (tokedex_ik_…), with TOKEDEX_BASE_URLTOKEDEX_URL and TOKEDEX_API_KEY set as in Connect your app. A request that reaches a model calls a provider and can incur charges.

Choose an API#

Use the API your client or agent already speaks: OpenAI Responses, OpenAI Chat Completions and Anthropic Messages each reach most models of every connected provider, so a new provider never needs a new API. Gemini GenerateContent serves Google's Gemini and Gemma models. Only OpenAI Responses keeps a conversation for you to continue with previous_response_id, and only Anthropic Messages and Gemini GenerateContent count input tokens.

Shared endpoints#

Method and pathDoesKey
GET /v1/modelsLists the model IDs your key can call, once for each client API that serves them; see Find a modelAuthorization: Bearer or x-api-key
GET /v1/limitsReturns every budget and rate limit that reaches your key; see Budget refusalsAuthorization: Bearer or x-api-key
POST /v1/keys/report-compromisedRevokes a leaked API key or admin key, sent as {"token": "<key>"}. It answers 202 to every well-formed report, so the reply never says whether the key was liveNone
GET /healthz, GET /readyz, GET /versionSay that the gateway is running, whether it is ready, and which release it runs. /readyz answers 503 while a store it needs does not answerNone
GET /api/helloAnswers 200 with no body; Claude Code checks it before its first requestNone
POST /v1/batches, GET /v1/batches/{id}, POST /v1/batches/{id}/cancel, GET /v1/batches/{id}/resultsBatch jobs, which only a gateway started from a configuration file runs, with one of that file's virtual keys or its master key. On any other gateway an API key gets 403. See Batch jobs in the SDK docsAuthorization: Bearer

A gateway started from a configuration file takes that file's virtual keys and master key on every path that takes a key, and has no admin keys, key states, budgets, rate limits, /v1/limits or report-compromised. The rest of this page describes a gateway started without one.

Authentication#

Send your API key as Authorization: Bearer. These paths do not read x-api-key, so a key sent only there gets 401.

Shell
curl -sS "$TOKEDEX_BASE_URL/responses" \
  -H "Authorization: Bearer $TOKEDEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-luna",
    "input": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }]
  }'
Shell
curl -sS "$TOKEDEX_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $TOKEDEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-luna",
    "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }]
  }'

Sent without the header, the same request gets 401:

JSON
{"error":{"code":"invalid_api_key","message":"authentication failed","type":"invalid_request_error"}}

Send your API key in x-api-key, as the Anthropic SDK does, or as Authorization: Bearer. If you send both, they must hold the same key, or the request gets 401.

Shell
curl -sS "$TOKEDEX_URL/v1/messages" \
  -H "x-api-key: $TOKEDEX_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-luna",
    "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }]
  }'

Sent without a key, the same request gets 401:

JSON
{"type":"error","error":{"code":"invalid_api_key","type":"authentication_error","message":"authentication failed"}}

Send your API key in x-goog-api-key, as the Google Gen AI SDK does, and no Authorization header: a request that carries both gets 401.

Shell
curl -sS "$TOKEDEX_URL/v1/models/google/gemini-3.5-flash-lite:generateContent" \
  -H "x-goog-api-key: $TOKEDEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "contents": [{ "role": "user", "parts": [{ "text": "Reply with exactly the word \"hello\"." }] }]
  }'

Sent without the header, the same request gets 401:

JSON
{"error":{"code":401,"status":"UNAUTHENTICATED","message":"authentication failed"}}

The gateway checks the key before it reads the body. A missing, unknown or revoked key gets 401 invalid_api_key, and so do the master key and admin keys, which do not call models: create an API key. A disabled, expired or suspended key gets 403 with its own code. The gateway calls providers with its own provider credentials and never forwards your key.

Request headers#

HeaderDoes
x-tokedex-fidelity-policystrict refuses with 422 a request the model cannot take exactly; best_effort lets the gateway drop or approximate what the model cannot take. Left out or empty, best_effort applies, and each approximation is reported in x-tokedex-fidelity-v1. Another value returns 400. See Check feature support
x-tokedex-providerComma-separated provider IDs allowed to serve the request; 422 provider_not_served when none of them can. See Choose a provider
x-tokedex-provider-orderComma-separated provider IDs the request tries first, in that order; the model's other providers follow. A blank or malformed value, or an ID that names no provider, returns 400. See Prefer providers
x-tokedex-trajectory-id, x-tokedex-tags, x-tokedex-project-name, x-tokedex-trace-text, x-tokedex-traceGroup, label and record the request; see Make a request easy to find
x-request-idIgnored: the gateway makes each request's ID itself

Anthropic Messages also reads these:

HeaderDoes
anthropic-versionOptional. 2023-06-01 is the only value accepted; another returns 400
anthropic-betaUp to 16 comma-separated values of up to 64 characters each, or 400. The gateway sends them on to a model it reaches over Anthropic's own API. Another model drops them and reports it in x-tokedex-fidelity-v1, or refuses with 422, as the fidelity policy decides

Response headers#

HeaderSent onHolds
x-request-id, request-id, x-tokedex-request-idEvery response except from report-compromised, errors includedThe request's ID, the same in all three
x-tokedex-provider, x-tokedex-modelSuccessThe provider that answered, after any fallback, and its name for the model
x-tokedex-deployment, x-tokedex-strategyMost successesThe deployment that served and the routing strategy that chose it
x-tokedex-fidelity-policySuccessThe fidelity policy the gateway applied
x-tokedex-fidelity-v1Success, when you asked for best_effort or the gateway changed the requestA JSON report of what it dropped or approximated
x-tokedex-trustSuccess from a model on your own model serverunreviewed
x-tokedex-ratelimit-limit, x-tokedex-ratelimit-remaining, x-tokedex-ratelimit-reset-msSuccess, when the key has a rate limitThe key's requests-a-minute limit, remaining requests, and milliseconds until the limit is full again on the replica that answered
x-tokedex-budget-remaining-usd and the other x-tokedex-budget-* headersSuccess, when a budget appliesThe tightest of the key's and its holder's own budgets; see Budgets
retry-after, retry-after-ms429The wait in seconds and in milliseconds. A provider's 429 carries retry-after only when the provider sent one
x-should-retry402, and 403 price_unavailablefalse, so the OpenAI and Anthropic SDKs do not retry it

A count_tokens response carries the request ID headers and x-tokedex-fidelity-policy, and x-tokedex-token-count: estimated when the count is the gateway's estimate rather than the provider's.

A countTokens response carries the request ID headers and x-tokedex-fidelity-policy, and x-tokedex-token-count: estimated when the count is the gateway's estimate rather than the provider's.

Request fields#

The gateway sends the request to the model that serves it, translated where that provider's API differs. A field the model cannot take gets 422 unsupported, naming the field, or, where the fidelity policy allows, is dropped or approximated and reported in x-tokedex-fidelity-v1. Where a table below says a value returns 400, the gateway refuses it itself with invalid_request, usually naming the field.

model is required. It names a model your key can call on OpenAI ResponsesOpenAI Chat CompletionsAnthropic MessagesGemini GenerateContent: a provider's model such as openai/gpt-6-lunagoogle/gemini-3.5-flash-lite, a router, or a model from your own model server, which only a key that names it can call. The reply's model is the ID you sent.

The path names the model: one your key can call, as the Google SDK's models.list() shows, and GET /v1/models with Authorization: Bearer lists for google.generate-content.

An ID this API does not serve returns 404 model_not_found, and one your key may not call returns 403 permission_denied; Find a model says why each happens. A task_type field is accepted only as "general", which changes nothing; another value returns 400.

The body must be JSON, or it gets 400 invalid_json, and at most 12,000,000 bytes, inline files and images counted after base64 encoding, or it gets 413 request_too_large. The operator changes the limit with TOKEDEX_MAX_REQUEST_BYTES, and a reverse proxy in front needs one at least as large.

FieldWhat the gateway does
inputA string or an array of input items
streamtrue streams the response
stream_optionsTakes include_obfuscation and include_usage; another key returns 400
storeLeft out or true, the gateway keeps the response for 24 hours by default, so previous_response_id can continue it. false keeps nothing
previous_response_idContinues a response the gateway kept. Send the same API key and model ID: an ID that is missing, expired or another key's returns 404 previous_response_not_found, as does one kept before the gateway's model configuration changed or, on a gateway without Postgres or Redis, before it restarted. A model that cannot continue a response returns 400 previous_response_unsupported
backgroundtrue returns 400
textIts format is text, json_object, json_schema with name and schema and optionally description and strict, grammar with syntax (lark or regex) and definition, or python; another key returns 400
top_logprobsA number asks for log probabilities; null asks for none; another value returns 400
The other fields of the OpenAI Responses API, such as instructions, tools, tool_choice, reasoning, include and max_output_tokensSent to the model

A field of the wrong type, such as a string in temperature, returns 400, except a stream, tools or instructions of the wrong type, which the gateway ignores. The operator sets how long responses are kept with TOKEDEX_CONTINUATION_TTL_SECONDS.

FieldWhat the gateway does
messagesRequired, with at least one message. Roles are system, developer, user, assistant and tool, and developer is read as system; another role returns 400
User message contentA string, or text, image_url, file and input_audio parts; another part type returns 400
streamtrue streams the completion
stream_optionsTakes only include_usage, a boolean; another key returns 400
max_completion_tokens, max_tokensWhen you send both, max_completion_tokens applies
temperature, top_p, seed, logprobs, parallel_tool_callsSent to the model
top_logprobsSent to the model with logprobs: true; without it, dropped
stopA string or an array of strings; anything else returns 400
toolsfunction and custom tools; another type returns 400
tool_choiceauto, none, required, or one named function or custom tool; another form returns 400
response_formattext, json_object, or json_schema with a json_schema.schema; another type returns 400
reasoning_effortnone, minimal, low, medium, high, xhigh or max; another value returns 400
Any other field, such as n, user, store, metadata, presence_penalty, frequency_penalty, logit_bias or service_tierReturns 400, naming the fields

The gateway ignores a value of the wrong type in temperature, top_p, seed, max_completion_tokens, max_tokens, logprobs, top_logprobs and parallel_tool_calls. It also ignores target_provider, and the snippy object with enabled: false that Copilot sends.

FieldWhat the gateway does
messagesRequired, with at least one message. Roles are user, assistant and system; another role returns 400
max_tokensOptional. Left out, an Anthropic model gets its maximum output
streamtrue streams the message; a value that is not a boolean returns 400
temperature, top_pNumbers; anything else returns 400
stop_sequencesAn array of strings; anything else returns 400
toolsClient tools, with name, input_schema, description, strict and cache_control. A tool with a type, such as Anthropic's web search, returns 400
system, tool_choice, thinking, output_config, metadata, context_managementSent to the model. A key inside them that the gateway does not know returns 400
Any other field, such as top_k or service_tierSent unchanged to a model the gateway reaches over Anthropic's own API. Another model returns 400
FieldWhat the gateway does
contentsThe conversation, with roles user and model
systemInstruction{"parts": […]} with text parts only, plus an optional role, which is ignored; another part type returns 400
Partstext, inlineData and fileData, the last two with an optional mediaResolution and, on a video, videoMetadata. A model turn may also hold the executableCode, codeExecutionResult, toolCall and toolResponse Parts a built-in tool returned, which go back to Gemini as they came
generationConfigTakes temperature, topP, topK, seed, presencePenalty, frequencyPenalty, maxOutputTokens, stopSequences, candidateCount, thinkingConfig, responseLogprobs, logprobs, mediaResolution and enableEnhancedCivicAnswers, all sent to Gemini as given. logprobs without responseLogprobs: true, or another key, returns 400. presencePenalty, frequencyPenalty and responseLogprobs: true return 422 before Gemini is called on a model that refuses them, which every Gemini and Gemma model in the catalogue does; the error names the fields to remove
Structured outputresponseMimeType with responseJsonSchema or responseSchema, sent as given, so text/x.enum works too. A schema without responseMimeType, or both schemas, returns 400
responseModalities["TEXT"] only: the gateway returns text, so another modality returns 400
safetySettingsSent to Gemini as given, each with category and threshold
toolsfunctionDeclarations, and Google's built-in tools googleSearch (with an optional timeRangeFilter), urlContext, codeExecution and googleMaps (with an optional enableWidget), each sent to Gemini as given, after the functions. A model not granted a built-in tool returns 422; another built-in tool, or a field Gemini refuses such as excludeDomains, returns 400. Gemini's grounding, URL-context and code-execution results come back as Gemini returns them
toolConfigfunctionCallingConfig with mode AUTO, NONE or ANY, and with ANY any number of allowedFunctionNames; VALIDATED, or names with another mode, returns 400. With a built-in tool, also retrievalConfig, the location Maps and Search ground on, and includeServerSideToolInvocations, which Gemini needs before it takes built-in tools beside functions
model, streamReturn 400: the path names the model and whether to stream
Any other field, such as cachedContent or serviceTierReturns 400

Errors#

Errors use OpenAI's envelope, {"error": {"code", "message", "type"}}. Inside a stream, an error is an event: error whose data holds code, message and param.

Errors use OpenAI's envelope, {"error": {"code", "message", "type"}}. Inside a stream, an error is a data: {"error": {…}} line followed by data: [DONE].

Errors use Anthropic's envelope, {"type": "error", "error": {"code", "type", "message"}}, with the gateway's code in error.code. Inside a stream, an error is an event: error with the same body.

Errors use Google's envelope, {"error": {"code", "status", "message"}}, where code is the HTTP status. A refusal for the key's state or one of its limits adds a details entry of type google.rpc.ErrorInfo, whose reason is the gateway's code in capitals, such as RATE_LIMITED. Other refusals carry none of the gateway codes this page names: read the HTTP status and error.status. Inside a stream, an error is a data: line with the same body.

A path the gateway does not serve gets 404 before your key is checked: the OpenAI envelope with code not_found on a POST, and a plain-text body on other methods. An error before the first streamed event returns its own status and a JSON body. Errors, limits and request IDs lists the codes and says which to retry.

Recommendations#

  • Send x-tokedex-fidelity-policy: strict when your code depends on a field, such as structured output it parses, so a model that cannot honour it fails with 422 instead of dropping it.
  • Check each model ID in GET /v1/models with your app's key before you deploy, since an ID can be served on one API and not another, and listing sends nothing to a provider.
  • Log x-request-idrequest-id with your own errors, since every response carries it, errors included, and Observability finds the request by it.
  • Send store: false when your client keeps its own history or makes a one-off request. To continue a turn with client-managed history, send the earlier inputs and response output items in input. Kept responses count against your key's storage, and once it is full the gateway refuses requests that would keep one with 503 continuation_capacity.
  • Count a large prompt with count_tokens and compare it with the model's context_window before you send it, since a count generates nothing and spends no budget.
  • Count a large prompt with countTokens and compare it with the model's inputTokenLimit before you send it, since a count generates nothing and spends no budget.

Next: Connect your app, Find a model or Errors, limits and request IDs.