
# Translation between APIs

Send a request in the API you use to a model whose provider speaks another, and choose what happens to a field that has no equivalent there.

**OpenAI Responses**

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

const router = new Router();
await router.responses.create(
  {
    model: 'google/gemini-3.5-flash-lite',
    input: 'Name the capital of France in one word.',
    prompt_cache_key: 'geography',
  },
  {
    fidelity: 'best_effort',
    onFidelityDecision: (decision) => {
      for (const change of decision.degradations) console.log(change.path, change.code);
    },
  },
);
```

```python
from tokedex import Router
from tokedex.core.ir import FidelityDecision


def report(decision: FidelityDecision) -> None:
    for change in decision.degradations:
        print(change.path, change.code)


with Router() as router:
    router.responses.create(
        model="google/gemini-3.5-flash-lite",
        input="Name the capital of France in one word.",
        prompt_cache_key="geography",
        fidelity="best_effort",
        on_fidelity_decision=report,
    )
```

```rust
use std::sync::Arc;

use serde_json::json;
use tokedex::{FidelityDecision, FidelityPolicy, RequestOptions, Router, wire};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?.with_options(RequestOptions {
        fidelity: Some(FidelityPolicy::BestEffort),
        on_fidelity_decision: Some(Arc::new(|decision: FidelityDecision| {
            for change in decision.degradations {
                println!("{} {}", change.path, change.code);
            }
        })),
        ..Default::default()
    });
    let request: wire::ResponsesRequest = serde_json::from_value(json!({
        "model": "google/gemini-3.5-flash-lite",
        "input": "Name the capital of France in one word.",
        "prompt_cache_key": "geography",
    }))?;
    router.responses().create(request).await?;
    Ok(())
}
```

```text
$.promptCache provider.degradation.google.prompt_cache_hint_omitted
```

It needs `GEMINI_API_KEY`, and the call is billed by Google. Google's API has no prompt cache key, so the Router left `prompt_cache_key` out, sent the rest and reported the change.

**OpenAI Chat Completions**

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

const router = new Router();
await router.chat.completions.create(
  {
    model: 'anthropic/claude-haiku-5.5',
    messages: [{ role: 'user', content: 'How many users signed up today?' }],
    tools: [{ type: 'custom', custom: { name: 'run_sql', description: 'Run one SQL query.' } }],
  },
  {
    fidelity: 'best_effort',
    onFidelityDecision: (decision) => {
      for (const change of decision.degradations) console.log(change.path, change.code);
    },
  },
);
```

```python
from tokedex import Router
from tokedex.core.ir import FidelityDecision


def report(decision: FidelityDecision) -> None:
    for change in decision.degradations:
        print(change.path, change.code)


with Router() as router:
    router.chat.completions.create(
        model="anthropic/claude-haiku-5.5",
        messages=[{"role": "user", "content": "How many users signed up today?"}],
        tools=[{"type": "custom", "custom": {"name": "run_sql", "description": "Run one SQL query."}}],
        fidelity="best_effort",
        on_fidelity_decision=report,
    )
```

```rust
use std::sync::Arc;

use serde_json::json;
use tokedex::{FidelityDecision, FidelityPolicy, RequestOptions, Router, wire};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?.with_options(RequestOptions {
        fidelity: Some(FidelityPolicy::BestEffort),
        on_fidelity_decision: Some(Arc::new(|decision: FidelityDecision| {
            for change in decision.degradations {
                println!("{} {}", change.path, change.code);
            }
        })),
        ..Default::default()
    });
    let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({
        "model": "anthropic/claude-haiku-5.5",
        "messages": [{ "role": "user", "content": "How many users signed up today?" }],
        "tools": [{ "type": "custom", "custom": { "name": "run_sql", "description": "Run one SQL query." } }],
    }))?;
    router.chat().completions().create(request).await?;
    Ok(())
}
```

```text
$.tools provider.degradation.anthropic.custom_tool_as_string_function
```

It needs `ANTHROPIC_API_KEY`, and the call is billed by Anthropic. Anthropic Messages has no free-form custom tool, so the Router sent `run_sql` as a function that takes one string, and reported the change.

**Anthropic Messages**

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

const router = new Router();
await router.messages.create(
  {
    model: 'google/gemini-3.5-flash-lite',
    system: [{ type: 'text', text: 'Answer in one word.', cache_control: { type: 'ephemeral' } }],
    messages: [{ role: 'user', content: 'Name the capital of France.' }],
  },
  {
    fidelity: 'best_effort',
    onFidelityDecision: (decision) => {
      for (const change of decision.degradations) console.log(change.path, change.code);
    },
  },
);
```

```python
from tokedex import Router
from tokedex.core.ir import FidelityDecision


def report(decision: FidelityDecision) -> None:
    for change in decision.degradations:
        print(change.path, change.code)


with Router() as router:
    router.messages.create(
        model="google/gemini-3.5-flash-lite",
        system=[
            {"type": "text", "text": "Answer in one word.", "cache_control": {"type": "ephemeral"}}
        ],
        messages=[{"role": "user", "content": "Name the capital of France."}],
        fidelity="best_effort",
        on_fidelity_decision=report,
    )
```

```rust
use std::sync::Arc;

use serde_json::json;
use tokedex::{FidelityDecision, FidelityPolicy, RequestOptions, Router, wire};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let router = Router::builder().build()?.with_options(RequestOptions {
        fidelity: Some(FidelityPolicy::BestEffort),
        on_fidelity_decision: Some(Arc::new(|decision: FidelityDecision| {
            for change in decision.degradations {
                println!("{} {}", change.path, change.code);
            }
        })),
        ..Default::default()
    });
    let request: wire::MessagesRequest = serde_json::from_value(json!({
        "model": "google/gemini-3.5-flash-lite",
        "system": [{ "type": "text", "text": "Answer in one word.", "cache_control": { "type": "ephemeral" } }],
        "messages": [{ "role": "user", "content": "Name the capital of France." }],
    }))?;
    router.messages().create(request).await?;
    Ok(())
}
```

```text
$.promptCacheBreakpoint provider.degradation.google.cache_control_omitted
```

It needs `GEMINI_API_KEY`, and the call is billed by Google. Google's API has no cache breakpoint, so the Router left `cache_control` out, sent the rest and reported the change.

**Rust**

The samples also need `cargo add serde_json`.

## Requests and replies across APIs

Your request is written in your API, and the model's provider may speak another API. The Router rewrites the request into the provider's API and rewrites the reply into your API, so your code reads every model's answer from the same fields. Most fields have an exact equivalent, so most requests arrive exactly as you wrote them. Gemini GenerateContent takes only Google's Gemini and Gemma models, which Google serves on that API, so nothing is translated there.

## Fields with no equivalent

The fidelity policy decides what happens to a field with no equivalent:

- **`strict`** refuses the call before anything is sent, so nothing is charged.
- **`best_effort`** sends the call, drops or approximates only the fields it is allowed to change, and reports each change.

A field that `best_effort` may not change refuses the call under either policy.

Chat Completions and Messages keep the visible summary and answer when a Responses provider also returns encrypted reasoning. The gateway reports the omitted encrypted content in the `x-tokedex-fidelity-v1` response header. In a stream, look for the report on a Chat chunk with empty `choices`, a Messages `message_delta`, or the terminal error. If an embedded stream throws, read `responseProjectionReport` on the TypeScript error, `response_projection_report` on the Python exception, or `raw["x-tokedex-fidelity-v1"]` on the Rust provider error.

If you send an assistant's `reasoning_content` back in Chat history, the selected route determines what the provider receives. Reviewed Chat hosts and xAI Responses routes can replay plain reasoning. Other reviewed cross-dialect routes retain the assistant's answer, omit its unsigned reasoning, and report `provider.degradation.chat.reasoning_echo_omitted` at `$.messages` under both fidelity policies. If an Anthropic response contains signed thinking, Chat returns the visible thinking and reports `provider.degradation.anthropic.thinking_signature_omitted` at `$.reasoning`. The gateway's buffered response header carries both observed omissions. A stream's opening header reports the history omission, and its terminal Chat chunk reports the omissions observed through completion.

Start with `strict` while you build, so each field a model cannot carry shows up as a refusal that costs nothing. Allow `best_effort` for a call once you have read the changes it reports and your code works without those fields. Keep `strict` where a dropped field would make the answer wrong, not only different.

## Changes best_effort makes

Each model has its own short list of changes on each API. For example, `best_effort` can:

**OpenAI Responses**

- leave out `prompt_cache_key` for a provider with no such field;
- leave out a reasoning `summary` that the model cannot return;
- send a custom tool to an Anthropic model as a function that takes one string.

**OpenAI Chat Completions**

- send a custom tool to an Anthropic model as a function that takes one string;
- send `reasoning_effort` as `none` when `openai/gpt-6-luna` gets tools, since OpenAI Chat Completions takes its tools only without reasoning.

**Anthropic Messages**

- leave out `cache_control` breakpoints for a provider with no such field;
- leave out a `thinking` budget for `openai/gpt-6-luna`, which takes an effort level rather than a budget, so OpenAI uses its default effort.

It never changes a function tool, a tool call's arguments or result, or an ID.

Under `best_effort`, pass `onFidelityDecision` (Python, Rust: `on_fidelity_decision`) as the opening sample does and log what it reports, so a dropped field shows in your logs and not only as a different answer.

## Set the policy

```ts
const bestEffort = { fidelity: 'best_effort' } as const;
const byHeader = { headers: { 'x-tokedex-fidelity-policy': 'best_effort' } };
```

```python
best_effort = {"fidelity": "best_effort"}
by_header = {"extra_headers": {"x-tokedex-fidelity-policy": "best_effort"}}
```

```rust
use tokedex::{FidelityPolicy, RequestOptions};

let best_effort = router.with_options(RequestOptions::default().fidelity(FidelityPolicy::BestEffort));
let by_header = router.with_options(RequestOptions::default().headers([(
    "x-tokedex-fidelity-policy".to_string(),
    "best_effort".to_string(),
)]));
```

**TypeScript**

Pass either object as the call's second argument. It applies to that call only.

**Python**

Pass either as keyword arguments to the call, such as `router.chat.completions.create(**best_effort, …)`. It applies to that call only.

**Rust**

`with_options` returns a Router whose calls all use the options.

The header does the same as the option, and a gateway reads it too. If either one says `strict`, the call is strict.

## Default policy

With no policy set, a call is `best_effort`: the model applies the approximations reviewed for it on your API and reports each one. Strict is yours to ask for. A model served natively on your API usually has nothing to approximate, so it takes each request exactly or refuses it under either policy.

**TypeScript**

A [router](/sdk/models#routers) that chooses among several models, such as `aa/fastest`, is `strict`.

**Python, Rust**

A [router](/sdk/models#routers) that chooses among several models, such as `aa/fastest`, uses the default of each model it tries. Set the policy on calls to such a router ID, so every attempt follows the same rule.

The list of models does not show a model's default. To be certain which policy applies, set it yourself, so that moving a call to another model does not change what happens to a field.

## Refusal errors

**OpenAI Responses**

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

try {
  await router.responses.create(
    { model: 'google/gemini-3.5-flash-lite', input: 'Name the capital of France.', prompt_cache_key: 'geography' },
    { fidelity: 'strict' },
  );
} catch (error) {
  if (!(error instanceof FidelityError)) throw error;
  for (const issue of error.issues) console.log(issue.path, issue.feature);
}
```

```python
from tokedex.core.ir import FidelityError

try:
    router.responses.create(
        model="google/gemini-3.5-flash-lite",
        input="Name the capital of France.",
        prompt_cache_key="geography",
        fidelity="strict",
    )
except FidelityError as error:
    for issue in error.issues:
        print(issue.path, issue.feature)
```

```rust
use serde_json::json;
use tokedex::{Error, FidelityPolicy, RequestOptions, RouterError, wire};

let request: wire::ResponsesRequest = serde_json::from_value(json!({
    "model": "google/gemini-3.5-flash-lite",
    "input": "Name the capital of France.",
    "prompt_cache_key": "geography",
}))?;
let strict = router.with_options(RequestOptions::default().fidelity(FidelityPolicy::Strict));
if let Err(Error::Router(error)) = strict.responses().create(request).await {
    if let RouterError::FidelityError(refusal) = *error {
        for issue in refusal.issues {
            println!("{} {}", issue.path, issue.feature);
        }
    }
}
```

**OpenAI Chat Completions**

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

try {
  await router.chat.completions.create({
    model: 'anthropic/claude-haiku-5.5',
    messages: [{ role: 'user', content: 'Name the capital of France.' }],
    seed: 7,
  });
} catch (error) {
  if (!(error instanceof FidelityError)) throw error;
  for (const issue of error.issues) console.log(issue.path, issue.feature);
}
```

```python
from tokedex.core.ir import FidelityError

try:
    router.chat.completions.create(
        model="anthropic/claude-haiku-5.5",
        messages=[{"role": "user", "content": "Name the capital of France."}],
        seed=7,
    )
except FidelityError as error:
    for issue in error.issues:
        print(issue.path, issue.feature)
```

```rust
use serde_json::json;
use tokedex::{Error, RouterError, wire};

let request: wire::ChatCompletionsRequest = serde_json::from_value(json!({
    "model": "anthropic/claude-haiku-5.5",
    "messages": [{ "role": "user", "content": "Name the capital of France." }],
    "seed": 7,
}))?;
if let Err(Error::Router(error)) = router.chat().completions().create(request).await {
    if let RouterError::FidelityError(refusal) = *error {
        for issue in refusal.issues {
            println!("{} {}", issue.path, issue.feature);
        }
    }
}
```

Anthropic has no `seed`, and no policy lets the Router drop it, so this call is refused under either one.

**Anthropic Messages**

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

try {
  await router.messages.create(
    {
      model: 'google/gemini-3.5-flash-lite',
      system: [{ type: 'text', text: 'Answer in one word.', cache_control: { type: 'ephemeral' } }],
      messages: [{ role: 'user', content: 'Name the capital of France.' }],
    },
    { fidelity: 'strict' },
  );
} catch (error) {
  if (!(error instanceof FidelityError)) throw error;
  for (const issue of error.issues) console.log(issue.path, issue.feature);
}
```

```python
from tokedex.core.ir import FidelityError

try:
    router.messages.create(
        model="google/gemini-3.5-flash-lite",
        system=[
            {"type": "text", "text": "Answer in one word.", "cache_control": {"type": "ephemeral"}}
        ],
        messages=[{"role": "user", "content": "Name the capital of France."}],
        fidelity="strict",
    )
except FidelityError as error:
    for issue in error.issues:
        print(issue.path, issue.feature)
```

```rust
use serde_json::json;
use tokedex::{Error, FidelityPolicy, RequestOptions, RouterError, wire};

let request: wire::MessagesRequest = serde_json::from_value(json!({
    "model": "google/gemini-3.5-flash-lite",
    "system": [{ "type": "text", "text": "Answer in one word.", "cache_control": { "type": "ephemeral" } }],
    "messages": [{ "role": "user", "content": "Name the capital of France." }],
}))?;
let strict = router.with_options(RequestOptions::default().fidelity(FidelityPolicy::Strict));
if let Err(Error::Router(error)) = strict.messages().create(request).await {
    if let RouterError::FidelityError(refusal) = *error {
        for issue in refusal.issues {
            println!("{} {}", issue.path, issue.feature);
        }
    }
}
```

The refusal is a `FidelityError`, raised before anything is sent. Each of its `issues` names a part of the request by its `path` and says which `feature` could not be carried. Remove or change that part, or allow `best_effort` when it may change it. Do not retry the same request: the refusal comes from the request, the model and the policy, so the same call is refused again.

**TypeScript**

A refusal of a change that `best_effort` would make, such as a custom tool, can raise an error with kind `UnsupportedRequest` instead of `FidelityError`; its message names the part of the request.

Next: [Choose a model](/sdk/models) or [Errors, retries and timeouts](/sdk/errors-and-retries).
