Registry / llm-agents / openrouter

openrouter

JSON →
library1.1.94pypypi✓ verified 26d ago

Official Python SDK for the OpenRouter API — a unified gateway to 300+ LLM models across providers (OpenAI, Anthropic, Google, Meta, Mistral, etc.) via a single OpenAI-compatible endpoint. Auto-generated from OpenRouter's OpenAPI spec and updated on every API change. Fully typed with Pydantic. SDK is explicitly in beta — breaking changes can occur between minor versions without a major version bump. IMPORTANT: There are multiple competing 'openrouter' packages on PyPI (openrouter, openrouter-client, python-open-router). Only 'openrouter' (by OpenRouter) is the official SDK.

pip install openrouter
INSTALL
IMPORT
SIG · OPENROUTER
O
openrouter
llm-agentspythonv1.1.94
Install
4.5s avg
Import
747ms
Disk
41MB
Pass rate
10/ 10
Env Coverage10 / 10
glibc
3.93.13
musl
3.93.13
Install & Compatibility
Where this runs
tested against v1.1.94 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
py 3.103.910 runs
installs and imports cleanly · install 0.0s · import 0.775s · 42.8MB
glibc
py 3.103.910 runs
installs and imports cleanly · install 4.5s · import 0.719s · 42MB
41MB installed
● package 41MB
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

OpenRouter
from openrouter import OpenRouter
import openrouter; openrouter.client()
Use as context manager: 'with OpenRouter(api_key=...) as client'. This ensures HTTPX connections are properly closed.

Always use OpenRouter as a context manager to ensure HTTPX connections are released. The OpenAI SDK approach (with base_url override) is simpler and more widely used in practice — consider it as a primary option if you already have openai installed.

import os from openrouter import OpenRouter # Sync usage — use as context manager with OpenRouter(api_key=os.environ['OPENROUTER_API_KEY']) as client: # Standard completion response = client.chat.send( model='anthropic/claude-sonnet-4-20250514', messages=[{'role': 'user', 'content': 'Hello!'}] ) print(response) # With provider routing preferences response = client.chat.send( model='openai/gpt-4o', messages=[{'role': 'user', 'content': 'Hello!'}], provider={ 'sort': 'price', # or 'latency', 'throughput' 'zdr': True # Zero Data Retention } ) # Async usage import asyncio from openrouter import OpenRouter async def main(): async with OpenRouter(api_key=os.environ['OPENROUTER_API_KEY']) as client: response = await client.chat.send_async( model='anthropic/claude-sonnet-4-20250514', messages=[{'role': 'user', 'content': 'Hello!'}] ) print(response) asyncio.run(main()) # OpenAI SDK approach (no openrouter package needed) from openai import OpenAI client = OpenAI( api_key=os.environ['OPENROUTER_API_KEY'], base_url='https://openrouter.ai/api/v1' ) response = client.chat.completions.create( model='anthropic/claude-sonnet-4-20250514', messages=[{'role': 'user', 'content': 'Hello!'}] )
Debug
Known issues
breakingSDK is explicitly in beta. The PyPI page states: 'breaking changes between versions without a major version update'. The SDK jumped from 0.0.x to 0.1.x to 0.6.0 to 0.7.x with no major version bump. Each jump contained breaking API changes.
fix
Pin to an exact version: pip install openrouter==0.7.11. Do not use unpinned installs in production.
affects: all
gotchaMultiple competing packages on PyPI share similar names: 'openrouter' (official), 'openrouter-client' (unofficial FastAPI wrapper), 'python-open-router' (unofficial async client). pip install openrouter-client or pip install python-open-router install the wrong package with different APIs.
fix
Only install 'openrouter' (the official SDK by OpenRouter). Verify with: pip show openrouter — author should be 'OpenRouter', license 'Apache-2.0'.
affects: all
gotchaNot using OpenRouter as a context manager leaves HTTPX client connections open (file handles, sockets). In long-running services or scripts that repeatedly instantiate OpenRouter(), this causes connection pool exhaustion.
fix
Always use: 'with OpenRouter(api_key=...) as client:' (sync) or 'async with OpenRouter(api_key=...) as client:' (async).
affects: all
gotchaOpenRouter model strings include the provider prefix: 'anthropic/claude-sonnet-4-20250514', not just 'claude-sonnet-4-20250514'. Using just the model name without provider prefix may fail or route to an unexpected provider.
fix
Always use 'provider/model-name' format. Browse available models at openrouter.ai/models.
affects: all
gotchaThe OpenAI SDK approach (setting base_url='https://openrouter.ai/api/v1') is often simpler and more stable than the native openrouter package, especially for teams already using the openai SDK. The OpenRouter API is OpenAI-compatible by design.
fix
For simple use cases, consider: from openai import OpenAI; client = OpenAI(api_key=OPENROUTER_API_KEY, base_url='https://openrouter.ai/api/v1'). No extra package needed.
affects: all
breakingThe SDK requires an API key for authentication, typically provided via the `OPENROUTER_API_KEY` environment variable. The `KeyError` indicates this environment variable was not found.
fix
Ensure the `OPENROUTER_API_KEY` environment variable is correctly set in your execution environment before running the application. For example: `export OPENROUTER_API_KEY='YOUR_KEY_HERE'` or pass it via your deployment system.
affects: all
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'openrouter'
This error occurs when the official `openrouter` Python SDK is not installed or when a different, unofficial package with a similar name is installed instead.
fix
Ensure you have installed the *official* `openrouter` package by OpenRouter: `pip install openrouter`
AuthenticationError: OpenrouterException - {"error":{"message":"No auth credentials found","code":401}}
This typically occurs when the OpenRouter API key is missing or incorrectly configured, often due to using the wrong environment variable name (e.g., `OPENAI_API_KEY` instead of `OPENROUTER_API_KEY`) or an invalid key.
fix
Set your OpenRouter API key as an environment variable named `OPENROUTER_API_KEY`. If using `python-dotenv`, ensure it's loaded. For direct client initialization, pass `api_key` explicitly. 

```python
import os
from openrouter import OpenRouter

# Ensure OPENROUTER_API_KEY is set in your environment or .env file
client = OpenRouter(api_key=os.getenv("OPENROUTER_API_KEY"))

# Or, if integrating with libraries like LiteLLM, ensure your .env has:
# OPENROUTER_API_KEY="your_api_key_here"
# OPENAI_API_BASE="https://openrouter.ai/api/v1"
```
pydantic_ai.exceptions.UnexpectedModelBehavior: Invalid response from OpenAI chat completions endpoint: 1 validation error for ChatCompletion choices.0.finish_reason Input should be 'stop', 'length', 'tool_calls', 'content_filter' or 'function_call' [type=literal_error, input_value='error', input_type=str]
OpenRouter sometimes returns a `finish_reason` value (like 'error') that is not recognized or expected by the Pydantic AI's internal OpenAI-compatible schema, leading to a validation failure.
fix
This issue often requires updates within the `pydantic-ai` library or handling specific OpenRouter error responses. For immediate workarounds, consider trying different models, adjusting request parameters (e.g., streaming settings), or implementing custom error parsing if directly using the OpenRouter API without strict Pydantic AI validation. Check for newer versions of `pydantic-ai` or `openrouter` that might have addressed this compatibility. A potential fix involves using `OpenRouterModel` from `pydantic_ai.models.openrouter` if available, or catching `UnexpectedModelBehavior` and inspecting the raw response if possible.
{'message': 'No endpoints found that support tool use. To learn more about provider routing, visit: https://openrouter.ai/docs/provider-routing', 'code': 404}
This error indicates that the specific model you selected does not support the 'tool use' (function calling) feature that your request is attempting to leverage.
fix
Choose an OpenRouter model that explicitly supports tool use. You can check the OpenRouter documentation or model listings to identify models compatible with function calling. 

```python
from openrouter import OpenRouter

client = OpenRouter(api_key=os.getenv("OPENROUTER_API_KEY"))

response = client.chat.completions.create(
    model="openrouter/your-tool-use-compatible-model", # e.g., 'openai/gpt-4o' or other models listed as supporting tools
    messages=[
        {"role": "user", "content": "What's the weather like in Paris?"}
    ],
    tools=[
        # Your tool definitions here
    ]
)
```
Upgrade
Version history
1.1.94latest on PyPI · released Aug 26, 2026
Audit
Dependencies
httpxrequiredRequired. Used for sync and async HTTP transport.
pydanticrequiredRequired. All request and response objects are Pydantic models.
Agent activity
39 hits · last 30 days
node
32
Amazon
1
OpenAI (training)
1
Resources
openrouter — pip install openrouter · libregistry