Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .devcontainer/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@

<div align="center">
<a href="https://codespaces.new/OpenRouterTeam/python-sdk.git/tree/main"><img src="https://github.com/codespaces/badge.svg" /></a>
</div>
<br>

> **Remember to shutdown a GitHub Codespace when it is not in use!**

# Dev Containers Quick Start
Expand Down
13 changes: 8 additions & 5 deletions .speakeasy/gen.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,19 @@ id: cfd52247-6a25-4c6d-bbce-fe6fce0cd69d
management:
docChecksum: b1b97e85c6e3464e1fd6e2163c4ebc87
docVersion: 1.0.0
speakeasyVersion: 1.656.2
generationVersion: 2.753.6
releaseVersion: 0.0.15
configChecksum: ef777b42ca5f6690075cb13d061364fd
speakeasyVersion: 1.658.1
generationVersion: 2.755.6
releaseVersion: 0.0.16
configChecksum: bccceb456c96a46bcbe65fdff6bd5e1f
repoURL: https://github.com/OpenRouterTeam/python-sdk.git
installationURL: https://github.com/OpenRouterTeam/python-sdk.git
published: true
features:
python:
acceptHeaders: 3.0.0
additionalDependencies: 1.0.0
constsAndDefaults: 1.0.5
core: 5.23.6
core: 5.23.8
defaultEnabledRetries: 0.2.0
deprecations: 3.0.2
devContainers: 3.0.0
Expand Down Expand Up @@ -523,6 +525,7 @@ generatedFiles:
- docs/sdks/responses/README.md
- py.typed
- pyproject.toml
- scripts/prepare_readme.py
- scripts/publish.sh
- src/openrouter/__init__.py
- src/openrouter/_hooks/__init__.py
Expand Down
3 changes: 2 additions & 1 deletion .speakeasy/gen.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ generation:
generateNewTests: true
skipResponseBodyAssertions: false
python:
version: 0.0.15
version: 0.0.16
additionalDependencies:
dev: {}
main: {}
Expand Down Expand Up @@ -64,6 +64,7 @@ python:
webhooks: ""
inputModelSuffix: input
legacyPyright: false
license: ""
maxMethodParams: 999
methodArguments: infer-optional-args
moduleName: ""
Expand Down
3 changes: 2 additions & 1 deletion .speakeasy/workflow.lock
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
speakeasyVersion: 1.656.2
speakeasyVersion: 1.658.1
sources:
-OAS:
sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:08647b466c00989914e3a2436175152270f771f0a57d055f5bab14cc2d4be89e
sourceBlobDigest: sha256:53027ec57392d9617cc001ece83c2fe1aa6e5dbfd52d170381c34c33c6042c23
tags:
- latest
- speakeasy-sdk-regen-1763230596
targets:
open-router:
source: -OAS
Expand Down
249 changes: 249 additions & 0 deletions README-PYPI.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,249 @@
# OpenRouter SDK (Beta)

The [OpenRouter SDK](https://openrouter.ai/docs/sdks/python) is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to over 300 models across providers in an easy and type-safe way.

To learn more about how to use the OpenRouter SDK, check out our [API Reference](https://openrouter.ai/docs/sdks/python/reference) and [Documentation](https://openrouter.ai/docs/sdks/python).

<!-- No Summary [summary] -->

<!-- No Table of Contents [toc] -->

<!-- Start SDK Installation [installation] -->
## SDK Installation

> [!NOTE]
> **Python version upgrade policy**
>
> Once a Python version reaches its [official end of life date](https://devguide.python.org/versions/), 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.

```bash
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.

```bash
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.

```bash
poetry add openrouter
```

### Shell and script usage with `uv`

You can use this SDK in a Python shell with [uv](https://docs.astral.sh/uv/) and the `uvx` command that comes with it like so:

```shell
uvx --from openrouter python
```

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

```python
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.9"
# 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.
<!-- End SDK Installation [installation] -->

<!-- Start Requirements [requirements] -->
## Requirements

This SDK requires Python 3.9 or higher. For Python version support policy, see the SDK Installation section above.
<!-- End Requirements [requirements] -->

<!-- Start IDE Support [idesupport] -->
## 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.

- [PyCharm Pydantic Plugin](https://docs.pydantic.dev/latest/integrations/pycharm/)
<!-- End IDE Support [idesupport] -->

<!-- No SDK Example Usage [usage] -->
## SDK Usage

```python
# 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)
```

</br>

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

```python
# 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())
```

<!-- No Authentication [security] -->

<!-- No Available Resources and Operations [operations] -->

<!-- No Standalone functions [standalone-funcs] -->

<!-- No React hooks with TanStack Query [react-query] -->

<!-- No Server-sent event streaming [eventstream] -->

<!-- No Retries [retries] -->

<!-- No Error Handling [errors] -->

<!-- No Server Selection [server] -->

<!-- No Custom HTTP Client [http-client] -->

<!-- Start Resource Management [resource-management] -->
## 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][context-manager] and reuse it across the application.

[context-manager]: https://docs.python.org/3/reference/datamodel.html#context-managers

```python
from openrouter import OpenRouter
import os
def main():

with OpenRouter(
api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:
# Rest of application here...


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

async with OpenRouter(
api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:
# Rest of application here...
```
<!-- End Resource Management [resource-management] -->

<!-- Start Debugging [debug] -->
## 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.
```python
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.
<!-- End Debugging [debug] -->

<!-- Placeholder for Future Speakeasy SDK Sections -->

# 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:

```bash
cp .env.example .env
```

2. Edit `.env` and add your OpenRouter API key:

```bash
OPENROUTER_API_KEY=your_api_key_here
```

3. Run the tests:

```bash
pytest
```

## Maturity

This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage
to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally
looking for the latest version.
11 changes: 11 additions & 0 deletions RELEASES.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@


## 2025-11-15 18:16:18
### Changes
Based on:
- OpenAPI Doc
- Speakeasy CLI 1.658.1 (2.755.6) https://github.com/speakeasy-api/speakeasy
### Generated
- [python v0.0.16] .
### Releases
- [PyPI v0.0.16] https://pypi.org/project/openrouter/0.0.16 - .
5 changes: 3 additions & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
[project]
name = "openrouter"
version = "0.0.15"
version = "0.0.16"
description = "Official Python Client SDK for OpenRouter."
authors = [{ name = "OpenRouter" },]
readme = "README.md"
readme = "README-PYPI.md"
requires-python = ">=3.9.2"
dependencies = [
"httpcore >=1.0.9",
"httpx >=0.28.1",
"pydantic >=2.11.2",
]
urls.repository = "https://github.com/OpenRouterTeam/python-sdk.git"

[dependency-groups]
dev = [
Expand Down
35 changes: 35 additions & 0 deletions scripts/prepare_readme.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

import re
import shutil

try:
with open("README.md", "r", encoding="utf-8") as rh:
readme_contents = rh.read()
GITHUB_URL = "https://github.com/OpenRouterTeam/python-sdk.git"
GITHUB_URL = (
GITHUB_URL[: -len(".git")] if GITHUB_URL.endswith(".git") else GITHUB_URL
)
REPO_SUBDIR = ""
# links on PyPI should have absolute URLs
readme_contents = re.sub(
r"(\[[^\]]+\]\()((?!https?:)[^\)]+)(\))",
lambda m: m.group(1)
+ GITHUB_URL
+ "/blob/master/"
+ REPO_SUBDIR
+ m.group(2)
+ m.group(3),
readme_contents,
)

with open("README-PYPI.md", "w", encoding="utf-8") as wh:
wh.write(readme_contents)
except Exception as e:
try:
print("Failed to rewrite README.md to README-PYPI.md, copying original instead")
print(e)
shutil.copyfile("README.md", "README-PYPI.md")
except Exception as ie:
print("Failed to copy README.md to README-PYPI.md")
print(ie)
2 changes: 2 additions & 0 deletions scripts/publish.sh
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#!/usr/bin/env bash

uv run python scripts/prepare_readme.py

uv build
uv publish --token $PYPI_TOKEN
Loading