Skip to main content

hero illustration

OpenRouter SDK

The OpenRouter SDK is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to 400+ models across providers in an easy and type-safe way.

The OpenRouter Python SDK is stable as of v1.0.

To learn more about how to use the OpenRouter SDK, check out our API Reference and Documentation.

SDK Installation

The SDK can be installed with uv, pip, or poetry package managers.

uv

uv is a fast Python package installer and resolver, designed as a drop-in replacement for pip and pip-tools. It's recommended for its speed and modern Python tooling capabilities.

uv add openrouter

PIP

PIP is the default package installer for Python, enabling easy installation and management of packages from PyPI via the command line.

pip install openrouter

Poetry

Poetry is a modern tool that simplifies dependency management and package publishing by using a single pyproject.toml file to handle project metadata and dependencies.

poetry add openrouter

Shell and script usage with uv

You can use this SDK in a Python shell with uv and the uvx command that comes with it like so:

uvx --from openrouter python

It's also possible to write a standalone Python script without needing to set up a whole project like so:

#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = [
#     "openrouter",
# ]
# ///

from openrouter import OpenRouter

sdk = OpenRouter(
  # SDK arguments
)

# Rest of script here...

Once that is saved to a file, you can run it with uv run script.py where script.py can be replaced with the actual file name.

Requirements

This SDK requires Python 3.10 or higher. For Python version support policy, see the SDK Installation section above.

IDE Support

PyCharm

Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.

SDK Usage

# Synchronous Example
from openrouter import OpenRouter
import os


with OpenRouter(
    api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:

    res = open_router.chat.send(messages=[
        {
            "role": "user",
            "content": "Hello, how are you?",
        },
    ], model="anthropic/claude-4.5-sonnet", provider={
        "zdr": True,
        "sort": "price",
    }, stream=True)

    for event in event_stream:
        # handle event
        print(event, flush=True)

The SDK includes native types for OpenRouter web search. For Chat Completions, pass the OpenRouter server tool in tools:

from openrouter import OpenRouter, components
import os


with OpenRouter(api_key=os.getenv("OPENROUTER_API_KEY", "")) as open_router:
    res = open_router.chat.send(
        model="openai/gpt-4o",
        messages=[{"role": "user", "content": "What changed in AI today?"}],
        tools=[
            components.OpenRouterWebSearchServerTool(
                type="openrouter:web_search",
                parameters=components.WebSearchConfig(
                    max_results=5,
                    search_context_size="medium",
                ),
            )
        ],
    )

For the Responses API, use the Responses server-tool type:

from openrouter import OpenRouter, components
import os


with OpenRouter(api_key=os.getenv("OPENROUTER_API_KEY", "")) as open_router:
    res = open_router.responses.send(
        model="openai/gpt-4o",
        input="What changed in AI today?",
        tools=[
            components.WebSearchServerToolOpenRouter(
                type="openrouter:web_search",
                parameters=components.WebSearchServerToolConfig(
                    max_results=5,
                    search_context_size="medium",
                ),
            )
        ],
        stream=False,
    )

The SDK also supports OpenRouter's web-search plugin via components.WebSearchPlugin(id="web", ...) for request shapes that accept plugins.

The same SDK client can also be used to make asynchronous requests by importing asyncio.

# Asynchronous Example
import asyncio
from openrouter import OpenRouter
import os

async def main():

    async with OpenRouter(
        api_key=os.getenv("OPENROUTER_API_KEY", ""),
    ) as open_router:

        res = await open_router.chat.send_async(messages=[
        {
            "role": "user",
            "content": "Hello, how are you?",
        },
    ], model="anthropic/claude-4.5-sonnet", provider={
        "zdr": True,
        "sort": "price",
    }, stream=True)

        async for event in event_stream:
            # handle event
            print(event, flush=True)

asyncio.run(main())

Pagination

Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the returned response object will have a Next method that can be called to pull down the next group of results. If the return value of Next is None, then there are no more pages to be fetched.

Here's an example of one such pagination call:

from openrouter import OpenRouter
import os


with OpenRouter(
    http_referer="<value>",
    x_open_router_title="<value>",
    x_open_router_categories="<value>",
    api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:

    res = open_router.batch.list()

    while res is not None:
        # Handle items

        res = res.next()

File uploads

Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.

from openrouter import OpenRouter
import os


with OpenRouter(
    http_referer="<value>",
    x_open_router_title="<value>",
    x_open_router_categories="<value>",
    api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:

    res = open_router.stt.create_transcription_multipart(model="openai/whisper-large-v3", file={
        "file_name": "example.file",
        "content": open("example.file", "rb"),
    }, language="en")

    # Handle response
    print(res)

Resource Management

The OpenRouter class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.

from openrouter import OpenRouter
import os
def main():

    with OpenRouter(
        http_referer="<value>",
        x_open_router_title="<value>",
        x_open_router_categories="<value>",
        api_key=os.getenv("OPENROUTER_API_KEY", ""),
    ) as open_router:
        # Rest of application here...


# Or when using async:
async def amain():

    async with OpenRouter(
        http_referer="<value>",
        x_open_router_title="<value>",
        x_open_router_categories="<value>",
        api_key=os.getenv("OPENROUTER_API_KEY", ""),
    ) as open_router:
        # Rest of application here...

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass your own logger class directly into your SDK.

from openrouter import OpenRouter
import logging

logging.basicConfig(level=logging.DEBUG)
s = OpenRouter(debug_logger=logging.getLogger("openrouter"))

You can also enable a default debug logger by setting an environment variable OPENROUTER_DEBUG to true.

Development

Running Tests

To run the test suite, you'll need to set up your environment with an OpenRouter API key.

Local Development

  1. Copy the example environment file:

    cp .env.example .env
    
  2. Edit .env and add your OpenRouter API key:

    OPENROUTER_API_KEY=your_api_key_here
    
  3. Run the tests:

    pytest
    

Metadata

Release files for openrouter 1.3.161

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for openrouter 1.3.161
File Size Uploaded Provenance Actions
openrouter-1.3.161.tar.gz 675.6 kB Without provenance Details for openrouter-1.3.161.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for openrouter 1.3.161
File Interpreter ABI Platform Actions
openrouter-1.3.161-py3-none-any.whl Python 3 none any Details for openrouter-1.3.161-py3-none-any.whl

Total release size: 2.1 MB

Release files / openrouter-1.3.161.tar.gz

Download URL openrouter-1.3.161.tar.gz
Size 675.6 kB
Tags Source
SHA-256 checksum
How to use checksums
0dfdbbf2f16e8ddce478b0305ceea7b8adad68f58b680c8a0073003a9c72d95a
BLAKE2b-256 checksum
How to use checksums
dd9c32ad4c5092d8376089937ee18766a7c2bf5da6aa436aed9f8b673a21dd4f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / openrouter-1.3.161-py3-none-any.whl

Download URL openrouter-1.3.161-py3-none-any.whl
Size 1.5 MB
Tags Python 3
SHA-256 checksum
How to use checksums
0e42938e3622b91fee55f4f340a4fce27fc0713eac166898156428ce456a7af4
BLAKE2b-256 checksum
How to use checksums
44c66d101b246072d697f6a5551295d25d6ae52abc6c991f272ec68018291d51
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"22.04","id":"jammy","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for openrouter 1.3.161

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

1.3.161 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page