This guide will help you get up and running with the OpenRouter Python client quickly.
Install the package using pip:
pip install openrouter-client-unofficialFor development with additional tools:
pip install openrouter-client-unofficial[dev]You'll need an OpenRouter API key to use this client. You can get one from OpenRouter.
from openrouter_client import OpenRouterClient
client = OpenRouterClient(api_key="your-api-key-here")You can also set your API key as an environment variable:
export OPENROUTER_API_KEY="your-api-key-here"Then initialize the client without passing the key:
client = OpenRouterClient() # Will automatically use OPENROUTER_API_KEYHere's a simple example to get you started:
from openrouter_client import OpenRouterClient
# Initialize the client
client = OpenRouterClient(api_key="your-api-key")
# Create a chat completion
response = client.chat.create(
model="anthropic/claude-3-opus",
messages=[
{"role": "user", "content": "What is the capital of France?"}
]
)
# Print the response
print(response.choices[0].message.content)You can list available models and their details:
# Get all available models
models = client.models.list()
for model in models.data:
print(f"{model.id}: {model.name}")
# Get specific model information
model_info = client.models.get("anthropic/claude-3-opus")
print(f"Context length: {model_info.context_length}")
print(f"Price per token: {model_info.pricing}")For real-time responses, you can use streaming:
stream = client.chat.create(
model="anthropic/claude-3-opus",
messages=[{"role": "user", "content": "Tell me a story"}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")The client provides comprehensive error handling:
from openrouter_client import OpenRouterClient
from openrouter_client.exceptions import (
OpenRouterError,
AuthenticationError,
RateLimitError,
ValidationError
)
client = OpenRouterClient(api_key="your-api-key")
try:
response = client.chat.create(
model="anthropic/claude-3-opus",
messages=[{"role": "user", "content": "Hello!"}]
)
except AuthenticationError:
print("Invalid API key")
except RateLimitError as e:
print(f"Rate limited. Retry after: {e.retry_after}")
except ValidationError as e:
print(f"Invalid request: {e}")
except OpenRouterError as e:
print(f"API error: {e}")Use the client as a context manager for automatic resource cleanup:
with OpenRouterClient(api_key="your-api-key") as client:
response = client.chat.create(
model="anthropic/claude-3-opus",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
# Client resources are automatically cleaned up here- Explore the API Reference for detailed endpoint documentation
- Learn about Advanced Features like function calling and rate limiting
- Check out practical Examples
- Customize your setup with Configuration options