Skip to content

Rules API Overview

The Rules API allows you to create custom routing logic that determines how TokenRouter routes your requests. Routing rules are evaluated before provider selection and can override the default routing behavior.

Routing rules let you define conditions that, when matched, trigger specific actions like:

  • Forcing a specific provider (e.g., always use OpenAI for coding tasks)
  • Overriding the routing mode (e.g., switch to cost mode for documentation)
  • Setting a specific model (e.g., use GPT-4 for complex analysis)
  • Adding warnings to responses

Rules are evaluated in priority order (highest first):

  1. Rules with higher priority values execute first
  2. When multiple rules match, the first matching rule’s actions take precedence
  3. Only enabled rules are evaluated (is_enabled: true)
  4. Rules are evaluated before firewall rules in the routing pipeline
https://api.tokenrouter.io/v1/routing-rules

All Rules API endpoints require authentication using your TokenRouter API key:

Terminal window
Authorization: Bearer tr_your_api_key
OperationMethodEndpoint
List all rulesGET/v1/routing-rules
Get single ruleGET/v1/routing-rules/{id}
Create rulePOST/v1/routing-rules
Update rulePATCH/v1/routing-rules/{id}
Delete ruleDELETE/v1/routing-rules/{id}

Define when a rule should be applied:

{
"contains": "code review", // Input contains text (case-insensitive)
"metadata_equals": { // Metadata key-value matches
"task": "documentation"
},
"mode": "balanced", // Routing mode equals
"task": "coding" // Shorthand for metadata_equals.task
}

All conditions must match for the rule to apply (AND logic).

Define what happens when a rule matches:

{
"set_provider": "openai", // Force specific provider
"set_model": "gpt-4o", // Force specific model
"set_mode": "cost", // Override routing mode
"add_warning": { // Add warning message
"message": "Using cost-optimized routing"
}
}
import Tokenrouter from 'tokenrouter';
const client = new Tokenrouter({
apiKey: process.env.TOKENROUTER_API_KEY
});
// Create a rule to use Anthropic for code review tasks
const rule = await client.routingRules.create({
name: 'Code Review → Anthropic',
priority: 100,
is_enabled: true,
match_json: {
task: 'code_review'
},
action_json: {
set_provider: 'anthropic',
set_model: 'claude-3-5-sonnet-20241022'
}
});

When a routing rule is applied, the response includes metadata:

{
"metadata": {
"applied_rules": ["Code Review → Anthropic"],
"routing_mode": "balanced",
"provider": "anthropic",
"model": "claude-3-5-sonnet-20241022"
}
}