Code Examples
Interactive code examples and comprehensive guides to help you get started with TokenRouter API.
Quick Start Examples
Simple examples to get you started with the TokenRouter API.
Basic Text Generation
Simple request with minimal parameters
Basic cURL Request
bashcurl -X POST https://api.tokenrouter.com/route \
-H "Authorization: Bearer tr_your_api_key_here" \
-H "Content-Type: application/json" \
-d '{
"prompt": "Explain quantum computing in simple terms",
"temperature": 0.7,
"max_tokens": 1000
}'
Advanced Usage
More complex examples with model preferences, cost optimization, and client libraries.
Advanced Configuration
Using model preferences, cost priority, and analytics
Python Client Class
pythonimport requests
import json
class TokenRouterClient:
def __init__(self, api_key):
self.api_key = api_key
self.base_url = "https://api.tokenrouter.com"
self.headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
def route(self, prompt, **kwargs):
data = {"prompt": prompt, **kwargs}
response = requests.post(
f"{self.base_url}/route",
headers=self.headers,
json=data
)
return response.json()
def get_usage_stats(self, start_date=None, end_date=None):
params = {}
if start_date:
params["start_date"] = start_date
if end_date:
params["end_date"] = end_date
response = requests.get(
f"{self.base_url}/analytics/usage",
headers=self.headers,
params=params
)
return response.json()
# Usage
client = TokenRouterClient("tr_your_api_key_here")
result = client.route(
prompt="Analyze market trends for Q4 2024",
model_preferences=["gpt-4", "claude-3-opus"],
temperature=0.3,
max_tokens=2000,
cost_priority="quality"
)
print(f"Selected model: {result['tokenrouter']['selected_model']}")
print(f"Cost savings: {result['tokenrouter']['cost_savings']}")
print(f"Response: {result['choices'][0]['message']['content']}")
Function Calling
Examples of using function calling (tools) with TokenRouter for interactive AI applications.
Weather Function Example
Using tools to call external functions
Python Function Calling
pythonimport requests
import json
def get_weather(location, unit="fahrenheit"):
# Mock weather function
return {
"location": location,
"temperature": 72 if unit == "fahrenheit" else 22,
"condition": "sunny",
"unit": unit
}
def handle_function_calls(response):
if response.get("choices", [{}])[0].get("message", {}).get("tool_calls"):
tool_calls = response["choices"][0]["message"]["tool_calls"]
for tool_call in tool_calls:
function_name = tool_call["function"]["name"]
function_args = json.loads(tool_call["function"]["arguments"])
if function_name == "get_weather":
result = get_weather(**function_args)
print(f"Weather in {result['location']}: {result['temperature']}°{result['unit'][0].upper()}, {result['condition']}")
# Make the request
url = "https://api.tokenrouter.com/route"
headers = {
"Authorization": "Bearer tr_your_api_key_here",
"Content-Type": "application/json"
}
data = {
"prompt": "What is the weather like in San Francisco and New York?",
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
},
"required": ["location"]
}
}
}
],
"tool_choice": "auto"
}
response = requests.post(url, headers=headers, json=data)
result = response.json()
# Handle function calls if present
handle_function_calls(result)
SDK Integration
OpenAI SDK Compatibility
Drop-in replacement for OpenAI SDK
CompatibleTokenRouter is compatible with the OpenAI SDK. Simply change the base URL:
OpenAI SDK Integration
pythonfrom openai import OpenAI
client = OpenAI(
api_key="tr_your_api_key_here",
base_url="https://api.tokenrouter.com"
)
response = client.chat.completions.create(
model="gpt-4", # Will be intelligently routed
messages=[
{"role": "user", "content": "Hello, world!"}
]
)
print(response.choices[0].message.content)
Error Handling
Robust error handling patterns
Best PracticeAlways implement proper error handling for production applications:
Error Handling Example
pythontry:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
result = response.json()
except requests.exceptions.HTTPError as e:
if response.status_code == 429:
# Rate limited
retry_after = response.headers.get('Retry-After', 60)
print(f"Rate limited. Retry after {retry_after}s")
elif response.status_code == 401:
print("Invalid API key")
else:
print(f"HTTP error: {e}")
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")