
# Custom models

Add your own model server to the Router under a namespaced model ID you choose, and call it like any other model. These examples use the local namespace `local/`; `upstreamModel` (Python and Rust: `upstream_model`) keeps the server's native model ID separate from the public selector.

**OpenAI Chat Completions**

```ts
import { Router } from '@tokedex/sdk';

const router = new Router({
  customModels: [
    {
      model: 'local/llama',
      protocol: 'openai.chat-completions',
      baseUrl: 'http://localhost:11434',
      upstreamModel: 'llama3.2',
    },
  ],
});

const completion = await router.chat.completions.create({
  model: 'local/llama',
  messages: [{ role: 'user', content: 'Name the capital of France in one word.' }],
});
console.log(completion.choices[0]?.message.content);
```

```python
from tokedex import Router, RouterCustomModel

local_llama = RouterCustomModel("local/llama", "http://localhost:11434", upstream_model="llama3.2")

with Router(custom_models=[local_llama]) as router:
    completion = router.chat.completions.create(
        model="local/llama",
        messages=[{"role": "user", "content": "Name the capital of France in one word."}],
    )
    print(completion.choices[0].message.content)
```

```rust
use tokedex::{Router, RouterCustomModel, wire};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut local_llama = RouterCustomModel::new("local/llama", "http://localhost:11434");
    local_llama.upstream_model = Some("llama3.2".into());
    let router = Router::builder().custom_model(local_llama).build()?;

    let messages = vec![wire::Message::user("Name the capital of France in one word.")];
    let request = wire::ChatCompletionsRequest::new("local/llama", messages);
    let completion = router.chat().completions().create(request).await?;
    if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content {
        println!("{text}");
    }
    Ok(())
}
```

```text
Paris
```

It needs [Ollama](https://ollama.com) running with `llama3.2` pulled. Nothing goes to a cloud provider, so nothing is billed. LM Studio and most other local servers speak OpenAI Chat Completions too; change `baseUrl` and the model.

**OpenAI Responses**

```ts
import { Router } from '@tokedex/sdk';

const router = new Router({
  customModels: [{ model: 'local/model', upstreamModel: 'local-model', protocol: 'openai.responses', baseUrl: 'http://localhost:8000' }],
});

const response = await router.responses.create({
  model: 'local/model',
  input: 'Name the capital of France in one word.',
});
const text = response.output
  .flatMap((item) => (item.type === 'message' ? item.content : []))
  .flatMap((part) => (part.type === 'output_text' ? [part.text] : []))
  .join('');
console.log(text);
```

```python
from tokedex import Router, RouterCustomModel

local_model = RouterCustomModel("local/model", "http://localhost:8000", upstream_model="local-model", protocol="openai.responses")

with Router(custom_models=[local_model]) as router:
    response = router.responses.create(
        model="local/model", input="Name the capital of France in one word."
    )
    print(response.output_text)
```

```rust
use tokedex::{Router, RouterCustomModel, RouterCustomProtocol, wire};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut local_model = RouterCustomModel::new("local/model", "http://localhost:8000")
        .with_protocol(RouterCustomProtocol::Responses);
    local_model.upstream_model = Some("local-model".into());
    let router = Router::builder().custom_model(local_model).build()?;

    let request = wire::ResponsesRequest::new("local/model", "Name the capital of France in one word.");
    let response = router.responses().create(request).await?;
    println!("{}", response.output_text());
    Ok(())
}
```

```text
Paris
```

It needs a server at `http://localhost:8000` that speaks OpenAI Responses. Nothing goes to a cloud provider, so nothing is billed.

**Anthropic Messages**

```ts
import { Router } from '@tokedex/sdk';

const router = new Router({
  customModels: [
    {
      model: 'local/model',
      protocol: 'anthropic.messages',
      baseUrl: 'http://localhost:8000',
      upstreamModel: 'local-model',
      messages: { apiVersion: '2023-06-01', maxOutputTokens: 16384 },
    },
  ],
});

const message = await router.messages.create({
  model: 'local/model',
  messages: [{ role: 'user', content: 'Name the capital of France in one word.' }],
});
const text = message.content.flatMap((block) => (block.type === 'text' ? [block.text] : [])).join('');
console.log(text);
```

```python
from tokedex import Router, RouterCustomModel

local_model = RouterCustomModel(
    "local/model",
    "http://localhost:8000",
    upstream_model="local-model",
    protocol="anthropic.messages",
    messages={"api_version": "2023-06-01", "max_output_tokens": 16384},
)

with Router(custom_models=[local_model]) as router:
    message = router.messages.create(
        model="local/model",
        messages=[{"role": "user", "content": "Name the capital of France in one word."}],
    )
    print("".join(block.text for block in message.content if block.type == "text"))
```

```rust
use tokedex::{Router, RouterCustomModel, RouterCustomProtocol, wire};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut local_model = RouterCustomModel::new("local/model", "http://localhost:8000").with_protocol(
        RouterCustomProtocol::Messages { api_version: "2023-06-01".into(), max_output_tokens: 16384 },
    );
    local_model.upstream_model = Some("local-model".into());
    let router = Router::builder().custom_model(local_model).build()?;

    let messages = vec![wire::Message::user("Name the capital of France in one word.")];
    let request = wire::MessagesRequest::new("local/model", messages);
    let message = router.messages().create(request).await?;
    for block in &message.content {
        if let wire::ContentBlock::Text { text, .. } = block {
            println!("{text}");
        }
    }
    Ok(())
}
```

```text
Paris
```

It needs a server at `http://localhost:8000` that speaks Anthropic Messages. Nothing goes to a cloud provider, so nothing is billed.

Through a gateway, the gateway's administrator adds model servers instead; see [Connect your own model server](/gateway/custom-models) in the gateway docs.

## Call an unlisted model from the SDK

Pass the provider's model ID as `model` and name the providers you want to call. The embedded Router uses their reviewed APIs and API keys. This example uses `FIREWORKS_API_KEY` and calls Fireworks, which can incur charges.

**Rust**

The Rust examples for calling unlisted models and configuring provider-hosted models use the SDK from a [Tokedex source checkout](https://github.com/ArtificialAnalysis/Tokedex). From your Cargo project, add the SDK as a path dependency and replace `/path/to/Tokedex` with the path to your checkout.

```bash
cargo add tokedex --path /path/to/Tokedex/rust/crates/tokedex
```

```ts
import { Router } from '@tokedex/sdk';

const router = new Router();
const completion = await router.chat.completions.create({
  model: 'accounts/fireworks/routers/glm-5p3-fast',
  messages: [{ role: 'user', content: 'Reply with OK.' }],
}, { providers: ['fireworks'] });
console.log(completion.choices[0]?.message.content);
```

```python
from tokedex import Router

with Router() as router:
    completion = router.chat.completions.create(
        model="accounts/fireworks/routers/glm-5p3-fast",
        messages=[{"role": "user", "content": "Reply with OK."}],
        providers=["fireworks"],
    )
    print(completion.choices[0].message.content)
```

```rust
use tokedex::{RequestOptions, Router, wire};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?;
    let request = wire::ChatCompletionsRequest::new(
        "accounts/fireworks/routers/glm-5p3-fast",
        vec![wire::Message::user("Reply with OK.")],
    );
    let pinned = router.with_options(RequestOptions::default().providers(["fireworks"]));
    let completion = pinned.chat().completions().create(request).await?;
    if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content {
        println!("{text}");
    }
    Ok(())
}
```

Set a default list with [[new Router({ providers: ['fireworks'] })|Router(providers=["fireworks"])|Router::builder().providers(["fireworks"]).build()?]]. A list on a call replaces the default. A provider pin header narrows the effective list when both are set.

On a catalogue match, the list limits normal routing to those providers. IDs beginning with `aa/` are reserved for built-in routers. For an unlisted ID, the list gives the base order and each eligible provider receives the same model ID. Set `providerOrder` (Python: `provider_order`; Rust: `RequestOptions::provider_order`) to change that order within the list. The Router can try a second provider after a retryable failure, before it sends a response.

The Router prefers the provider API that matches your request. If only one other reviewed API can serve it, the Router translates the request and reports any fidelity losses. A Chat Completions or Responses request without an output limit uses 4,096 tokens when it reaches Anthropic Messages.

To serve an unlisted model through a gateway, have an administrator [add it in the gateway](/gateway/custom-models).

## A model a catalogue provider serves

When a provider the catalogue knows serves a model the catalogue does not list yet, name the provider and its model ID instead of a server. The Router calls the provider's own API with the key it already reads for that provider, such as `FIREWORKS_API_KEY`, and serves the model under the provider's ID, so a provider pin names it.

**Rust**

Use the [Rust SDK from a source checkout](#call-an-unlisted-model-from-the-sdk) for `RouterCustomModel::on_provider`.

```ts
import { Router } from '@tokedex/sdk';

const router = new Router({
  customModels: [
    { model: 'team/new-model', provider: 'fireworks', upstreamModel: 'accounts/fireworks/models/new-model' },
  ],
});

const completion = await router.chat.completions.create({
  model: 'team/new-model',
  messages: [{ role: 'user', content: 'Name the capital of France in one word.' }],
});
console.log(completion.choices[0]?.message.content);
```

```python
from tokedex import Router, RouterCustomModel

new_model = RouterCustomModel(
    "team/new-model", provider="fireworks", upstream_model="accounts/fireworks/models/new-model"
)

with Router(custom_models=[new_model]) as router:
    completion = router.chat.completions.create(
        model="team/new-model",
        messages=[{"role": "user", "content": "Name the capital of France in one word."}],
    )
    print(completion.choices[0].message.content)
```

```rust
use tokedex::{Router, RouterCustomModel, wire};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let new_model = RouterCustomModel::on_provider("team/new-model", "fireworks", "accounts/fireworks/models/new-model");
    let router = Router::builder().custom_model(new_model).build()?;

    let messages = vec![wire::Message::user("Name the capital of France in one word.")];
    let request = wire::ChatCompletionsRequest::new("team/new-model", messages);
    let completion = router.chat().completions().create(request).await?;
    if let Some(wire::Content::Text(text)) = &completion.choices[0].message.content {
        println!("{text}");
    }
    Ok(())
}
```

- **Provider.** Use a reviewed provider API, including those for Bedrock, Vertex AI, Azure, Google AI Studio, Cloudflare Workers AI and Databricks. The Router uses the provider's credentials and account settings. [[The Router uses the provider's API when it has one, and asks for `protocol` when it has several.|The Router uses the provider's API when it has one, and asks for `protocol` when it has several.|The Router uses the provider's API when it has one, and asks for `with_protocol` when it has several.]] Construction fails for a provider that cannot serve the model, naming the available APIs.
- **Model ID.** `upstreamModel` (Python: `upstream_model`; Rust: `the third argument`) is the provider's own ID. A model the catalogue already serves on that provider is refused: call it by its catalogue ID instead.
- **Inputs.** It takes text and function tools. [[inputs: ['image']|inputs=("image",)|with_inputs([RouterCustomInput::Image])]] lets images or files through.
- **Reasoning.** Set reasoning on the request as you would for a built-in model. The provider's API determines which controls the Router can send, including named effort, Responses summaries and context, Messages adaptive thinking and token budgets, or Gemini `thinkingBudget` and `includeThoughts`. If a route offers effort but cannot send the requested level, the Router reports the available levels before calling the provider. The provider can still reject a forwarded control.
- **APIs.** Most providers serve OpenAI Responses, OpenAI Chat Completions and Anthropic Messages. Bedrock Converse serves OpenAI Responses. Vertex AI and Google AI Studio models using GenerateContent also serve Gemini GenerateContent. The Router translates between supported APIs and reports the provider's reviewed losses in best-effort mode. Strict mode requires a lossless route.
- **Messages.** On a Messages provider, set `messages: { maxOutputTokens }` (Python: `messages={"api_version": …, "max_output_tokens": …}`; Rust: `RouterCustomProtocol::Messages { api_version, max_output_tokens }`).

## Serve one model ID through several providers

**Rust**

Use the [Rust SDK from a source checkout](#call-an-unlisted-model-from-the-sdk) to configure several providers for one model ID.

```ts
import { Router } from '@tokedex/sdk';

const router = new Router({
  customModels: [
    { model: 'team/new-model', provider: 'fireworks', upstreamModel: 'accounts/fireworks/models/new-model',
      price: { input: '0.10', output: '0.30' } },
    { model: 'team/new-model', provider: 'togetherai', upstreamModel: 'example/new-model' },
  ],
});
```

```python
from tokedex import Router, RouterCustomModel

primary = RouterCustomModel(
    "team/new-model", provider="fireworks", upstream_model="accounts/fireworks/models/new-model",
    price={"input": "0.10", "output": "0.30"},
)
backup = RouterCustomModel(
    "team/new-model", provider="togetherai", upstream_model="example/new-model"
)

with Router(custom_models=[primary, backup]) as router:
    available_models = router.models.list()
```

```rust
use tokedex::{Router, RouterCustomModel, RouterCustomPrice};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let _router = Router::builder()
        .custom_model_with_price(
            RouterCustomModel::on_provider("team/new-model", "fireworks", "accounts/fireworks/models/new-model"),
            RouterCustomPrice::tokens("0.10", "0.30"),
        )
        .custom_model(RouterCustomModel::on_provider("team/new-model", "togetherai", "example/new-model"))
        .build()?;
    Ok(())
}
```

Give every declaration the same model ID and listing setting. Name a different provider in each declaration. Each client API can use the providers that serve it, and model discovery lists the shared ID once per API.

- **Price order.** The Router ranks priced providers by the input and output rates in US dollars per million tokens. Input counts three times as much as output. Use [[`price: { free: true }`|`price={"free": True}`|`RouterCustomPrice::Free`]] for a free provider. Unpriced providers follow priced ones, and provider ID breaks ties.
- **Order and pins.** Set a preferred provider order on the Router or on the call. A provider pin limits the call to the named providers. [Order the providers](/sdk/models#order-the-providers)
- **Fallback.** Before the response starts, a retryable failure can send the request to the next eligible provider. Each provider uses its own reviewed translations. A continuation returns to the provider that served the earlier turn.

## Server protocols

| Server speaks | Protocol | Also give |
|---|---|---|
| OpenAI Chat Completions | `openai.chat-completions` | Nothing |
| OpenAI Responses | `openai.responses` | Nothing |
| Anthropic Messages | `anthropic.messages` | `messages: { apiVersion, maxOutputTokens }` (Python: `messages={"api_version": …, "max_output_tokens": …}`; Rust: `RouterCustomProtocol::Messages { api_version, max_output_tokens }`) |

**TypeScript**

Every custom model names its `protocol`.

**Python**

`protocol` defaults to `openai.chat-completions`.

**Rust**

`with_protocol` sets the protocol; without it, a custom model speaks OpenAI Chat Completions.

Choose the protocol your server speaks natively, because the Router sends it requests in that protocol. Start with `openai.chat-completions`, which LM Studio, Ollama and most local servers speak. Choose `openai.responses` when your server speaks it and you want typed values from `router.responses.parse` (Rust: `router.responses().parse`), which needs that protocol.

- Give the server's address with or without `/v1`, and `upstreamModel` (Python, Rust: `upstream_model`) when the server knows the model by another name.
- An OpenAI Responses server receives every request with `store: false`. The Router keeps the conversation itself, so `previous_response_id` still works.
- An Anthropic Messages server takes the API version `2023-06-01`. `max_output_tokens` is the most a call may ask for, and the default when a call sets none, so set it to the most your server can return.

## API for a custom model

Call the model on the one API its server speaks: `router.chat.completions` (OpenAI Responses: `router.responses`; Anthropic Messages: `router.messages`) here. A call on any other API fails with `NotFound`, because the Router does not translate to your server.

Set reasoning on the request using `reasoning_effort` (OpenAI Responses: `reasoning`; Anthropic Messages: `thinking`). Choose a named effort level. (OpenAI Responses: Set the effort, summary or context.; Anthropic Messages: Choose adaptive, disabled or manual thinking, or set the output effort.) Your server decides which of those controls the model accepts.

**OpenAI Chat Completions, Anthropic Messages**

To get a typed value with `router.responses.parse` (Rust: `router.responses().parse`), declare the model with the OpenAI Responses protocol; see [Structured output](/sdk/structured-output).

## Rules

- **IDs.** An ID cannot be blank, start with `aa/` or match a built-in model ID. Reuse an ID only across different reviewed providers. Name the model for its role, such as `local-llama`, and give the server's own name in `upstreamModel` (Python, Rust: `upstream_model`), so you can swap the model on the server without changing your calls.
- **Inputs.** A custom model takes text and function tools. A request with an image or a file fails before anything is sent.
- **Listing.** `router.models.list()` (Rust: `router.models().list()`) lists custom models after the built-in ones, with `trust` set to `unreviewed`. Set `listed: false` (Python: `listed=False`; Rust: `listed = false`) to leave one out; you can still call it by ID.
- **Keys.** Set `apiKey` (Python, Rust: `api_key`) if the server needs one. The Router sends it as `x-api-key` to an Anthropic Messages server and as a bearer token to the others, and sends no key when you set none. Read the key from the environment or a secret store, as you would a provider key, so it stays out of your source code.

Next: [Choose a model](/sdk/models) or [Conversations](/sdk/conversations).
