Skip to main content

Official Python Client SDK for OpenRouter.

Project description

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

[!NOTE] Python version upgrade policy

Once a Python version reaches its official end of life date, a 3-month grace period is provided for users to upgrade. Following this grace period, the minimum python version supported in the SDK will be updated.

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 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.byok.list(offset=0, limit=50)

    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.

[!TIP]

For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files.

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(file={
        "file_name": "example.file",
        "content": open("example.file", "rb"),
    }, model="openai/whisper-large-v3", 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
    

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

openrouter-1.0.3.tar.gz (381.0 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

openrouter-1.0.3-py3-none-any.whl (838.0 kB view details)

Uploaded Python 3

File details

Details for the file openrouter-1.0.3.tar.gz.

File metadata

  • Download URL: openrouter-1.0.3.tar.gz
  • Upload date:
  • Size: 381.0 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.30 {"installer":{"name":"uv","version":"0.11.30","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}

File hashes

Hashes for openrouter-1.0.3.tar.gz
Algorithm Hash digest
SHA256 99f0f27bb3a2a2881c3fc52dc6a98de0fee539dd0ea75a1b3d227c85ed6236b0
MD5 251aaa856ca44c3d1b2df6aa3c94390f
BLAKE2b-256 4a312f880a0bb7ecaf3fda6d3ccb7bd3b4cb0367981618f4a10ce773908bbb4d

See more details on using hashes here.

File details

Details for the file openrouter-1.0.3-py3-none-any.whl.

File metadata

  • Download URL: openrouter-1.0.3-py3-none-any.whl
  • Upload date:
  • Size: 838.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.11.30 {"installer":{"name":"uv","version":"0.11.30","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}

File hashes

Hashes for openrouter-1.0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 940eb3a98d02741f0c0dff3f08c4ddb9629d712cabb1a4b0701aa05a52fe6531
MD5 b50382b35f8a7b6a76c98da4f7aada8e
BLAKE2b-256 0e9d86997ed3e1b934609119f24edd1fd222067a17a1a224329154f2c47603bc

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page