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.
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);
},
},
);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,
)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(())
}$.promptCache provider.degradation.google.prompt_cache_hint_omittedIt 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.
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);
},
},
);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,
)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(())
}$.tools provider.degradation.anthropic.custom_tool_as_string_functionIt 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.
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);
},
},
);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,
)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(())
}$.promptCacheBreakpoint provider.degradation.google.cache_control_omittedIt 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.
The samples also need cargo add serde_json.
Requests and replies across APIs#
Your request is written in OpenAI ResponsesOpenAI Chat CompletionsAnthropic Messages, and the model's provider may speak another API. The Router rewrites the request into the provider's API and rewrites the reply into OpenAI ResponsesOpenAI Chat CompletionsAnthropic Messages, 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:
strictrefuses the call before anything is sent, so nothing is charged.best_effortsends 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:
- leave out
prompt_cache_keyfor a provider with no such field; - leave out a reasoning
summarythat the model cannot return; - send a custom tool to an Anthropic model as a function that takes one string.
- send a custom tool to an Anthropic model as a function that takes one string;
- send
reasoning_effortasnonewhenopenai/gpt-6-lunagets tools, since OpenAI Chat Completions takes its tools only without reasoning.
- leave out
cache_controlbreakpoints for a provider with no such field; - leave out a
thinkingbudget foropenai/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 onFidelityDecisionon_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#
const bestEffort = { fidelity: 'best_effort' } as const;
const byHeader = { headers: { 'x-tokedex-fidelity-policy': 'best_effort' } };best_effort = {"fidelity": "best_effort"}
by_header = {"extra_headers": {"x-tokedex-fidelity-policy": "best_effort"}}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(),
)]));Pass either object as the call's second argument. It applies to that call only.
Pass either as keyword arguments to the call, such as router.chat.completions.create(**best_effort, …). It applies to that call only.
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 OpenAI ResponsesOpenAI Chat CompletionsAnthropic Messages and reports each one. Strict is yours to ask for. A model served natively on OpenAI ResponsesOpenAI Chat CompletionsAnthropic Messages usually has nothing to approximate, so it takes each request exactly or refuses it under either policy.
A router that chooses among several models, such as aa/fastest, is strict.
A router 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#
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);
}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)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);
}
}
}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);
}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)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.
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);
}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)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.
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 or Errors, retries and timeouts.