Skip to content

Routing Rules API - Programmatic AI Routing Control

The Routing Rules API allows you to programmatically create and manage custom routing rules that control how TokenRouter selects AI providers and models for your requests.

TokenRouter currently supports the following providers for routing rules:

  • openai - OpenAI (GPT-4o, GPT-4, GPT-3.5)
  • anthropic - Anthropic (Claude 3.7, Claude 3.5, Claude 3)
  • gemini - Google Gemini
  • mistral - Mistral AI
  • deepseek - DeepSeek
  • balance - Balanced routing (default)
  • cost - Cost-optimized routing
  • quality - Quality-optimized routing
  • latency - Latency-optimized routing

GET https://api.tokenrouter.io/v1/routing-rules

Returns all routing rules for the authenticated user, ordered by priority (highest first).

const response = await fetch('https://api.tokenrouter.io/v1/routing-rules', {
headers: {
'Authorization': 'Bearer tr_...',
}
});
const { data } = await response.json();
console.log(`Found ${data.length} routing rules`);
{
"data": [
{
"id": 1,
"user_id": 123,
"name": "Force Anthropic for Code",
"is_enabled": true,
"priority": 100,
"match_json": {
"contains": ["code", "function", "programming"]
},
"action_json": {
"set_provider": "anthropic",
"set_model": "claude-3-7-sonnet-latest"
},
"created_at": "2025-09-13T19:14:17.000000Z",
"updated_at": "2025-09-13T19:14:17.000000Z"
}
]
}

POST https://api.tokenrouter.io/v1/routing-rules

Creates a new routing rule.

ParameterTypeRequiredDescription
namestringYesHuman-readable name (max 128 chars)
is_enabledbooleanYesWhether the rule is active
priorityintegerYesPriority (-1000 to 1000, higher = first)
match_jsonobjectYesConditions for matching
action_jsonobjectYesActions to take when matched

All conditions are combined with AND logic - every specified condition must match for the rule to trigger.

ConditionTypeDescriptionExample
containsstring or arraySearch for text in user input (case-insensitive substring match)"code" or ["code", "function"]
metadata_equalsobjectMatch metadata key-value pairs (exact match){"user_tier": "premium"}
modestringMatch routing mode (case-insensitive)"balance", "cost", "quality", "latency"
taskstringShorthand for metadata_equals.task (case-sensitive)"summarize"

Notes:

  • contains searches anywhere in the input text (if array, matches if ANY value found)
  • Input is normalized: objects/arrays are JSON-encoded before matching
  • Empty strings in contains array are ignored

Once set, actions cannot be overridden by lower-priority rules.

ActionTypeDescriptionNotes
set_providerstringForce specific providerLowercase: openai, anthropic, gemini, mistral, deepseek
set_modelstringForce specific modelFull model name: claude-3-7-sonnet-latest, gpt-4o
set_modestringOverride routing modeLowercase: balance, cost, quality, latency
add_warningstring or objectAdd custom warningString or {"message": "text"}

Action Precedence:

  • First matching rule that sets set_provider wins - subsequent rules cannot change it
  • Same applies for set_model and set_mode
  • add_warning can be set by multiple rules (accumulates)
  • Skipped actions are logged in rule trace with reason
const response = await fetch('https://api.tokenrouter.io/v1/routing-rules', {
method: 'POST',
headers: {
'Authorization': 'Bearer tr_...',
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: "Force Anthropic for Code",
is_enabled: true,
priority: 100,
match_json: {
contains: ["code", "function", "programming"]
},
action_json: {
set_provider: "anthropic",
set_model: "claude-3-7-sonnet-latest"
}
})
});
const { data } = await response.json();
console.log(`Created rule: ${data.name}`);
{
"name": "Cost-optimize summaries",
"is_enabled": true,
"priority": 50,
"match_json": {
"metadata_equals": {
"task": "summarize"
}
},
"action_json": {
"set_mode": "cost"
}
}
{
"name": "Research in balanced mode",
"is_enabled": true,
"priority": 60,
"match_json": {
"contains": "research",
"mode": "balanced"
},
"action_json": {
"set_mode": "quality",
"set_provider": "anthropic"
}
}

GET https://api.tokenrouter.io/v1/routing-rules/{id}

Returns a single routing rule by ID.

const response = await fetch('https://api.tokenrouter.io/v1/routing-rules/1', {
headers: {
'Authorization': 'Bearer tr_...',
}
});
const { data } = await response.json();

PATCH https://api.tokenrouter.io/v1/routing-rules/{id}

Updates an existing routing rule. All fields are optional.

await fetch('https://api.tokenrouter.io/v1/routing-rules/1', {
method: 'PATCH',
headers: {
'Authorization': 'Bearer tr_...',
'Content-Type': 'application/json',
},
body: JSON.stringify({
is_enabled: false
})
});
{
"priority": 150
}
{
"action_json": {
"set_provider": "openai",
"set_model": "gpt-4o"
}
}

DELETE https://api.tokenrouter.io/v1/routing-rules/{id}

Permanently deletes a routing rule.

await fetch('https://api.tokenrouter.io/v1/routing-rules/1', {
method: 'DELETE',
headers: {
'Authorization': 'Bearer tr_...',
}
});
{
"success": true
}

Section titled “Example 1: Route Legal Questions to GPT-4o”
{
"name": "Legal content → GPT-4o",
"is_enabled": true,
"priority": 90,
"match_json": {
"contains": ["legal", "contract", "compliance", "regulation"]
},
"action_json": {
"set_provider": "openai",
"set_model": "gpt-4o"
}
}

When it matches:

  • Input contains “legal”, “contract”, “compliance”, or “regulation”

What it does:

  • Routes to OpenAI’s GPT-4o model

Example 2: Use DeepSeek for Cost-Sensitive Tasks

Section titled “Example 2: Use DeepSeek for Cost-Sensitive Tasks”
{
"name": "Cost mode → DeepSeek",
"is_enabled": true,
"priority": 75,
"match_json": {
"mode": "cost"
},
"action_json": {
"set_provider": "deepseek"
}
}

When it matches:

  • Request uses auto:cost or mode is set to cost

What it does:

  • Routes to DeepSeek (most cost-effective)
{
"name": "Premium users → Quality",
"is_enabled": true,
"priority": 80,
"match_json": {
"metadata_equals": {
"user_tier": "premium"
}
},
"action_json": {
"set_mode": "quality",
"add_warning": {
"message": "Premium user - using quality routing"
}
}
}

When it matches:

  • Request metadata includes user_tier: "premium"

What it does:

  • Switches to quality mode
  • Adds a warning message to the response

Rules are evaluated in the following order:

  1. Priority (descending) - Higher priority rules evaluated first
  2. ID (ascending) - Older rules evaluated first for same priority
  3. All rules are checked - Multiple rules can match the same request
  4. Action precedence - First rule to set an action wins for that action type
{
"error": {
"message": "The name field is required."
}
}
{
"error": {
"message": "Custom routing rules require a paid plan."
}
}
{
"error": {
"message": "Routing rule not found"
}
}