Skip to content

OpenRouter

Install

To use OpenRouterModel, you need to either install pydantic-ai, or install pydantic-ai-slim with the openrouter optional group:

pip install "pydantic-ai-slim[openrouter]"
uv add "pydantic-ai-slim[openrouter]"

Configuration

To use OpenRouter, first create an API key at openrouter.ai/keys.

You can set the OPENROUTER_API_KEY environment variable and use OpenRouterProvider by name:

from pydantic_ai import Agent

agent = Agent('openrouter:anthropic/claude-3.5-sonnet')
...

Or initialise the model and provider directly:

from pydantic_ai import Agent
from pydantic_ai.models.openrouter import OpenRouterModel
from pydantic_ai.providers.openrouter import OpenRouterProvider

model = OpenRouterModel(
    'anthropic/claude-3.5-sonnet',
    provider=OpenRouterProvider(api_key='your-openrouter-api-key'),
)
agent = Agent(model)
...

App Attribution

OpenRouter has an app attribution feature to track your application in their public ranking and analytics.

You can pass in an app_url and app_title when initializing the provider to enable app attribution.

from pydantic_ai.providers.openrouter import OpenRouterProvider

provider=OpenRouterProvider(
    api_key='your-openrouter-api-key',
    app_url='https://your-app.com',
    app_title='Your App',
),
...