OpenRouter Python SDK

0.7.11 · active · verified Sat Feb 28

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.

Warnings

Install

Imports

Quickstart

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!'}]
)

view raw JSON →