Language
Client

Connect your app#

Keep the client your app already uses and change three values, its base URL, its API key and the model ID, to send its requests through the gateway.

import OpenAI from 'openai';
 
const client = new OpenAI({
  baseURL: process.env['TOKEDEX_BASE_URL'],
  apiKey: process.env['TOKEDEX_API_KEY'],
});
 
const completion = await client.chat.completions.create({
  model: 'openai/gpt-6-luna',
  messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }],
});
console.log(completion.choices[0]?.message.content);
import os
 
from openai import OpenAI
 
client = OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"])
 
completion = client.chat.completions.create(
    model="openai/gpt-6-luna",
    messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
)
print(completion.choices[0].message.content)
code
hello
import Anthropic from '@anthropic-ai/sdk';
 
const client = new Anthropic({
  baseURL: process.env['TOKEDEX_URL'],
  apiKey: process.env['TOKEDEX_API_KEY'],
});
 
const message = await client.messages
  .stream({
    model: 'openai/gpt-6-luna',
    // Anthropic's SDK requires max_tokens, and streaming once it is this large.
    max_tokens: 128000,
    messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }],
  })
  .finalMessage();
for (const block of message.content) if (block.type === 'text') console.log(block.text);
import os
 
from anthropic import Anthropic
 
client = Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"])
 
with client.messages.stream(
    model="openai/gpt-6-luna",
    # Anthropic's SDK requires max_tokens, and streaming once it is this large.
    max_tokens=128000,
    messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
) as stream:
    message = stream.get_final_message()
for block in message.content:
    if block.type == "text":
        print(block.text)
code
hello

For Rust, choose Tokedex SDK in the bar above: its Rust client takes the same address and key.

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\"." }]
  }'
JSON
{
  "object": "chat.completion",
  "model": "openai/gpt-6-luna",
  "choices": [{ "index": 0, "message": { "role": "assistant", "content": "hello" }, "finish_reason": "stop" }],
  "usage": { "prompt_tokens": 14, "completion_tokens": 2, "total_tokens": 16 }
}
import { Router } from '@tokedex/sdk';
 
const router = new Router({
  baseUrl: process.env['TOKEDEX_URL']!,
  apiKey: process.env['TOKEDEX_API_KEY']!,
});
 
const completion = await router.chat.completions.create({
  model: 'openai/gpt-6-luna',
  messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }],
});
console.log(completion.choices[0]?.message.content);
import os
 
from tokedex import Router
 
with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router:
    completion = router.chat.completions.create(
        model="openai/gpt-6-luna",
        messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
    )
    print(completion.choices[0].message.content)
use tokedex::{GatewayOptions, Router, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?;
    let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)];
    let request = wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages);
    let completion = router.chat().completions().create(request).await?;
    if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content {
        println!("{text}");
    }
    Ok(())
}
code
hello

You need: the gateway's address and an API key (tokedex_ik_…) that can call openai/gpt-6-luna. An admin can give you one, or you can create one under API keys. For an application, use a workspace key rather than your personal key, because a personal key stops working when its holder leaves the workspace. Each request calls a provider and can incur charges.

Values to change#

Shell
export TOKEDEX_BASE_URL='http://127.0.0.1:4000/v1'
export TOKEDEX_API_KEY='<your-api-key>'
Shell
export TOKEDEX_URL='http://127.0.0.1:4000'
export TOKEDEX_API_KEY='<your-api-key>'
ValueSet it to
Base URLThe gateway's address followed bywithout /v1, such as https://gateway.example.com/v1https://gateway.example.com
API keyYour API key, in place of the provider's key
Model IDA model ID your key can call, such as openai/gpt-6-luna

127.0.0.1 reaches the gateway only from its own machine. A client in a container or on another computer needs an address it can reach. Keep the key in your app's secret store, never in browser code or source files, because anyone who reads it can call models on your key until it is revoked.

The same client calls other providers' models too: with anthropic/claude-haiku-5.5 as the model ID, if your key can call it, the gateway sends the request to Anthropic.

The client adds /chat/completions to the base URL and sends the key as Authorization: Bearer. The same client calls OpenAI Responses at client.responses.create.

The client adds /v1/messages to the base URL and sends the key in x-api-key. The gateway accepts anthropic-version: 2023-06-01, the version the client sends.

Send the key as Authorization: Bearer. The same key calls OpenAI Responses at $TOKEDEX_BASE_URL/responses, and Anthropic Messages at $TOKEDEX_BASE_URL/messages, where x-api-key carries it too.

The SDK adds each API's path to the address, such as /v1/chat/completions, and sends the key as Authorization: Bearer. The same Router calls OpenAI Responses, Anthropic Messages and Gemini GenerateContent too; see Run through a gateway.

API reference lists each API's endpoints, the headers the gateway reads and returns, and what it does with each request field.

List the models your key can call#

import OpenAI from 'openai';
 
const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'] });
 
for await (const model of client.models.list()) {
  if ('client_dialect_id' in model && model.client_dialect_id === 'openai.chat-completions') console.log(model.id);
}
import os
 
from openai import OpenAI
 
client = OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"])
 
for model in client.models.list():
    if getattr(model, "client_dialect_id", None) == "openai.chat-completions":
        print(model.id)
import Anthropic from '@anthropic-ai/sdk';
 
const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'] });
 
for await (const model of client.models.list()) {
  if ('client_dialect_id' in model && model.client_dialect_id === 'anthropic.messages') console.log(model.id);
}
import os
 
from anthropic import Anthropic
 
client = Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"])
 
for model in client.models.list():
    if getattr(model, "client_dialect_id", None) == "anthropic.messages":
        print(model.id)
Shell
curl -sS "$TOKEDEX_BASE_URL/models" \
  -H "Authorization: Bearer $TOKEDEX_API_KEY"
JSON
{
  "object": "list",
  "data": [
    …
    { "id": "openai/gpt-6-luna", "object": "model", "client_dialect_id": "openai.chat-completions", "context_window": 1050000, … },
    { "id": "openai/gpt-6-luna", "object": "model", "client_dialect_id": "openai.responses", "context_window": 1050000, … },
    …
  ],
  "models": […]
}
import { Router } from '@tokedex/sdk';
 
const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! });
 
for (const model of await router.models.list()) {
  if (model.client_dialect_id === 'openai.chat-completions') console.log(model.id);
}
import os
 
from tokedex import Router
 
with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router:
    for model in router.models.list():
        if model.client_dialect_id == "openai.chat-completions":
            print(model.id)
use tokedex::{GatewayOptions, Router};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?;
    for model in router.models().list().await? {
        if model.client_dialect_id == "openai.chat-completions" {
            println!("{}", model.id);
        }
    }
    Ok(())
}
code
…
openai/gpt-6.1-sol
openai/gpt-6.1-terra
openai/gpt-6-luna
…

The list holds each model ID once for every client API that serves it, and client_dialect_id names the API; a model ID can be served on one client API and not another. Use an ID listed with openai.chat-completionsanthropic.messages. An empty list means no provider is connected yet, or your key can call no model. Listing sends nothing to a provider, so check a model ID here with the key your app will use before you deploy it.

Stream a response#

import OpenAI from 'openai';
 
const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'] });
 
const stream = await client.chat.completions.create({
  model: 'openai/gpt-6-luna',
  messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }],
  stream: true,
});
for await (const chunk of stream) process.stdout.write(chunk.choices[0]?.delta.content ?? '');
console.log();
import os
 
from openai import OpenAI
 
client = OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"])
 
stream = client.chat.completions.create(
    model="openai/gpt-6-luna",
    messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
    stream=True,
)
for chunk in stream:
    for choice in chunk.choices:
        print(choice.delta.content or "", end="", flush=True)
print()
import Anthropic from '@anthropic-ai/sdk';
 
const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'] });
 
const stream = client.messages.stream({
  model: 'openai/gpt-6-luna',
  max_tokens: 128000,
  messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }],
});
stream.on('text', (text: string) => process.stdout.write(text));
await stream.finalMessage();
console.log();
import os
 
from anthropic import Anthropic
 
client = Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"])
 
with client.messages.stream(
    model="openai/gpt-6-luna",
    max_tokens=128000,
    messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)
print()
Shell
curl -sS -N "$TOKEDEX_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $TOKEDEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "openai/gpt-6-luna",
    "stream": true,
    "messages": [{ "role": "user", "content": "Reply with exactly the word \"hello\"." }]
  }'
code
data: {"object":"chat.completion.chunk","model":"openai/gpt-6-luna","choices":[{"index":0,"delta":{"role":"assistant"},"finish_reason":null}]}
 
data: {"object":"chat.completion.chunk","model":"openai/gpt-6-luna","choices":[{"index":0,"delta":{"content":"hello"},"finish_reason":null}]}
 
data: {"object":"chat.completion.chunk","model":"openai/gpt-6-luna","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}
 
data: {"object":"chat.completion.chunk","model":"openai/gpt-6-luna","choices":[],"usage":{"prompt_tokens":14,"completion_tokens":2,"total_tokens":16}}
 
data: [DONE]

-N prints each event as it arrives. The stream ends with a usage chunk and data: [DONE].

import { Router } from '@tokedex/sdk';
 
const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! });
 
for await (const chunk of router.chat.completions.stream({
  model: 'openai/gpt-6-luna',
  messages: [{ role: 'user', content: 'Reply with exactly the word "hello".' }],
})) {
  process.stdout.write(chunk.choices[0]?.delta.content ?? '');
}
console.log();
import os
 
from tokedex import Router
 
with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router:
    with router.chat.completions.stream(
        model="openai/gpt-6-luna",
        messages=[{"role": "user", "content": 'Reply with exactly the word "hello".'}],
    ) as chunks:
        for chunk in chunks:
            for choice in chunk.choices:
                print(choice.delta.content or "", end="", flush=True)
    print()
use tokedex::{GatewayOptions, Router, StreamExt, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?;
    let messages = vec![wire::Message::user(r#"Reply with exactly the word "hello"."#)];
    let mut chunks = router.chat().completions().stream(wire::ChatCompletionsRequest::new("openai/gpt-6-luna", messages));
    while let Some(chunk) = chunks.next().await {
        for choice in chunk?.choices {
            if let wire::Presence::Value(text) = choice.delta.content {
                print!("{text}");
            }
        }
    }
    println!();
    Ok(())
}
code
hello

The last chunk carries usage and no choices.

A streamed request can fail after it starts, so handle an error inside the stream as well as an error status.

Errors#

import OpenAI from 'openai';
 
const client = new OpenAI({ baseURL: process.env['TOKEDEX_BASE_URL'], apiKey: process.env['TOKEDEX_API_KEY'] });
 
try {
  await client.chat.completions.create({ model: 'unknown/no-such-model', messages: [{ role: 'user', content: 'Hello' }] });
} catch (error) {
  if (!(error instanceof OpenAI.APIError)) throw error;
  console.log(error.status, error.code);
}
import os
 
import openai
 
client = openai.OpenAI(base_url=os.environ["TOKEDEX_BASE_URL"], api_key=os.environ["TOKEDEX_API_KEY"])
 
try:
    client.chat.completions.create(model="unknown/no-such-model", messages=[{"role": "user", "content": "Hello"}])
except openai.APIStatusError as error:
    print(error.status_code, error.code)
code
404 model_not_found

The client raises an APIErrorAPIStatusError with the HTTP status in statusstatus_code and the gateway's error code in code. Branch on code.

import Anthropic from '@anthropic-ai/sdk';
 
const client = new Anthropic({ baseURL: process.env['TOKEDEX_URL'], apiKey: process.env['TOKEDEX_API_KEY'] });
 
try {
  await client.messages
    .stream({ model: 'unknown/no-such-model', max_tokens: 128000, messages: [{ role: 'user', content: 'Hello' }] })
    .finalMessage();
} catch (error) {
  if (!(error instanceof Anthropic.APIError)) throw error;
  const body = error.error as { error?: { code?: string } } | undefined;
  console.log(error.status, body?.error?.code);
}
import os
 
import anthropic
 
client = anthropic.Anthropic(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"])
 
try:
    with client.messages.stream(
        model="unknown/no-such-model", max_tokens=128000, messages=[{"role": "user", "content": "Hello"}]
    ) as stream:
        stream.get_final_message()
except anthropic.APIStatusError as error:
    print(error.status_code, error.body["error"]["code"])
code
404 model_not_found

The client raises an APIErrorAPIStatusError subclass that follows the status, such as NotFoundError for 404. The body is {"type":"error","error":{"code":"model_not_found","type":"not_found_error","message":"…"}}. Branch on error.code in the body.

Shell
curl -sS -i "$TOKEDEX_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $TOKEDEX_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "unknown/no-such-model",
    "messages": [{ "role": "user", "content": "Hello" }]
  }'
code
HTTP/1.1 404 Not Found
content-type: application/json
 
{"error":{"code":"model_not_found","message":"model is not available on this gateway","type":"invalid_request_error"}}

Branch on error.code. Anthropic Messages wraps the same fields as {"type":"error","error":{…}}, so error.code holds the code there too.

import { GatewayHttpError, Router } from '@tokedex/sdk';
 
const router = new Router({ baseUrl: process.env['TOKEDEX_URL']!, apiKey: process.env['TOKEDEX_API_KEY']! });
 
try {
  await router.chat.completions.create({ model: 'unknown/no-such-model', messages: [{ role: 'user', content: 'Hello' }] });
} catch (error) {
  if (!(error instanceof GatewayHttpError)) throw error;
  console.log(error.status, error.code);
}
import os
 
import httpx2
from tokedex import Router
 
with Router(base_url=os.environ["TOKEDEX_URL"], api_key=os.environ["TOKEDEX_API_KEY"]) as router:
    try:
        router.chat.completions.create(model="unknown/no-such-model", messages=[{"role": "user", "content": "Hello"}])
    except httpx2.HTTPStatusError as error:
        print(error.response.status_code, error.response.json()["error"]["code"])
use tokedex::{Error, GatewayOptions, Router, RouterError, wire};
 
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::new(GatewayOptions::new(std::env::var("TOKEDEX_URL")?, std::env::var("TOKEDEX_API_KEY")?))?;
    let request = wire::ChatCompletionsRequest::new("unknown/no-such-model", vec![wire::Message::user("Hello")]);
    match router.chat().completions().create(request).await {
        Err(Error::Router(error)) => {
            if let RouterError::Provider { status_code, provider_code, .. } = *error {
                println!("{status_code:?} {provider_code:?}");
            }
        }
        Err(error) => return Err(error.into()),
        Ok(_) => {}
    }
    Ok(())
}
code
404 model_not_found
code
Some(404) Some("model_not_found")

The Router throws a GatewayHttpError, with the HTTP status in status and the gateway's error code in code. Branch on code.

The Router raises httpx2.HTTPStatusError. The status is in error.response.status_code, and the gateway's error code in the body's error.code. Branch on the code.

The Router returns Error::Router holding a RouterError::Provider, with the HTTP status in status_code and the gateway's error code in provider_code. Branch on provider_code.

The code names the cause where one status has several:

StatusCodeMeans
401invalid_api_keyThe key is wrong or revoked
402budget_exceededA budget that applies to the key has run out
403permission_denied, key_expired, key_disabled, key_suspendedThe key may not make this request, or cannot be used
404model_not_foundThe gateway does not serve this model ID
429rate_limitedA rate limit applies; retry later
502, 503provider_unavailable and othersThe provider failed or could not be reached

A retry sends another provider request and can incur another charge. Retry only 429 and the 5xx codes that Errors, limits and request IDs marks retryable: a 401, 402, 403 or 404 fails the same way until the key, the budget or the request changes.

Next: Connect a coding agent, Errors, limits and request IDs or Run through a gateway in the SDK docs.