Compare commits

...
8 Commits
Author SHA1 Message Date
Matt AppersonandGitHub a1dae775cb chore: regenerate Python SDK v0.0.17 (#18) 2025-11-18 13:59:14 -05:00
Matt Apperson 10a76ba502 chore: regenerate SDK to v0.0.19 with speakeasy 2025-11-18 13:58:48 -05:00
Matt Apperson f4ffd51f40 chore: regenerate Python SDK v0.0.17
Update Python SDK with Speakeasy regeneration:
- Bump version from 0.0.16 to 0.0.17
- Refactor OpenAPI schema definitions:
  - Inline BigNumberUnion type into usage sites
  - Reorganize ProviderName enum location
  - Simplify provider order/only/ignore array types
  - Add plugins schema definitions
- Update gen.lock with new configChecksum
2025-11-18 13:56:41 -05:00
Matt AppersonandGitHub 20c63f6f13 feat: add monorepo sync notification workflow (#17) 2025-11-15 16:16:37 -05:00
Matt Apperson 0f9cb9787a feat: add monorepo sync notification workflow
Automatically notifies openrouter-web monorepo when changes are pushed to main.
This triggers the subtree sync workflow to create a PR with updates.

Requires MONOREPO_SYNC_TOKEN secret to be configured.
2025-11-15 15:53:15 -05:00
Matt AppersonandGitHub 6c5dfcfb2b chore: 🐝 Update SDK - Generate 0.0.16 (#16) 2025-11-15 13:50:49 -05:00
speakeasy-github[bot]andspeakeasy-bot afbf99e8bf empty commit to trigger [run-tests] workflow 2025-11-15 18:17:41 +00:00
speakeasybot 6895d9d45b ci: regenerated with OpenAPI Doc , Speakeasy CLI 1.658.1 2025-11-15 18:17:32 +00:00
77 changed files with 9609 additions and 699 deletions
+5
View File
@@ -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
+46
View File
@@ -0,0 +1,46 @@
name: Notify Monorepo of Changes
on:
push:
branches:
- main
jobs:
notify-monorepo:
runs-on: ubuntu-latest
steps:
- name: Send repository dispatch to monorepo
run: |
# Determine which event type to send based on repository name
REPO_NAME="${GITHUB_REPOSITORY#*/}" # Gets 'python-sdk' from 'OpenRouterTeam/python-sdk'
case "$REPO_NAME" in
"typescript-sdk")
EVENT_TYPE="sync-typescript-sdk"
;;
"python-sdk")
EVENT_TYPE="sync-python-sdk"
;;
"ai-sdk-provider")
EVENT_TYPE="sync-ai-sdk-provider"
;;
"cli")
EVENT_TYPE="sync-cli"
;;
*)
echo "Unknown repository: $REPO_NAME"
exit 1
;;
esac
echo "Sending repository_dispatch event: $EVENT_TYPE"
curl -L \
-X POST \
-H "Accept: application/vnd.github+json" \
-H "Authorization: Bearer ${{ secrets.MONOREPO_SYNC_TOKEN }}" \
-H "X-GitHub-Api-Version: 2022-11-28" \
https://api.github.com/repos/OpenRouterTeam/openrouter-web/dispatches \
-d "{\"event_type\":\"$EVENT_TYPE\",\"client_payload\":{\"repository\":\"$GITHUB_REPOSITORY\",\"ref\":\"$GITHUB_REF\",\"sha\":\"$GITHUB_SHA\"}}"
echo "✅ Notification sent to monorepo"
+24 -15
View File
@@ -1,19 +1,21 @@
lockVersion: 2.0.0
id: cfd52247-6a25-4c6d-bbce-fe6fce0cd69d
management:
docChecksum: b1b97e85c6e3464e1fd6e2163c4ebc87
docChecksum: 4cc4a9d9115d0eca9a5eb4786505579d
docVersion: 1.0.0
speakeasyVersion: 1.656.2
generationVersion: 2.753.6
releaseVersion: 0.0.15
configChecksum: ef777b42ca5f6690075cb13d061364fd
speakeasyVersion: 1.658.2
generationVersion: 2.755.9
releaseVersion: 0.0.19
configChecksum: 834d5c1cea368e35ab6535ffb2bf9e7a
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.9
defaultEnabledRetries: 0.2.0
deprecations: 3.0.2
devContainers: 3.0.0
@@ -69,6 +71,8 @@ generatedFiles:
- docs/components/chatmessagecontentitemimagedetail.md
- docs/components/chatmessagecontentitemtext.md
- docs/components/chatmessagecontentitemvideo.md
- docs/components/chatmessagecontentitemvideoinputvideo.md
- docs/components/chatmessagecontentitemvideovideourl.md
- docs/components/chatmessagetokenlogprob.md
- docs/components/chatmessagetokenlogprobs.md
- docs/components/chatmessagetoolcall.md
@@ -303,6 +307,7 @@ generatedFiles:
- docs/components/provider.md
- docs/components/providername.md
- docs/components/provideroverloadedresponseerrordata.md
- docs/components/providersort.md
- docs/components/publicendpoint.md
- docs/components/publicendpointquantization.md
- docs/components/publicpricing.md
@@ -373,7 +378,6 @@ generatedFiles:
- docs/components/security.md
- docs/components/servicetier.md
- docs/components/serviceunavailableresponseerrordata.md
- docs/components/sort.md
- docs/components/streamoptions.md
- docs/components/systemmessage.md
- docs/components/systemmessagecontent.md
@@ -412,7 +416,8 @@ generatedFiles:
- docs/components/usermessage.md
- docs/components/usermessagecontent.md
- docs/components/variables.md
- docs/components/videourl.md
- docs/components/videourl1.md
- docs/components/videourl2.md
- docs/components/websearchpreviewtooluserlocation.md
- docs/components/websearchpreviewtooluserlocationtype.md
- docs/components/websearchstatus.md
@@ -434,6 +439,9 @@ generatedFiles:
- docs/models/utils/retryconfig.md
- docs/operations/apitype.md
- docs/operations/calldata.md
- docs/operations/content.md
- docs/operations/contentimageurl.md
- docs/operations/contenttext.md
- docs/operations/createauthkeyscodecodechallengemethod.md
- docs/operations/createauthkeyscodedata.md
- docs/operations/createauthkeyscoderequest.md
@@ -452,13 +460,10 @@ generatedFiles:
- docs/operations/createkeysresponse.md
- docs/operations/createresponsesresponse.md
- docs/operations/createresponsesresponsebody.md
- docs/operations/datacollection.md
- docs/operations/deletekeysrequest.md
- docs/operations/deletekeysresponse.md
- docs/operations/embedding.md
- docs/operations/encodingformat.md
- docs/operations/encodingformatbase64.md
- docs/operations/encodingformatfloat.md
- docs/operations/exchangeauthcodeforapikeycodechallengemethod.md
- docs/operations/exchangeauthcodeforapikeyrequest.md
- docs/operations/exchangeauthcodeforapikeyresponse.md
@@ -480,7 +485,9 @@ generatedFiles:
- docs/operations/getuseractivityrequest.md
- docs/operations/getuseractivityresponse.md
- docs/operations/ignore.md
- docs/operations/imageurl.md
- docs/operations/input.md
- docs/operations/inputunion.md
- docs/operations/listdata.md
- docs/operations/listendpointsrequest.md
- docs/operations/listendpointsresponse.md
@@ -498,9 +505,10 @@ generatedFiles:
- docs/operations/order.md
- docs/operations/ratelimit.md
- docs/operations/sendchatcompletionrequestresponse.md
- docs/operations/sort.md
- docs/operations/supportedparameter.md
- docs/operations/transferintent.md
- docs/operations/typeimageurl.md
- docs/operations/typetext.md
- docs/operations/updatekeysdata.md
- docs/operations/updatekeyslimitreset.md
- docs/operations/updatekeysrequest.md
@@ -523,6 +531,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
@@ -540,7 +549,6 @@ generatedFiles:
- src/openrouter/components/assistantmessage.py
- src/openrouter/components/badgatewayresponseerrordata.py
- src/openrouter/components/badrequestresponseerrordata.py
- src/openrouter/components/chatcompletionfinishreason.py
- src/openrouter/components/chaterror.py
- src/openrouter/components/chatgenerationparams.py
- src/openrouter/components/chatgenerationtokenusage.py
@@ -554,7 +562,6 @@ generatedFiles:
- src/openrouter/components/chatmessagetoolcall.py
- src/openrouter/components/chatresponse.py
- src/openrouter/components/chatresponsechoice.py
- src/openrouter/components/chatstreamingchoice.py
- src/openrouter/components/chatstreamingmessagechunk.py
- src/openrouter/components/chatstreamingmessagetoolcall.py
- src/openrouter/components/chatstreamingresponsechunk.py
@@ -565,6 +572,7 @@ generatedFiles:
- src/openrouter/components/completionresponse.py
- src/openrouter/components/completionusage.py
- src/openrouter/components/createchargerequest.py
- src/openrouter/components/datacollection.py
- src/openrouter/components/defaultparameters.py
- src/openrouter/components/edgenetworktimeoutresponseerrordata.py
- src/openrouter/components/endpointstatus.py
@@ -634,6 +642,7 @@ generatedFiles:
- src/openrouter/components/perrequestlimits.py
- src/openrouter/components/providername.py
- src/openrouter/components/provideroverloadedresponseerrordata.py
- src/openrouter/components/providersort.py
- src/openrouter/components/publicendpoint.py
- src/openrouter/components/publicpricing.py
- src/openrouter/components/quantization.py
@@ -830,7 +839,7 @@ examples:
createEmbeddings:
speakeasy-default-create-embeddings:
requestBody:
application/json: {"input": "<value>", "model": "Taurus", "provider": {"data_collection": "deny", "zdr": true, "enforce_distillable_text": true, "order": ["OpenAI"], "only": ["OpenAI"], "ignore": ["OpenAI"], "quantizations": ["fp16"], "sort": "price"}}
application/json: {"input": "<value>", "model": "Taurus", "provider": {"data_collection": "allow", "zdr": true, "enforce_distillable_text": true, "order": ["OpenAI"], "only": ["OpenAI"], "ignore": ["OpenAI"], "quantizations": ["fp16"], "sort": "price"}}
responses:
"200":
application/json: {"object": "list", "data": [], "model": "Land Cruiser"}
+2 -1
View File
@@ -30,7 +30,7 @@ generation:
generateNewTests: true
skipResponseBodyAssertions: false
python:
version: 0.0.15
version: 0.0.19
additionalDependencies:
dev: {}
main: {}
@@ -64,6 +64,7 @@ python:
webhooks: ""
inputModelSuffix: input
legacyPyright: false
license: Apache-2.0
maxMethodParams: 999
methodArguments: infer-optional-args
moduleName: ""
File diff suppressed because it is too large Load Diff
+135 -119
View File
@@ -1067,6 +1067,7 @@ components:
- medium
- low
- minimal
- none
x-speakeasy-unknown-values: allow
ReasoningSummaryVerbosity:
type: string
@@ -3239,6 +3240,7 @@ components:
- openai-responses-v1
- xai-responses-v1
- anthropic-claude-v1
- google-gemini-v1
x-speakeasy-unknown-values: allow
example:
type: reasoning
@@ -3440,47 +3442,44 @@ components:
- reasoning.encrypted_content
- code_interpreter_call.outputs
x-speakeasy-unknown-values: allow
DataCollection:
type: string
nullable: true
enum:
- deny
- allow
description: >-
Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
example: allow
x-speakeasy-unknown-values: allow
ProviderName:
type: string
enum:
- AnyScale
- Cent-ML
- HuggingFace
- Hyperbolic 2
- Lepton
- Lynn 2
- Lynn
- Mancer
- Modal
- OctoAI
- Recursal
- Reflection
- Replicate
- SambaNova 2
- SF Compute
- Together 2
- 01.AI
- AI21
- AionLabs
- Alibaba
- Amazon Bedrock
- Anthropic
- Arcee
- AtlasCloud
- Atoma
- Avian
- Azure
- BaseTen
- Black Forest Labs
- Cerebras
- Chutes
- Cirrascale
- Clarifai
- Cloudflare
- Cohere
- CrofAI
- Crusoe
- DeepInfra
- DeepSeek
- Enfer
- Featherless
- Fireworks
- Friendli
@@ -3493,12 +3492,8 @@ components:
- InferenceNet
- Infermatic
- Inflection
- InoCloud
- Kluster
- Lambda
- Liquid
- Mancer 2
- Meta
- Minimax
- ModelRun
- Mistral
@@ -3508,7 +3503,6 @@ components:
- NCompass
- Nebius
- NextBit
- Nineteen
- Novita
- Nvidia
- OpenAI
@@ -3523,7 +3517,6 @@ components:
- Switchpoint
- Targon
- Together
- Ubicloud
- Venice
- WandB
- xAI
@@ -3545,6 +3538,17 @@ components:
- unknown
example: fp16
x-speakeasy-unknown-values: allow
ProviderSort:
type: string
nullable: true
enum:
- price
- throughput
- latency
description: >-
The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed.
example: price
x-speakeasy-unknown-values: allow
BigNumberUnion:
anyOf:
- type: number
@@ -3683,20 +3687,7 @@ components:
description: >-
Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.
data_collection:
type: string
nullable: true
enum:
- deny
- allow
example: deny
description: >
Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
x-speakeasy-unknown-values: allow
$ref: '#/components/schemas/DataCollection'
zdr:
type: boolean
nullable: true
@@ -3743,16 +3734,7 @@ components:
$ref: '#/components/schemas/Quantization'
description: A list of quantization levels to filter the provider by.
sort:
type: string
nullable: true
enum:
- price
- throughput
- latency
example: price
description: >-
The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed.
x-speakeasy-unknown-values: allow
$ref: '#/components/schemas/ProviderSort'
max_price:
type: object
properties:
@@ -3984,6 +3966,8 @@ components:
$ref: '#/components/schemas/BigNumberUnion'
image:
$ref: '#/components/schemas/BigNumberUnion'
image_token:
$ref: '#/components/schemas/BigNumberUnion'
image_output:
$ref: '#/components/schemas/BigNumberUnion'
audio:
@@ -4428,6 +4412,8 @@ components:
$ref: '#/components/schemas/BigNumberUnion'
image:
$ref: '#/components/schemas/BigNumberUnion'
image_token:
$ref: '#/components/schemas/BigNumberUnion'
image_output:
$ref: '#/components/schemas/BigNumberUnion'
audio:
@@ -4611,10 +4597,6 @@ components:
status: default
uptime_last_30m: 99.5
supports_implicit_caching: true
__schema0:
anyOf:
- $ref: '#/components/schemas/ChatCompletionFinishReason'
- type: 'null'
ModelName:
type: string
ChatMessageContentItemText:
@@ -4680,21 +4662,38 @@ components:
- type
- input_audio
ChatMessageContentItemVideo:
oneOf:
- type: object
properties:
type:
type: string
const: input_video
video_url:
type: object
properties:
url:
type: string
required:
- url
required:
- type
- video_url
- type: object
properties:
type:
type: string
const: video_url
video_url:
type: object
properties:
url:
type: string
required:
- url
required:
- type
- video_url
type: object
properties:
type:
type: string
const: input_video
video_url:
type: object
properties:
url:
type: string
required:
- url
required:
- type
- video_url
ChatMessageContentItem:
oneOf:
- $ref: '#/components/schemas/ChatMessageContentItemText'
@@ -4709,6 +4708,7 @@ components:
image_url: '#/components/schemas/ChatMessageContentItemImage'
input_audio: '#/components/schemas/ChatMessageContentItemAudio'
input_video: '#/components/schemas/ChatMessageContentItemVideo'
video_url: '#/components/schemas/ChatMessageContentItemVideo'
ChatMessageToolCall:
type: object
properties:
@@ -4832,14 +4832,16 @@ components:
- prompt_tokens
- total_tokens
ChatCompletionFinishReason:
type: string
enum:
- tool_calls
- stop
- length
- content_filter
- error
x-speakeasy-unknown-values: allow
anyOf:
- type: string
enum:
- tool_calls
- stop
- length
- content_filter
- error
x-speakeasy-unknown-values: allow
- type: 'null'
JSONSchemaConfig:
type: object
properties:
@@ -5111,6 +5113,7 @@ components:
anyOf:
- type: string
enum:
- none
- minimal
- low
- medium
@@ -5197,7 +5200,7 @@ components:
type: object
properties:
finish_reason:
$ref: '#/components/schemas/__schema0'
$ref: '#/components/schemas/ChatCompletionFinishReason'
index:
type: number
message:
@@ -5258,7 +5261,7 @@ components:
delta:
$ref: '#/components/schemas/ChatStreamingMessageChunk'
finish_reason:
$ref: '#/components/schemas/__schema0'
$ref: '#/components/schemas/ChatCompletionFinishReason'
index:
type: number
logprobs:
@@ -5998,8 +6001,57 @@ paths:
type: array
items:
type: number
- type: array
items:
type: object
properties:
content:
type: array
items:
oneOf:
- type: object
properties:
type:
type: string
enum:
- text
text:
type: string
required:
- type
- text
- type: object
properties:
type:
type: string
enum:
- image_url
image_url:
type: object
properties:
url:
type: string
required:
- url
required:
- type
- image_url
required:
- content
model:
type: string
encoding_format:
type: string
enum:
- float
- base64
x-speakeasy-unknown-values: allow
dimensions:
type: integer
minimum: 0
exclusiveMinimum: true
user:
type: string
provider:
type: object
properties:
@@ -6019,20 +6071,7 @@ paths:
description: >-
Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest.
data_collection:
type: string
nullable: true
enum:
- deny
- allow
example: deny
description: >
Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
x-speakeasy-unknown-values: allow
$ref: '#/components/schemas/DataCollection'
zdr:
type: boolean
nullable: true
@@ -6079,16 +6118,7 @@ paths:
$ref: '#/components/schemas/Quantization'
description: A list of quantization levels to filter the provider by.
sort:
type: string
nullable: true
enum:
- price
- throughput
- latency
example: price
description: >-
The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed.
x-speakeasy-unknown-values: allow
$ref: '#/components/schemas/ProviderSort'
max_price:
type: object
properties:
@@ -6105,15 +6135,7 @@ paths:
additionalProperties: false
description: >-
The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion.
encoding_format:
anyOf:
- type: string
enum:
- float
- type: string
enum:
- base64
user:
input_type:
type: string
required:
- input
@@ -6709,22 +6731,21 @@ paths:
- Alibaba
- Amazon Bedrock
- Anthropic
- Arcee
- AtlasCloud
- Atoma
- Avian
- Azure
- BaseTen
- Black Forest Labs
- Cerebras
- Chutes
- Cirrascale
- Clarifai
- Cloudflare
- Cohere
- CrofAI
- Crusoe
- DeepInfra
- DeepSeek
- Enfer
- Featherless
- Fireworks
- Friendli
@@ -6737,11 +6758,8 @@ paths:
- InferenceNet
- Infermatic
- Inflection
- Kluster
- Lambda
- Liquid
- Mancer 2
- Meta
- Minimax
- ModelRun
- Mistral
@@ -6751,7 +6769,6 @@ paths:
- NCompass
- Nebius
- NextBit
- Nineteen
- Novita
- Nvidia
- OpenAI
@@ -6766,7 +6783,6 @@ paths:
- Switchpoint
- Targon
- Together
- Ubicloud
- Venice
- WandB
- xAI
+5 -5
View File
@@ -1,17 +1,17 @@
speakeasyVersion: 1.656.2
speakeasyVersion: 1.658.2
sources:
-OAS:
sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:08647b466c00989914e3a2436175152270f771f0a57d055f5bab14cc2d4be89e
sourceBlobDigest: sha256:53027ec57392d9617cc001ece83c2fe1aa6e5dbfd52d170381c34c33c6042c23
sourceRevisionDigest: sha256:fc0c90dc8ebb69ef4a571e4e63dcd7f8f33c3254c17ad2583b628fbbf3d1ac05
sourceBlobDigest: sha256:635d63fd18db468c1dcc23700382af788de76594ba3b8292fae9b14c0e5c22c4
tags:
- latest
targets:
open-router:
source: -OAS
sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:08647b466c00989914e3a2436175152270f771f0a57d055f5bab14cc2d4be89e
sourceBlobDigest: sha256:53027ec57392d9617cc001ece83c2fe1aa6e5dbfd52d170381c34c33c6042c23
sourceRevisionDigest: sha256:fc0c90dc8ebb69ef4a571e4e63dcd7f8f33c3254c17ad2583b628fbbf3d1ac05
sourceBlobDigest: sha256:635d63fd18db468c1dcc23700382af788de76594ba3b8292fae9b14c0e5c22c4
workflow:
workflowVersion: 1.0.0
speakeasyVersion: latest
+249
View File
@@ -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
View File
@@ -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 - .
+2 -2
View File
@@ -49,7 +49,7 @@ with OpenRouter(
},
},
}, service_tier="auto", truncation="auto", stream=False, provider={
"data_collection": "deny",
"data_collection": "allow",
"zdr": True,
"enforce_distillable_text": True,
"order": [
@@ -127,7 +127,7 @@ async def main():
},
},
}, service_tier="auto", truncation="auto", stream=False, provider={
"data_collection": "deny",
"data_collection": "allow",
"zdr": True,
"enforce_distillable_text": True,
"order": [
@@ -27,3 +27,9 @@ value: components.ChatMessageContentItemAudio = /* values here */
value: components.ChatMessageContentItemVideo = /* values here */
```
### `components.ChatMessageContentItemVideo`
```python
value: components.ChatMessageContentItemVideo = /* values here */
```
+13 -5
View File
@@ -1,9 +1,17 @@
# ChatMessageContentItemVideo
## Fields
## Supported Types
### `components.ChatMessageContentItemVideoInputVideo`
```python
value: components.ChatMessageContentItemVideoInputVideo = /* values here */
```
### `components.ChatMessageContentItemVideoVideoURL`
```python
value: components.ChatMessageContentItemVideoVideoURL = /* values here */
```
| Field | Type | Required | Description |
| ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ |
| `type` | *Literal["input_video"]* | :heavy_check_mark: | N/A |
| `video_url` | [components.VideoURL](../components/videourl.md) | :heavy_check_mark: | N/A |
@@ -0,0 +1,9 @@
# ChatMessageContentItemVideoInputVideo
## Fields
| Field | Type | Required | Description |
| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- |
| `type` | *Literal["input_video"]* | :heavy_check_mark: | N/A |
| `video_url` | [components.VideoURL1](../components/videourl1.md) | :heavy_check_mark: | N/A |
@@ -0,0 +1,9 @@
# ChatMessageContentItemVideoVideoURL
## Fields
| Field | Type | Required | Description |
| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- |
| `type` | *Literal["video_url"]* | :heavy_check_mark: | N/A |
| `video_url` | [components.VideoURL2](../components/videourl2.md) | :heavy_check_mark: | N/A |
+1 -1
View File
@@ -2,8 +2,8 @@
Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
- deny: use only providers which do not collect user data.
## Values
+1
View File
@@ -5,6 +5,7 @@
| Name | Value |
| --------- | --------- |
| `NONE` | none |
| `MINIMAL` | minimal |
| `LOW` | low |
| `MEDIUM` | medium |
@@ -8,4 +8,5 @@
| `HIGH` | high |
| `MEDIUM` | medium |
| `LOW` | low |
| `MINIMAL` | minimal |
| `MINIMAL` | minimal |
| `NONE` | none |
@@ -8,4 +8,5 @@
| `UNKNOWN` | unknown |
| `OPENAI_RESPONSES_V1` | openai-responses-v1 |
| `XAI_RESPONSES_V1` | xai-responses-v1 |
| `ANTHROPIC_CLAUDE_V1` | anthropic-claude-v1 |
| `ANTHROPIC_CLAUDE_V1` | anthropic-claude-v1 |
| `GOOGLE_GEMINI_V1` | google-gemini-v1 |
+1
View File
@@ -9,6 +9,7 @@
| `completion` | *Any* | :heavy_check_mark: | A value in string or number format that is a large number |
| `request` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `image` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `image_token` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `image_output` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `audio` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `input_audio_cache` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
+2 -2
View File
@@ -9,12 +9,12 @@ When multiple model providers are available, optionally indicate your routing pr
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `allow_fallbacks` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to allow backup providers to serve requests<br/>- true: (default) when the primary provider (or your custom providers in "order") is unavailable, use the next best provider.<br/>- false: use only the primary/custom provider, and return the upstream error if it's unavailable.<br/> | |
| `require_parameters` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest. | |
| `data_collection` | [OptionalNullable[components.DataCollection]](../components/datacollection.md) | :heavy_minus_sign: | Data collection setting. If no available model provider meets the requirement, your request will return an error.<br/>- allow: (default) allow providers which store user data non-transiently and may train on it<br/>- deny: use only providers which do not collect user data.<br/> | deny |
| `data_collection` | [OptionalNullable[components.DataCollection]](../components/datacollection.md) | :heavy_minus_sign: | Data collection setting. If no available model provider meets the requirement, your request will return an error.<br/>- allow: (default) allow providers which store user data non-transiently and may train on it<br/><br/>- deny: use only providers which do not collect user data. | allow |
| `zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used. | true |
| `enforce_distillable_text` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used. | true |
| `order` | List[[components.Order](../components/order.md)] | :heavy_minus_sign: | An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message. | |
| `only` | List[[components.Only](../components/only.md)] | :heavy_minus_sign: | List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request. | |
| `ignore` | List[[components.Ignore](../components/ignore.md)] | :heavy_minus_sign: | List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request. | |
| `quantizations` | List[[components.Quantization](../components/quantization.md)] | :heavy_minus_sign: | A list of quantization levels to filter the provider by. | |
| `sort` | [OptionalNullable[components.Sort]](../components/sort.md) | :heavy_minus_sign: | The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. | price |
| `sort` | [OptionalNullable[components.ProviderSort]](../components/providersort.md) | :heavy_minus_sign: | The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. | price |
| `max_price` | [Optional[components.MaxPrice]](../components/maxprice.md) | :heavy_minus_sign: | The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion. | |
+64 -88
View File
@@ -3,91 +3,67 @@
## Values
| Name | Value |
| ------------------ | ------------------ |
| `ANY_SCALE` | AnyScale |
| `CENT_ML` | Cent-ML |
| `HUGGING_FACE` | HuggingFace |
| `HYPERBOLIC_2` | Hyperbolic 2 |
| `LEPTON` | Lepton |
| `LYNN_2` | Lynn 2 |
| `LYNN` | Lynn |
| `MANCER` | Mancer |
| `MODAL` | Modal |
| `OCTO_AI` | OctoAI |
| `RECURSAL` | Recursal |
| `REFLECTION` | Reflection |
| `REPLICATE` | Replicate |
| `SAMBA_NOVA_2` | SambaNova 2 |
| `SF_COMPUTE` | SF Compute |
| `TOGETHER_2` | Together 2 |
| `ONE_DOT_AI` | 01.AI |
| `AI21` | AI21 |
| `AION_LABS` | AionLabs |
| `ALIBABA` | Alibaba |
| `AMAZON_BEDROCK` | Amazon Bedrock |
| `ANTHROPIC` | Anthropic |
| `ATLAS_CLOUD` | AtlasCloud |
| `ATOMA` | Atoma |
| `AVIAN` | Avian |
| `AZURE` | Azure |
| `BASE_TEN` | BaseTen |
| `CEREBRAS` | Cerebras |
| `CHUTES` | Chutes |
| `CIRRASCALE` | Cirrascale |
| `CLARIFAI` | Clarifai |
| `CLOUDFLARE` | Cloudflare |
| `COHERE` | Cohere |
| `CROF_AI` | CrofAI |
| `CRUSOE` | Crusoe |
| `DEEP_INFRA` | DeepInfra |
| `DEEP_SEEK` | DeepSeek |
| `ENFER` | Enfer |
| `FEATHERLESS` | Featherless |
| `FIREWORKS` | Fireworks |
| `FRIENDLI` | Friendli |
| `GMI_CLOUD` | GMICloud |
| `GOOGLE` | Google |
| `GOOGLE_AI_STUDIO` | Google AI Studio |
| `GROQ` | Groq |
| `HYPERBOLIC` | Hyperbolic |
| `INCEPTION` | Inception |
| `INFERENCE_NET` | InferenceNet |
| `INFERMATIC` | Infermatic |
| `INFLECTION` | Inflection |
| `INO_CLOUD` | InoCloud |
| `KLUSTER` | Kluster |
| `LAMBDA` | Lambda |
| `LIQUID` | Liquid |
| `MANCER_2` | Mancer 2 |
| `META` | Meta |
| `MINIMAX` | Minimax |
| `MODEL_RUN` | ModelRun |
| `MISTRAL` | Mistral |
| `MODULAR` | Modular |
| `MOONSHOT_AI` | Moonshot AI |
| `MORPH` | Morph |
| `N_COMPASS` | NCompass |
| `NEBIUS` | Nebius |
| `NEXT_BIT` | NextBit |
| `NINETEEN` | Nineteen |
| `NOVITA` | Novita |
| `NVIDIA` | Nvidia |
| `OPEN_AI` | OpenAI |
| `OPEN_INFERENCE` | OpenInference |
| `PARASAIL` | Parasail |
| `PERPLEXITY` | Perplexity |
| `PHALA` | Phala |
| `RELACE` | Relace |
| `SAMBA_NOVA` | SambaNova |
| `SILICON_FLOW` | SiliconFlow |
| `STEALTH` | Stealth |
| `SWITCHPOINT` | Switchpoint |
| `TARGON` | Targon |
| `TOGETHER` | Together |
| `UBICLOUD` | Ubicloud |
| `VENICE` | Venice |
| `WAND_B` | WandB |
| `X_AI` | xAI |
| `Z_AI` | Z.AI |
| `FAKE_PROVIDER` | FakeProvider |
| Name | Value |
| ------------------- | ------------------- |
| `AI21` | AI21 |
| `AION_LABS` | AionLabs |
| `ALIBABA` | Alibaba |
| `AMAZON_BEDROCK` | Amazon Bedrock |
| `ANTHROPIC` | Anthropic |
| `ARCEE` | Arcee |
| `ATLAS_CLOUD` | AtlasCloud |
| `AVIAN` | Avian |
| `AZURE` | Azure |
| `BASE_TEN` | BaseTen |
| `BLACK_FOREST_LABS` | Black Forest Labs |
| `CEREBRAS` | Cerebras |
| `CHUTES` | Chutes |
| `CIRRASCALE` | Cirrascale |
| `CLARIFAI` | Clarifai |
| `CLOUDFLARE` | Cloudflare |
| `COHERE` | Cohere |
| `CRUSOE` | Crusoe |
| `DEEP_INFRA` | DeepInfra |
| `DEEP_SEEK` | DeepSeek |
| `FEATHERLESS` | Featherless |
| `FIREWORKS` | Fireworks |
| `FRIENDLI` | Friendli |
| `GMI_CLOUD` | GMICloud |
| `GOOGLE` | Google |
| `GOOGLE_AI_STUDIO` | Google AI Studio |
| `GROQ` | Groq |
| `HYPERBOLIC` | Hyperbolic |
| `INCEPTION` | Inception |
| `INFERENCE_NET` | InferenceNet |
| `INFERMATIC` | Infermatic |
| `INFLECTION` | Inflection |
| `LIQUID` | Liquid |
| `MANCER_2` | Mancer 2 |
| `MINIMAX` | Minimax |
| `MODEL_RUN` | ModelRun |
| `MISTRAL` | Mistral |
| `MODULAR` | Modular |
| `MOONSHOT_AI` | Moonshot AI |
| `MORPH` | Morph |
| `N_COMPASS` | NCompass |
| `NEBIUS` | Nebius |
| `NEXT_BIT` | NextBit |
| `NOVITA` | Novita |
| `NVIDIA` | Nvidia |
| `OPEN_AI` | OpenAI |
| `OPEN_INFERENCE` | OpenInference |
| `PARASAIL` | Parasail |
| `PERPLEXITY` | Perplexity |
| `PHALA` | Phala |
| `RELACE` | Relace |
| `SAMBA_NOVA` | SambaNova |
| `SILICON_FLOW` | SiliconFlow |
| `STEALTH` | Stealth |
| `SWITCHPOINT` | Switchpoint |
| `TARGON` | Targon |
| `TOGETHER` | Together |
| `VENICE` | Venice |
| `WAND_B` | WandB |
| `X_AI` | xAI |
| `Z_AI` | Z.AI |
| `FAKE_PROVIDER` | FakeProvider |
@@ -1,4 +1,4 @@
# Sort
# ProviderSort
The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed.
+1
View File
@@ -11,6 +11,7 @@ Pricing information for the model
| `completion` | *Any* | :heavy_check_mark: | A value in string or number format that is a large number |
| `request` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `image` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `image_token` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `image_output` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `audio` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
| `input_audio_cache` | *Optional[Any]* | :heavy_minus_sign: | A value in string or number format that is a large number |
+8
View File
@@ -0,0 +1,8 @@
# VideoURL1
## Fields
| Field | Type | Required | Description |
| ------------------ | ------------------ | ------------------ | ------------------ |
| `url` | *str* | :heavy_check_mark: | N/A |
+8
View File
@@ -0,0 +1,8 @@
# VideoURL2
## Fields
| Field | Type | Required | Description |
| ------------------ | ------------------ | ------------------ | ------------------ |
| `url` | *str* | :heavy_check_mark: | N/A |
+17
View File
@@ -0,0 +1,17 @@
# Content
## Supported Types
### `operations.ContentText`
```python
value: operations.ContentText = /* values here */
```
### `operations.ContentImageURL`
```python
value: operations.ContentImageURL = /* values here */
```
+9
View File
@@ -0,0 +1,9 @@
# ContentImageURL
## Fields
| Field | Type | Required | Description |
| -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- | -------------------------------------------------------- |
| `type` | [operations.TypeImageURL](../operations/typeimageurl.md) | :heavy_check_mark: | N/A |
| `image_url` | [operations.ImageURL](../operations/imageurl.md) | :heavy_check_mark: | N/A |
+9
View File
@@ -0,0 +1,9 @@
# ContentText
## Fields
| Field | Type | Required | Description |
| ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ |
| `type` | [operations.TypeText](../operations/typetext.md) | :heavy_check_mark: | N/A |
| `text` | *str* | :heavy_check_mark: | N/A |
+2 -2
View File
@@ -7,12 +7,12 @@
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `allow_fallbacks` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to allow backup providers to serve requests<br/>- true: (default) when the primary provider (or your custom providers in "order") is unavailable, use the next best provider.<br/>- false: use only the primary/custom provider, and return the upstream error if it's unavailable.<br/> | |
| `require_parameters` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest. | |
| `data_collection` | [OptionalNullable[operations.DataCollection]](../operations/datacollection.md) | :heavy_minus_sign: | Data collection setting. If no available model provider meets the requirement, your request will return an error.<br/>- allow: (default) allow providers which store user data non-transiently and may train on it<br/>- deny: use only providers which do not collect user data.<br/> | deny |
| `data_collection` | [OptionalNullable[components.DataCollection]](../components/datacollection.md) | :heavy_minus_sign: | Data collection setting. If no available model provider meets the requirement, your request will return an error.<br/>- allow: (default) allow providers which store user data non-transiently and may train on it<br/><br/>- deny: use only providers which do not collect user data. | allow |
| `zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used. | true |
| `enforce_distillable_text` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to restrict routing to only models that allow text distillation. When true, only models where the author has allowed distillation will be used. | true |
| `order` | List[[operations.Order](../operations/order.md)] | :heavy_minus_sign: | An ordered list of provider slugs. The router will attempt to use the first provider in the subset of this list that supports your requested model, and fall back to the next if it is unavailable. If no providers are available, the request will fail with an error message. | |
| `only` | List[[operations.Only](../operations/only.md)] | :heavy_minus_sign: | List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request. | |
| `ignore` | List[[operations.Ignore](../operations/ignore.md)] | :heavy_minus_sign: | List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request. | |
| `quantizations` | List[[components.Quantization](../components/quantization.md)] | :heavy_minus_sign: | A list of quantization levels to filter the provider by. | |
| `sort` | [OptionalNullable[operations.Sort]](../operations/sort.md) | :heavy_minus_sign: | The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. | price |
| `sort` | [OptionalNullable[components.ProviderSort]](../components/providersort.md) | :heavy_minus_sign: | The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. | price |
| `max_price` | [Optional[operations.MaxPrice]](../operations/maxprice.md) | :heavy_minus_sign: | The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion. | |
+5 -3
View File
@@ -5,8 +5,10 @@
| Field | Type | Required | Description |
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
| `input` | [operations.Input](../operations/input.md) | :heavy_check_mark: | N/A |
| `input` | [operations.InputUnion](../operations/inputunion.md) | :heavy_check_mark: | N/A |
| `model` | *str* | :heavy_check_mark: | N/A |
| `provider` | [Optional[operations.CreateEmbeddingsProvider]](../operations/createembeddingsprovider.md) | :heavy_minus_sign: | N/A |
| `encoding_format` | [Optional[operations.EncodingFormat]](../operations/encodingformat.md) | :heavy_minus_sign: | N/A |
| `user` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `dimensions` | *Optional[int]* | :heavy_minus_sign: | N/A |
| `user` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `provider` | [Optional[operations.CreateEmbeddingsProvider]](../operations/createembeddingsprovider.md) | :heavy_minus_sign: | N/A |
| `input_type` | *Optional[str]* | :heavy_minus_sign: | N/A |
-14
View File
@@ -1,14 +0,0 @@
# DataCollection
Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
## Values
| Name | Value |
| ------- | ------- |
| `DENY` | deny |
| `ALLOW` | allow |
+5 -13
View File
@@ -1,17 +1,9 @@
# EncodingFormat
## Supported Types
### `operations.EncodingFormatFloat`
```python
value: operations.EncodingFormatFloat = /* values here */
```
### `operations.EncodingFormatBase64`
```python
value: operations.EncodingFormatBase64 = /* values here */
```
## Values
| Name | Value |
| -------- | -------- |
| `FLOAT` | float |
| `BASE64` | base64 |
-8
View File
@@ -1,8 +0,0 @@
# EncodingFormatBase64
## Values
| Name | Value |
| -------- | -------- |
| `BASE64` | base64 |
-8
View File
@@ -1,8 +0,0 @@
# EncodingFormatFloat
## Values
| Name | Value |
| ------- | ------- |
| `FLOAT` | float |
+64 -70
View File
@@ -3,73 +3,67 @@
## Values
| Name | Value |
| ------------------ | ------------------ |
| `AI21` | AI21 |
| `AION_LABS` | AionLabs |
| `ALIBABA` | Alibaba |
| `AMAZON_BEDROCK` | Amazon Bedrock |
| `ANTHROPIC` | Anthropic |
| `ATLAS_CLOUD` | AtlasCloud |
| `ATOMA` | Atoma |
| `AVIAN` | Avian |
| `AZURE` | Azure |
| `BASE_TEN` | BaseTen |
| `CEREBRAS` | Cerebras |
| `CHUTES` | Chutes |
| `CIRRASCALE` | Cirrascale |
| `CLARIFAI` | Clarifai |
| `CLOUDFLARE` | Cloudflare |
| `COHERE` | Cohere |
| `CROF_AI` | CrofAI |
| `CRUSOE` | Crusoe |
| `DEEP_INFRA` | DeepInfra |
| `DEEP_SEEK` | DeepSeek |
| `ENFER` | Enfer |
| `FEATHERLESS` | Featherless |
| `FIREWORKS` | Fireworks |
| `FRIENDLI` | Friendli |
| `GMI_CLOUD` | GMICloud |
| `GOOGLE` | Google |
| `GOOGLE_AI_STUDIO` | Google AI Studio |
| `GROQ` | Groq |
| `HYPERBOLIC` | Hyperbolic |
| `INCEPTION` | Inception |
| `INFERENCE_NET` | InferenceNet |
| `INFERMATIC` | Infermatic |
| `INFLECTION` | Inflection |
| `KLUSTER` | Kluster |
| `LAMBDA` | Lambda |
| `LIQUID` | Liquid |
| `MANCER_2` | Mancer 2 |
| `META` | Meta |
| `MINIMAX` | Minimax |
| `MODEL_RUN` | ModelRun |
| `MISTRAL` | Mistral |
| `MODULAR` | Modular |
| `MOONSHOT_AI` | Moonshot AI |
| `MORPH` | Morph |
| `N_COMPASS` | NCompass |
| `NEBIUS` | Nebius |
| `NEXT_BIT` | NextBit |
| `NINETEEN` | Nineteen |
| `NOVITA` | Novita |
| `NVIDIA` | Nvidia |
| `OPEN_AI` | OpenAI |
| `OPEN_INFERENCE` | OpenInference |
| `PARASAIL` | Parasail |
| `PERPLEXITY` | Perplexity |
| `PHALA` | Phala |
| `RELACE` | Relace |
| `SAMBA_NOVA` | SambaNova |
| `SILICON_FLOW` | SiliconFlow |
| `STEALTH` | Stealth |
| `SWITCHPOINT` | Switchpoint |
| `TARGON` | Targon |
| `TOGETHER` | Together |
| `UBICLOUD` | Ubicloud |
| `VENICE` | Venice |
| `WAND_B` | WandB |
| `X_AI` | xAI |
| `Z_AI` | Z.AI |
| `FAKE_PROVIDER` | FakeProvider |
| Name | Value |
| ------------------- | ------------------- |
| `AI21` | AI21 |
| `AION_LABS` | AionLabs |
| `ALIBABA` | Alibaba |
| `AMAZON_BEDROCK` | Amazon Bedrock |
| `ANTHROPIC` | Anthropic |
| `ARCEE` | Arcee |
| `ATLAS_CLOUD` | AtlasCloud |
| `AVIAN` | Avian |
| `AZURE` | Azure |
| `BASE_TEN` | BaseTen |
| `BLACK_FOREST_LABS` | Black Forest Labs |
| `CEREBRAS` | Cerebras |
| `CHUTES` | Chutes |
| `CIRRASCALE` | Cirrascale |
| `CLARIFAI` | Clarifai |
| `CLOUDFLARE` | Cloudflare |
| `COHERE` | Cohere |
| `CRUSOE` | Crusoe |
| `DEEP_INFRA` | DeepInfra |
| `DEEP_SEEK` | DeepSeek |
| `FEATHERLESS` | Featherless |
| `FIREWORKS` | Fireworks |
| `FRIENDLI` | Friendli |
| `GMI_CLOUD` | GMICloud |
| `GOOGLE` | Google |
| `GOOGLE_AI_STUDIO` | Google AI Studio |
| `GROQ` | Groq |
| `HYPERBOLIC` | Hyperbolic |
| `INCEPTION` | Inception |
| `INFERENCE_NET` | InferenceNet |
| `INFERMATIC` | Infermatic |
| `INFLECTION` | Inflection |
| `LIQUID` | Liquid |
| `MANCER_2` | Mancer 2 |
| `MINIMAX` | Minimax |
| `MODEL_RUN` | ModelRun |
| `MISTRAL` | Mistral |
| `MODULAR` | Modular |
| `MOONSHOT_AI` | Moonshot AI |
| `MORPH` | Morph |
| `N_COMPASS` | NCompass |
| `NEBIUS` | Nebius |
| `NEXT_BIT` | NextBit |
| `NOVITA` | Novita |
| `NVIDIA` | Nvidia |
| `OPEN_AI` | OpenAI |
| `OPEN_INFERENCE` | OpenInference |
| `PARASAIL` | Parasail |
| `PERPLEXITY` | Perplexity |
| `PHALA` | Phala |
| `RELACE` | Relace |
| `SAMBA_NOVA` | SambaNova |
| `SILICON_FLOW` | SiliconFlow |
| `STEALTH` | Stealth |
| `SWITCHPOINT` | Switchpoint |
| `TARGON` | Targon |
| `TOGETHER` | Together |
| `VENICE` | Venice |
| `WAND_B` | WandB |
| `X_AI` | xAI |
| `Z_AI` | Z.AI |
| `FAKE_PROVIDER` | FakeProvider |
@@ -1,4 +1,4 @@
# VideoURL
# ImageURL
## Fields
+4 -25
View File
@@ -1,29 +1,8 @@
# Input
## Supported Types
### `str`
```python
value: str = /* values here */
```
### `List[str]`
```python
value: List[str] = /* values here */
```
### `List[float]`
```python
value: List[float] = /* values here */
```
### `List[List[float]]`
```python
value: List[List[float]] = /* values here */
```
## Fields
| Field | Type | Required | Description |
| ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- |
| `content` | List[[operations.Content](../operations/content.md)] | :heavy_check_mark: | N/A |
+35
View File
@@ -0,0 +1,35 @@
# InputUnion
## Supported Types
### `str`
```python
value: str = /* values here */
```
### `List[str]`
```python
value: List[str] = /* values here */
```
### `List[float]`
```python
value: List[float] = /* values here */
```
### `List[List[float]]`
```python
value: List[List[float]] = /* values here */
```
### `List[operations.Input]`
```python
value: List[operations.Input] = /* values here */
```
-12
View File
@@ -1,12 +0,0 @@
# Sort
The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed.
## Values
| Name | Value |
| ------------ | ------------ |
| `PRICE` | price |
| `THROUGHPUT` | throughput |
| `LATENCY` | latency |
+8
View File
@@ -0,0 +1,8 @@
# TypeImageURL
## Values
| Name | Value |
| ----------- | ----------- |
| `IMAGE_URL` | image_url |
+8
View File
@@ -0,0 +1,8 @@
# TypeText
## Values
| Name | Value |
| ------ | ------ |
| `TEXT` | text |
+5 -3
View File
@@ -27,7 +27,7 @@ with OpenRouter(
) as open_router:
res = open_router.embeddings.generate(input="<value>", model="Taurus", provider={
"data_collection": "deny",
"data_collection": "allow",
"zdr": True,
"enforce_distillable_text": True,
"order": [
@@ -54,11 +54,13 @@ with OpenRouter(
| Parameter | Type | Required | Description |
| --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- |
| `input` | [operations.Input](../../operations/input.md) | :heavy_check_mark: | N/A |
| `input` | [operations.InputUnion](../../operations/inputunion.md) | :heavy_check_mark: | N/A |
| `model` | *str* | :heavy_check_mark: | N/A |
| `provider` | [Optional[operations.CreateEmbeddingsProvider]](../../operations/createembeddingsprovider.md) | :heavy_minus_sign: | N/A |
| `encoding_format` | [Optional[operations.EncodingFormat]](../../operations/encodingformat.md) | :heavy_minus_sign: | N/A |
| `dimensions` | *Optional[int]* | :heavy_minus_sign: | N/A |
| `user` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `provider` | [Optional[operations.CreateEmbeddingsProvider]](../../operations/createembeddingsprovider.md) | :heavy_minus_sign: | N/A |
| `input_type` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. |
### Response
+1 -1
View File
@@ -65,7 +65,7 @@ with OpenRouter(
},
},
}, service_tier="auto", truncation="auto", stream=False, provider={
"data_collection": "deny",
"data_collection": "allow",
"zdr": True,
"enforce_distillable_text": True,
"order": [
+4 -2
View File
@@ -1,15 +1,17 @@
[project]
name = "openrouter"
version = "0.0.15"
version = "0.0.19"
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"
license = { text = "Apache-2.0" }
[dependency-groups]
dev = [
+35
View File
@@ -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
View File
@@ -1,4 +1,6 @@
#!/usr/bin/env bash
uv run python scripts/prepare_readme.py
uv build
uv publish --token $PYPI_TOKEN
+3 -3
View File
@@ -3,10 +3,10 @@
import importlib.metadata
__title__: str = "openrouter"
__version__: str = "0.0.15"
__version__: str = "0.0.19"
__openapi_doc_version__: str = "1.0.0"
__gen_version__: str = "2.753.6"
__user_agent__: str = "speakeasy-sdk/python 0.0.15 2.753.6 1.0.0 openrouter"
__gen_version__: str = "2.755.9"
__user_agent__: str = "speakeasy-sdk/python 0.0.19 2.755.9 1.0.0 openrouter"
try:
if __package__ is not None:
+3 -3
View File
@@ -6,7 +6,7 @@ from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, List, Mapping, Optional
from typing import Any, Mapping, Optional
class Analytics(BaseSDK):
@@ -20,7 +20,7 @@ class Analytics(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.ActivityItem]:
) -> operations.GetUserActivityResponse:
r"""Get user activity grouped by endpoint
Returns user activity data grouped by endpoint for the last 30 (completed) UTC days
@@ -128,7 +128,7 @@ class Analytics(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.ActivityItem]:
) -> operations.GetUserActivityResponse:
r"""Get user activity grouped by endpoint
Returns user activity data grouped by endpoint for the last 30 (completed) UTC days
+11 -11
View File
@@ -7,7 +7,7 @@ from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, List, Mapping, Optional
from typing import Any, Mapping, Optional
class APIKeys(BaseSDK):
@@ -22,7 +22,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[operations.ListData]:
) -> operations.ListResponse:
r"""List API keys
:param include_disabled: Whether to include disabled API keys in the response
@@ -126,7 +126,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[operations.ListData]:
) -> operations.ListResponse:
r"""List API keys
:param include_disabled: Whether to include disabled API keys in the response
@@ -233,7 +233,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.CreateKeysData:
) -> operations.CreateKeysResponse:
r"""Create a new API key
:param name: Name for the new API key
@@ -354,7 +354,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.CreateKeysData:
) -> operations.CreateKeysResponse:
r"""Create a new API key
:param name: Name for the new API key
@@ -476,7 +476,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.UpdateKeysData:
) -> operations.UpdateKeysResponse:
r"""Update an API key
:param hash: The hash identifier of the API key to update
@@ -607,7 +607,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.UpdateKeysData:
) -> operations.UpdateKeysResponse:
r"""Update an API key
:param hash: The hash identifier of the API key to update
@@ -945,7 +945,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetKeyData:
) -> operations.GetKeyResponse:
r"""Get a single API key
:param hash: The hash identifier of the API key to retrieve
@@ -1051,7 +1051,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetKeyData:
) -> operations.GetKeyResponse:
r"""Get a single API key
:param hash: The hash identifier of the API key to retrieve
@@ -1156,7 +1156,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetCurrentKeyData:
) -> operations.GetCurrentKeyResponse:
r"""Get current API key
Get information on the API key associated with the current authentication session
@@ -1247,7 +1247,7 @@ class APIKeys(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetCurrentKeyData:
) -> operations.GetCurrentKeyResponse:
r"""Get current API key
Get information on the API key associated with the current authentication session
+39 -17
View File
@@ -21,7 +21,6 @@ if TYPE_CHECKING:
BadRequestResponseErrorData,
BadRequestResponseErrorDataTypedDict,
)
from .chatcompletionfinishreason import ChatCompletionFinishReason
from .chaterror import ChatErrorError, ChatErrorErrorTypedDict, Code, CodeTypedDict
from .chatgenerationparams import (
ChatGenerationParams,
@@ -72,9 +71,15 @@ if TYPE_CHECKING:
)
from .chatmessagecontentitemvideo import (
ChatMessageContentItemVideo,
ChatMessageContentItemVideoInputVideo,
ChatMessageContentItemVideoInputVideoTypedDict,
ChatMessageContentItemVideoTypedDict,
VideoURL,
VideoURLTypedDict,
ChatMessageContentItemVideoVideoURL,
ChatMessageContentItemVideoVideoURLTypedDict,
VideoURL1,
VideoURL1TypedDict,
VideoURL2,
VideoURL2TypedDict,
)
from .chatmessagetokenlogprob import (
ChatMessageTokenLogprob,
@@ -93,8 +98,13 @@ if TYPE_CHECKING:
ChatMessageToolCallTypedDict,
)
from .chatresponse import ChatResponse, ChatResponseTypedDict
from .chatresponsechoice import ChatResponseChoice, ChatResponseChoiceTypedDict
from .chatstreamingchoice import ChatStreamingChoice, ChatStreamingChoiceTypedDict
from .chatresponsechoice import (
ChatCompletionFinishReason,
ChatResponseChoice,
ChatResponseChoiceTypedDict,
ChatStreamingChoice,
ChatStreamingChoiceTypedDict,
)
from .chatstreamingmessagechunk import (
ChatStreamingMessageChunk,
ChatStreamingMessageChunkRole,
@@ -146,6 +156,7 @@ if TYPE_CHECKING:
CreateChargeRequest,
CreateChargeRequestTypedDict,
)
from .datacollection import DataCollection
from .defaultparameters import DefaultParameters, DefaultParametersTypedDict
from .edgenetworktimeoutresponseerrordata import (
EdgeNetworkTimeoutResponseErrorData,
@@ -408,7 +419,6 @@ if TYPE_CHECKING:
OpenResponsesReasoningSummaryTextDoneEventTypedDict,
)
from .openresponsesrequest import (
DataCollection,
Engine,
IDFileParser,
IDModeration,
@@ -442,7 +452,6 @@ if TYPE_CHECKING:
Provider,
ProviderTypedDict,
ServiceTier,
Sort,
Truncation,
)
from .openresponsesresponsetext import (
@@ -581,6 +590,7 @@ if TYPE_CHECKING:
ProviderOverloadedResponseErrorData,
ProviderOverloadedResponseErrorDataTypedDict,
)
from .providersort import ProviderSort
from .publicendpoint import (
Pricing,
PricingTypedDict,
@@ -821,7 +831,11 @@ __all__ = [
"ChatMessageContentItemTextTypedDict",
"ChatMessageContentItemTypedDict",
"ChatMessageContentItemVideo",
"ChatMessageContentItemVideoInputVideo",
"ChatMessageContentItemVideoInputVideoTypedDict",
"ChatMessageContentItemVideoTypedDict",
"ChatMessageContentItemVideoVideoURL",
"ChatMessageContentItemVideoVideoURLTypedDict",
"ChatMessageTokenLogprob",
"ChatMessageTokenLogprobTypedDict",
"ChatMessageTokenLogprobs",
@@ -1205,6 +1219,7 @@ __all__ = [
"ProviderName",
"ProviderOverloadedResponseErrorData",
"ProviderOverloadedResponseErrorDataTypedDict",
"ProviderSort",
"ProviderTypedDict",
"PublicEndpoint",
"PublicEndpointQuantization",
@@ -1310,7 +1325,6 @@ __all__ = [
"ServiceTier",
"ServiceUnavailableResponseErrorData",
"ServiceUnavailableResponseErrorDataTypedDict",
"Sort",
"StreamOptions",
"StreamOptionsTypedDict",
"SystemMessage",
@@ -1366,8 +1380,10 @@ __all__ = [
"UserMessageTypedDict",
"Variables",
"VariablesTypedDict",
"VideoURL",
"VideoURLTypedDict",
"VideoURL1",
"VideoURL1TypedDict",
"VideoURL2",
"VideoURL2TypedDict",
"WebSearchPreviewToolUserLocation",
"WebSearchPreviewToolUserLocationType",
"WebSearchPreviewToolUserLocationTypedDict",
@@ -1385,7 +1401,6 @@ _dynamic_imports: dict[str, str] = {
"BadGatewayResponseErrorDataTypedDict": ".badgatewayresponseerrordata",
"BadRequestResponseErrorData": ".badrequestresponseerrordata",
"BadRequestResponseErrorDataTypedDict": ".badrequestresponseerrordata",
"ChatCompletionFinishReason": ".chatcompletionfinishreason",
"ChatErrorError": ".chaterror",
"ChatErrorErrorTypedDict": ".chaterror",
"Code": ".chaterror",
@@ -1426,9 +1441,15 @@ _dynamic_imports: dict[str, str] = {
"ChatMessageContentItemText": ".chatmessagecontentitemtext",
"ChatMessageContentItemTextTypedDict": ".chatmessagecontentitemtext",
"ChatMessageContentItemVideo": ".chatmessagecontentitemvideo",
"ChatMessageContentItemVideoInputVideo": ".chatmessagecontentitemvideo",
"ChatMessageContentItemVideoInputVideoTypedDict": ".chatmessagecontentitemvideo",
"ChatMessageContentItemVideoTypedDict": ".chatmessagecontentitemvideo",
"VideoURL": ".chatmessagecontentitemvideo",
"VideoURLTypedDict": ".chatmessagecontentitemvideo",
"ChatMessageContentItemVideoVideoURL": ".chatmessagecontentitemvideo",
"ChatMessageContentItemVideoVideoURLTypedDict": ".chatmessagecontentitemvideo",
"VideoURL1": ".chatmessagecontentitemvideo",
"VideoURL1TypedDict": ".chatmessagecontentitemvideo",
"VideoURL2": ".chatmessagecontentitemvideo",
"VideoURL2TypedDict": ".chatmessagecontentitemvideo",
"ChatMessageTokenLogprob": ".chatmessagetokenlogprob",
"ChatMessageTokenLogprobTypedDict": ".chatmessagetokenlogprob",
"TopLogprob": ".chatmessagetokenlogprob",
@@ -1441,10 +1462,11 @@ _dynamic_imports: dict[str, str] = {
"ChatMessageToolCallTypedDict": ".chatmessagetoolcall",
"ChatResponse": ".chatresponse",
"ChatResponseTypedDict": ".chatresponse",
"ChatCompletionFinishReason": ".chatresponsechoice",
"ChatResponseChoice": ".chatresponsechoice",
"ChatResponseChoiceTypedDict": ".chatresponsechoice",
"ChatStreamingChoice": ".chatstreamingchoice",
"ChatStreamingChoiceTypedDict": ".chatstreamingchoice",
"ChatStreamingChoice": ".chatresponsechoice",
"ChatStreamingChoiceTypedDict": ".chatresponsechoice",
"ChatStreamingMessageChunk": ".chatstreamingmessagechunk",
"ChatStreamingMessageChunkRole": ".chatstreamingmessagechunk",
"ChatStreamingMessageChunkTypedDict": ".chatstreamingmessagechunk",
@@ -1488,6 +1510,7 @@ _dynamic_imports: dict[str, str] = {
"ChainID": ".createchargerequest",
"CreateChargeRequest": ".createchargerequest",
"CreateChargeRequestTypedDict": ".createchargerequest",
"DataCollection": ".datacollection",
"DefaultParameters": ".defaultparameters",
"DefaultParametersTypedDict": ".defaultparameters",
"EdgeNetworkTimeoutResponseErrorData": ".edgenetworktimeoutresponseerrordata",
@@ -1687,7 +1710,6 @@ _dynamic_imports: dict[str, str] = {
"OpenResponsesReasoningSummaryTextDoneEvent": ".openresponsesreasoningsummarytextdoneevent",
"OpenResponsesReasoningSummaryTextDoneEventType": ".openresponsesreasoningsummarytextdoneevent",
"OpenResponsesReasoningSummaryTextDoneEventTypedDict": ".openresponsesreasoningsummarytextdoneevent",
"DataCollection": ".openresponsesrequest",
"Engine": ".openresponsesrequest",
"IDFileParser": ".openresponsesrequest",
"IDModeration": ".openresponsesrequest",
@@ -1721,7 +1743,6 @@ _dynamic_imports: dict[str, str] = {
"Provider": ".openresponsesrequest",
"ProviderTypedDict": ".openresponsesrequest",
"ServiceTier": ".openresponsesrequest",
"Sort": ".openresponsesrequest",
"Truncation": ".openresponsesrequest",
"OpenResponsesResponseText": ".openresponsesresponsetext",
"OpenResponsesResponseTextTypedDict": ".openresponsesresponsetext",
@@ -1834,6 +1855,7 @@ _dynamic_imports: dict[str, str] = {
"ProviderName": ".providername",
"ProviderOverloadedResponseErrorData": ".provideroverloadedresponseerrordata",
"ProviderOverloadedResponseErrorDataTypedDict": ".provideroverloadedresponseerrordata",
"ProviderSort": ".providersort",
"Pricing": ".publicendpoint",
"PricingTypedDict": ".publicendpoint",
"PublicEndpoint": ".publicendpoint",
@@ -31,6 +31,7 @@ from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
Effort = Union[
Literal[
"none",
"minimal",
"low",
"medium",
@@ -40,6 +40,7 @@ ChatMessageContentItem = Annotated[
Annotated[ChatMessageContentItemImage, Tag("image_url")],
Annotated[ChatMessageContentItemAudio, Tag("input_audio")],
Annotated[ChatMessageContentItemVideo, Tag("input_video")],
Annotated[ChatMessageContentItemVideo, Tag("video_url")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
@@ -5,25 +5,47 @@ from openrouter.types import BaseModel
from openrouter.utils import validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import Literal
from typing_extensions import Annotated, TypedDict
from typing import Literal, Union
from typing_extensions import Annotated, TypeAliasType, TypedDict
class VideoURLTypedDict(TypedDict):
class VideoURL2TypedDict(TypedDict):
url: str
class VideoURL(BaseModel):
class VideoURL2(BaseModel):
url: str
class ChatMessageContentItemVideoTypedDict(TypedDict):
video_url: VideoURLTypedDict
class ChatMessageContentItemVideoVideoURLTypedDict(TypedDict):
video_url: VideoURL2TypedDict
type: Literal["video_url"]
class ChatMessageContentItemVideoVideoURL(BaseModel):
video_url: VideoURL2
TYPE: Annotated[
Annotated[Literal["video_url"], AfterValidator(validate_const("video_url"))],
pydantic.Field(alias="type"),
] = "video_url"
class VideoURL1TypedDict(TypedDict):
url: str
class VideoURL1(BaseModel):
url: str
class ChatMessageContentItemVideoInputVideoTypedDict(TypedDict):
video_url: VideoURL1TypedDict
type: Literal["input_video"]
class ChatMessageContentItemVideo(BaseModel):
video_url: VideoURL
class ChatMessageContentItemVideoInputVideo(BaseModel):
video_url: VideoURL1
TYPE: Annotated[
Annotated[
@@ -31,3 +53,18 @@ class ChatMessageContentItemVideo(BaseModel):
],
pydantic.Field(alias="type"),
] = "input_video"
ChatMessageContentItemVideoTypedDict = TypeAliasType(
"ChatMessageContentItemVideoTypedDict",
Union[
ChatMessageContentItemVideoInputVideoTypedDict,
ChatMessageContentItemVideoVideoURLTypedDict,
],
)
ChatMessageContentItemVideo = TypeAliasType(
"ChatMessageContentItemVideo",
Union[ChatMessageContentItemVideoInputVideo, ChatMessageContentItemVideoVideoURL],
)
@@ -2,24 +2,41 @@
from __future__ import annotations
from .assistantmessage import AssistantMessage, AssistantMessageTypedDict
from .chatcompletionfinishreason import ChatCompletionFinishReason
from .chatmessagetokenlogprobs import (
ChatMessageTokenLogprobs,
ChatMessageTokenLogprobsTypedDict,
)
from .chatstreamingmessagechunk import (
ChatStreamingMessageChunk,
ChatStreamingMessageChunkTypedDict,
)
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Literal, Union
from typing_extensions import Annotated, NotRequired, TypedDict
ChatCompletionFinishReason = Union[
Literal[
"tool_calls",
"stop",
"length",
"content_filter",
"error",
],
UnrecognizedStr,
]
class ChatResponseChoiceTypedDict(TypedDict):
finish_reason: Nullable[ChatCompletionFinishReason]
index: float
@@ -67,3 +84,52 @@ class ChatResponseChoice(BaseModel):
m[k] = val
return m
class ChatStreamingChoiceTypedDict(TypedDict):
delta: ChatStreamingMessageChunkTypedDict
finish_reason: Nullable[ChatCompletionFinishReason]
index: float
logprobs: NotRequired[Nullable[ChatMessageTokenLogprobsTypedDict]]
class ChatStreamingChoice(BaseModel):
delta: ChatStreamingMessageChunk
finish_reason: Annotated[
Nullable[ChatCompletionFinishReason], PlainValidator(validate_open_enum(False))
]
index: float
logprobs: OptionalNullable[ChatMessageTokenLogprobs] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["logprobs"]
nullable_fields = ["finish_reason", "logprobs"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -1,72 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatcompletionfinishreason import ChatCompletionFinishReason
from .chatmessagetokenlogprobs import (
ChatMessageTokenLogprobs,
ChatMessageTokenLogprobsTypedDict,
)
from .chatstreamingmessagechunk import (
ChatStreamingMessageChunk,
ChatStreamingMessageChunkTypedDict,
)
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing_extensions import Annotated, NotRequired, TypedDict
class ChatStreamingChoiceTypedDict(TypedDict):
delta: ChatStreamingMessageChunkTypedDict
finish_reason: Nullable[ChatCompletionFinishReason]
index: float
logprobs: NotRequired[Nullable[ChatMessageTokenLogprobsTypedDict]]
class ChatStreamingChoice(BaseModel):
delta: ChatStreamingMessageChunk
finish_reason: Annotated[
Nullable[ChatCompletionFinishReason], PlainValidator(validate_open_enum(False))
]
index: float
logprobs: OptionalNullable[ChatMessageTokenLogprobs] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["logprobs"]
nullable_fields = ["finish_reason", "logprobs"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -5,7 +5,7 @@ from .chatgenerationtokenusage import (
ChatGenerationTokenUsage,
ChatGenerationTokenUsageTypedDict,
)
from .chatstreamingchoice import ChatStreamingChoice, ChatStreamingChoiceTypedDict
from .chatresponsechoice import ChatStreamingChoice, ChatStreamingChoiceTypedDict
from openrouter.types import (
BaseModel,
Nullable,
@@ -0,0 +1,19 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import UnrecognizedStr
from typing import Literal, Union
DataCollection = Union[
Literal[
"deny",
"allow",
],
UnrecognizedStr,
]
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
"""
@@ -11,6 +11,7 @@ OpenAIResponsesReasoningEffort = Union[
"medium",
"low",
"minimal",
"none",
],
UnrecognizedStr,
]
@@ -57,6 +57,7 @@ OpenResponsesReasoningFormat = Union[
"openai-responses-v1",
"xai-responses-v1",
"anthropic-claude-v1",
"google-gemini-v1",
],
UnrecognizedStr,
]
@@ -1,6 +1,7 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .datacollection import DataCollection
from .openairesponsesincludable import OpenAIResponsesIncludable
from .openairesponsesprompt import OpenAIResponsesPrompt, OpenAIResponsesPromptTypedDict
from .openairesponsestoolchoice_union import (
@@ -33,6 +34,7 @@ from .openresponseswebsearchtool import (
OpenResponsesWebSearchToolTypedDict,
)
from .providername import ProviderName
from .providersort import ProviderSort
from .quantization import Quantization
from openrouter.types import (
BaseModel,
@@ -151,20 +153,6 @@ Truncation = Union[
]
DataCollection = Union[
Literal[
"deny",
"allow",
],
UnrecognizedStr,
]
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
"""
OrderTypedDict = TypeAliasType("OrderTypedDict", Union[ProviderName, str])
@@ -192,17 +180,6 @@ Ignore = TypeAliasType(
)
Sort = Union[
Literal[
"price",
"throughput",
"latency",
],
UnrecognizedStr,
]
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
class MaxPriceTypedDict(TypedDict):
r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""
@@ -251,8 +228,8 @@ class ProviderTypedDict(TypedDict):
data_collection: NotRequired[Nullable[DataCollection]]
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
- deny: use only providers which do not collect user data.
"""
zdr: NotRequired[Nullable[bool]]
r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used."""
@@ -266,7 +243,7 @@ class ProviderTypedDict(TypedDict):
r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request."""
quantizations: NotRequired[Nullable[List[Quantization]]]
r"""A list of quantization levels to filter the provider by."""
sort: NotRequired[Nullable[Sort]]
sort: NotRequired[Nullable[ProviderSort]]
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
max_price: NotRequired[MaxPriceTypedDict]
r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""
@@ -290,8 +267,8 @@ class Provider(BaseModel):
] = UNSET
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
- deny: use only providers which do not collect user data.
"""
zdr: OptionalNullable[bool] = UNSET
@@ -315,7 +292,7 @@ class Provider(BaseModel):
r"""A list of quantization levels to filter the provider by."""
sort: Annotated[
OptionalNullable[Sort], PlainValidator(validate_open_enum(False))
OptionalNullable[ProviderSort], PlainValidator(validate_open_enum(False))
] = UNSET
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
+2 -26
View File
@@ -7,44 +7,26 @@ from typing import Literal, Union
ProviderName = Union[
Literal[
"AnyScale",
"Cent-ML",
"HuggingFace",
"Hyperbolic 2",
"Lepton",
"Lynn 2",
"Lynn",
"Mancer",
"Modal",
"OctoAI",
"Recursal",
"Reflection",
"Replicate",
"SambaNova 2",
"SF Compute",
"Together 2",
"01.AI",
"AI21",
"AionLabs",
"Alibaba",
"Amazon Bedrock",
"Anthropic",
"Arcee",
"AtlasCloud",
"Atoma",
"Avian",
"Azure",
"BaseTen",
"Black Forest Labs",
"Cerebras",
"Chutes",
"Cirrascale",
"Clarifai",
"Cloudflare",
"Cohere",
"CrofAI",
"Crusoe",
"DeepInfra",
"DeepSeek",
"Enfer",
"Featherless",
"Fireworks",
"Friendli",
@@ -57,12 +39,8 @@ ProviderName = Union[
"InferenceNet",
"Infermatic",
"Inflection",
"InoCloud",
"Kluster",
"Lambda",
"Liquid",
"Mancer 2",
"Meta",
"Minimax",
"ModelRun",
"Mistral",
@@ -72,7 +50,6 @@ ProviderName = Union[
"NCompass",
"Nebius",
"NextBit",
"Nineteen",
"Novita",
"Nvidia",
"OpenAI",
@@ -87,7 +64,6 @@ ProviderName = Union[
"Switchpoint",
"Targon",
"Together",
"Ubicloud",
"Venice",
"WandB",
"xAI",
@@ -5,13 +5,12 @@ from openrouter.types import UnrecognizedStr
from typing import Literal, Union
ChatCompletionFinishReason = Union[
ProviderSort = Union[
Literal[
"tool_calls",
"stop",
"length",
"content_filter",
"error",
"price",
"throughput",
"latency",
],
UnrecognizedStr,
]
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
@@ -21,6 +21,8 @@ class PricingTypedDict(TypedDict):
r"""A value in string or number format that is a large number"""
image: NotRequired[Any]
r"""A value in string or number format that is a large number"""
image_token: NotRequired[Any]
r"""A value in string or number format that is a large number"""
image_output: NotRequired[Any]
r"""A value in string or number format that is a large number"""
audio: NotRequired[Any]
@@ -51,6 +53,9 @@ class Pricing(BaseModel):
image: Optional[Any] = None
r"""A value in string or number format that is a large number"""
image_token: Optional[Any] = None
r"""A value in string or number format that is a large number"""
image_output: Optional[Any] = None
r"""A value in string or number format that is a large number"""
@@ -17,6 +17,8 @@ class PublicPricingTypedDict(TypedDict):
r"""A value in string or number format that is a large number"""
image: NotRequired[Any]
r"""A value in string or number format that is a large number"""
image_token: NotRequired[Any]
r"""A value in string or number format that is a large number"""
image_output: NotRequired[Any]
r"""A value in string or number format that is a large number"""
audio: NotRequired[Any]
@@ -49,6 +51,9 @@ class PublicPricing(BaseModel):
image: Optional[Any] = None
r"""A value in string or number format that is a large number"""
image_token: Optional[Any] = None
r"""A value in string or number format that is a large number"""
image_output: Optional[Any] = None
r"""A value in string or number format that is a large number"""
+2 -2
View File
@@ -218,7 +218,7 @@ class Credits(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.CreateCoinbaseChargeData:
) -> operations.CreateCoinbaseChargeResponse:
r"""Create a Coinbase charge for crypto payment
Create a Coinbase charge for crypto payment
@@ -342,7 +342,7 @@ class Credits(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.CreateCoinbaseChargeData:
) -> operations.CreateCoinbaseChargeResponse:
r"""Create a Coinbase charge for crypto payment
Create a Coinbase charge for crypto payment
+29 -21
View File
@@ -7,7 +7,7 @@ from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, List, Mapping, Optional, Union
from typing import Any, Mapping, Optional, Union
class GenerateAcceptEnum(str, Enum):
@@ -21,18 +21,18 @@ class Embeddings(BaseSDK):
def generate(
self,
*,
input: Union[operations.Input, operations.InputTypedDict],
input: Union[operations.InputUnion, operations.InputUnionTypedDict],
model: str,
encoding_format: Optional[operations.EncodingFormat] = None,
dimensions: Optional[int] = None,
user: Optional[str] = None,
provider: Optional[
Union[
operations.CreateEmbeddingsProvider,
operations.CreateEmbeddingsProviderTypedDict,
]
] = None,
encoding_format: Optional[
Union[operations.EncodingFormat, operations.EncodingFormatTypedDict]
] = None,
user: Optional[str] = None,
input_type: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -45,9 +45,11 @@ class Embeddings(BaseSDK):
:param input:
:param model:
:param provider:
:param encoding_format:
:param dimensions:
:param user:
:param provider:
:param input_type:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
@@ -65,13 +67,15 @@ class Embeddings(BaseSDK):
base_url = self._get_url(base_url, url_variables)
request = operations.CreateEmbeddingsRequest(
input=input,
input=utils.get_pydantic_model(input, operations.InputUnion),
model=model,
encoding_format=encoding_format,
dimensions=dimensions,
user=user,
provider=utils.get_pydantic_model(
provider, Optional[operations.CreateEmbeddingsProvider]
),
encoding_format=encoding_format,
user=user,
input_type=input_type,
)
req = self._build_request(
@@ -204,18 +208,18 @@ class Embeddings(BaseSDK):
async def generate_async(
self,
*,
input: Union[operations.Input, operations.InputTypedDict],
input: Union[operations.InputUnion, operations.InputUnionTypedDict],
model: str,
encoding_format: Optional[operations.EncodingFormat] = None,
dimensions: Optional[int] = None,
user: Optional[str] = None,
provider: Optional[
Union[
operations.CreateEmbeddingsProvider,
operations.CreateEmbeddingsProviderTypedDict,
]
] = None,
encoding_format: Optional[
Union[operations.EncodingFormat, operations.EncodingFormatTypedDict]
] = None,
user: Optional[str] = None,
input_type: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -228,9 +232,11 @@ class Embeddings(BaseSDK):
:param input:
:param model:
:param provider:
:param encoding_format:
:param dimensions:
:param user:
:param provider:
:param input_type:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
@@ -248,13 +254,15 @@ class Embeddings(BaseSDK):
base_url = self._get_url(base_url, url_variables)
request = operations.CreateEmbeddingsRequest(
input=input,
input=utils.get_pydantic_model(input, operations.InputUnion),
model=model,
encoding_format=encoding_format,
dimensions=dimensions,
user=user,
provider=utils.get_pydantic_model(
provider, Optional[operations.CreateEmbeddingsProvider]
),
encoding_format=encoding_format,
user=user,
input_type=input_type,
)
req = self._build_request_async(
@@ -391,7 +399,7 @@ class Embeddings(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.Model]:
) -> components.ModelsListResponse:
r"""List all embeddings models
Returns a list of all available embeddings models and their properties
@@ -482,7 +490,7 @@ class Embeddings(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.Model]:
) -> components.ModelsListResponse:
r"""List all embeddings models
Returns a list of all available embeddings models and their properties
+5 -5
View File
@@ -6,7 +6,7 @@ from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, List, Mapping, Optional
from typing import Any, Mapping, Optional
class Endpoints(BaseSDK):
@@ -21,7 +21,7 @@ class Endpoints(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.ListEndpointsResponse:
) -> operations.ListEndpointsResponse:
r"""List all endpoints for a model
:param author:
@@ -120,7 +120,7 @@ class Endpoints(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.ListEndpointsResponse:
) -> operations.ListEndpointsResponse:
r"""List all endpoints for a model
:param author:
@@ -217,7 +217,7 @@ class Endpoints(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.PublicEndpoint]:
) -> operations.ListEndpointsZdrResponse:
r"""Preview the impact of ZDR on the available endpoints
:param retries: Override the default retry configuration for this method
@@ -303,7 +303,7 @@ class Endpoints(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.PublicEndpoint]:
) -> operations.ListEndpointsZdrResponse:
r"""Preview the impact of ZDR on the available endpoints
:param retries: Override the default retry configuration for this method
+2 -2
View File
@@ -20,7 +20,7 @@ class Generations(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetGenerationData:
) -> operations.GetGenerationResponse:
r"""Get request & usage metadata for a generation
:param id:
@@ -157,7 +157,7 @@ class Generations(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetGenerationData:
) -> operations.GetGenerationResponse:
r"""Get request & usage metadata for a generation
:param id:
+7 -7
View File
@@ -6,7 +6,7 @@ from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, List, Mapping, Optional, Union
from typing import Any, Mapping, Optional, Union
class Models(BaseSDK):
@@ -19,7 +19,7 @@ class Models(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.ModelsCountResponseData:
) -> components.ModelsCountResponse:
r"""Get total count of available models
:param retries: Override the default retry configuration for this method
@@ -103,7 +103,7 @@ class Models(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> components.ModelsCountResponseData:
) -> components.ModelsCountResponse:
r"""Get total count of available models
:param retries: Override the default retry configuration for this method
@@ -189,7 +189,7 @@ class Models(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.Model]:
) -> components.ModelsListResponse:
r"""List all models and their properties
:param category:
@@ -288,7 +288,7 @@ class Models(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.Model]:
) -> components.ModelsListResponse:
r"""List all models and their properties
:param category:
@@ -389,7 +389,7 @@ class Models(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.Model]:
) -> components.ModelsListResponse:
r"""List models filtered by user provider preferences
:param security:
@@ -483,7 +483,7 @@ class Models(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[components.Model]:
) -> components.ModelsListResponse:
r"""List models filtered by user provider preferences
:param security:
+2 -2
View File
@@ -267,7 +267,7 @@ class OAuth(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.CreateAuthKeysCodeData:
) -> operations.CreateAuthKeysCodeResponse:
r"""Create authorization code
Create an authorization code for the PKCE flow to generate a user-controlled API key
@@ -389,7 +389,7 @@ class OAuth(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.CreateAuthKeysCodeData:
) -> operations.CreateAuthKeysCodeResponse:
r"""Create authorization code
Create an authorization code for the PKCE flow to generate a user-controlled API key
+36 -15
View File
@@ -32,6 +32,12 @@ if TYPE_CHECKING:
Web3DataTypedDict,
)
from .createembeddings import (
Content,
ContentImageURL,
ContentImageURLTypedDict,
ContentText,
ContentTextTypedDict,
ContentTypedDict,
CreateEmbeddingsData,
CreateEmbeddingsDataTypedDict,
CreateEmbeddingsProvider,
@@ -42,17 +48,17 @@ if TYPE_CHECKING:
CreateEmbeddingsResponseBody,
CreateEmbeddingsResponseBodyTypedDict,
CreateEmbeddingsResponseTypedDict,
DataCollection,
Embedding,
EmbeddingTypedDict,
EncodingFormat,
EncodingFormatBase64,
EncodingFormatFloat,
EncodingFormatTypedDict,
Ignore,
IgnoreTypedDict,
ImageURL,
ImageURLTypedDict,
Input,
InputTypedDict,
InputUnion,
InputUnionTypedDict,
MaxPrice,
MaxPriceTypedDict,
Object,
@@ -61,7 +67,8 @@ if TYPE_CHECKING:
OnlyTypedDict,
Order,
OrderTypedDict,
Sort,
TypeImageURL,
TypeText,
Usage,
UsageTypedDict,
)
@@ -183,6 +190,12 @@ __all__ = [
"APIType",
"CallData",
"CallDataTypedDict",
"Content",
"ContentImageURL",
"ContentImageURLTypedDict",
"ContentText",
"ContentTextTypedDict",
"ContentTypedDict",
"CreateAuthKeysCodeCodeChallengeMethod",
"CreateAuthKeysCodeData",
"CreateAuthKeysCodeDataTypedDict",
@@ -217,7 +230,6 @@ __all__ = [
"CreateResponsesResponseBody",
"CreateResponsesResponseBodyTypedDict",
"CreateResponsesResponseTypedDict",
"DataCollection",
"DeleteKeysRequest",
"DeleteKeysRequestTypedDict",
"DeleteKeysResponse",
@@ -225,9 +237,6 @@ __all__ = [
"Embedding",
"EmbeddingTypedDict",
"EncodingFormat",
"EncodingFormatBase64",
"EncodingFormatFloat",
"EncodingFormatTypedDict",
"ExchangeAuthCodeForAPIKeyCodeChallengeMethod",
"ExchangeAuthCodeForAPIKeyRequest",
"ExchangeAuthCodeForAPIKeyRequestTypedDict",
@@ -268,8 +277,12 @@ __all__ = [
"GetUserActivityResponseTypedDict",
"Ignore",
"IgnoreTypedDict",
"ImageURL",
"ImageURLTypedDict",
"Input",
"InputTypedDict",
"InputUnion",
"InputUnionTypedDict",
"ListData",
"ListDataTypedDict",
"ListEndpointsRequest",
@@ -302,10 +315,11 @@ __all__ = [
"RateLimitTypedDict",
"SendChatCompletionRequestResponse",
"SendChatCompletionRequestResponseTypedDict",
"Sort",
"SupportedParameter",
"TransferIntent",
"TransferIntentTypedDict",
"TypeImageURL",
"TypeText",
"UpdateKeysData",
"UpdateKeysDataTypedDict",
"UpdateKeysLimitReset",
@@ -343,6 +357,12 @@ _dynamic_imports: dict[str, str] = {
"TransferIntentTypedDict": ".createcoinbasecharge",
"Web3Data": ".createcoinbasecharge",
"Web3DataTypedDict": ".createcoinbasecharge",
"Content": ".createembeddings",
"ContentImageURL": ".createembeddings",
"ContentImageURLTypedDict": ".createembeddings",
"ContentText": ".createembeddings",
"ContentTextTypedDict": ".createembeddings",
"ContentTypedDict": ".createembeddings",
"CreateEmbeddingsData": ".createembeddings",
"CreateEmbeddingsDataTypedDict": ".createembeddings",
"CreateEmbeddingsProvider": ".createembeddings",
@@ -353,17 +373,17 @@ _dynamic_imports: dict[str, str] = {
"CreateEmbeddingsResponseBody": ".createembeddings",
"CreateEmbeddingsResponseBodyTypedDict": ".createembeddings",
"CreateEmbeddingsResponseTypedDict": ".createembeddings",
"DataCollection": ".createembeddings",
"Embedding": ".createembeddings",
"EmbeddingTypedDict": ".createembeddings",
"EncodingFormat": ".createembeddings",
"EncodingFormatBase64": ".createembeddings",
"EncodingFormatFloat": ".createembeddings",
"EncodingFormatTypedDict": ".createembeddings",
"Ignore": ".createembeddings",
"IgnoreTypedDict": ".createembeddings",
"ImageURL": ".createembeddings",
"ImageURLTypedDict": ".createembeddings",
"Input": ".createembeddings",
"InputTypedDict": ".createembeddings",
"InputUnion": ".createembeddings",
"InputUnionTypedDict": ".createembeddings",
"MaxPrice": ".createembeddings",
"MaxPriceTypedDict": ".createembeddings",
"Object": ".createembeddings",
@@ -372,7 +392,8 @@ _dynamic_imports: dict[str, str] = {
"OnlyTypedDict": ".createembeddings",
"Order": ".createembeddings",
"OrderTypedDict": ".createembeddings",
"Sort": ".createembeddings",
"TypeImageURL": ".createembeddings",
"TypeText": ".createembeddings",
"Usage": ".createembeddings",
"UsageTypedDict": ".createembeddings",
"CreateKeysData": ".createkeys",
+85 -50
View File
@@ -2,7 +2,9 @@
from __future__ import annotations
from openrouter.components import (
datacollection as components_datacollection,
providername as components_providername,
providersort as components_providersort,
quantization as components_quantization,
)
from openrouter.types import (
@@ -20,26 +22,76 @@ from typing import Any, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
InputTypedDict = TypeAliasType(
"InputTypedDict", Union[str, List[str], List[float], List[List[float]]]
TypeImageURL = Literal["image_url",]
class ImageURLTypedDict(TypedDict):
url: str
class ImageURL(BaseModel):
url: str
class ContentImageURLTypedDict(TypedDict):
type: TypeImageURL
image_url: ImageURLTypedDict
class ContentImageURL(BaseModel):
type: TypeImageURL
image_url: ImageURL
TypeText = Literal["text",]
class ContentTextTypedDict(TypedDict):
type: TypeText
text: str
class ContentText(BaseModel):
type: TypeText
text: str
ContentTypedDict = TypeAliasType(
"ContentTypedDict", Union[ContentTextTypedDict, ContentImageURLTypedDict]
)
Input = TypeAliasType("Input", Union[str, List[str], List[float], List[List[float]]])
Content = TypeAliasType("Content", Union[ContentText, ContentImageURL])
DataCollection = Union[
class InputTypedDict(TypedDict):
content: List[ContentTypedDict]
class Input(BaseModel):
content: List[Content]
InputUnionTypedDict = TypeAliasType(
"InputUnionTypedDict",
Union[str, List[str], List[float], List[List[float]], List[InputTypedDict]],
)
InputUnion = TypeAliasType(
"InputUnion", Union[str, List[str], List[float], List[List[float]], List[Input]]
)
EncodingFormat = Union[
Literal[
"deny",
"allow",
"float",
"base64",
],
UnrecognizedStr,
]
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
"""
OrderTypedDict = TypeAliasType(
@@ -93,17 +145,6 @@ Ignore = TypeAliasType(
)
Sort = Union[
Literal[
"price",
"throughput",
"latency",
],
UnrecognizedStr,
]
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
class MaxPriceTypedDict(TypedDict):
r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""
@@ -147,11 +188,11 @@ class CreateEmbeddingsProviderTypedDict(TypedDict):
"""
require_parameters: NotRequired[Nullable[bool]]
r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest."""
data_collection: NotRequired[Nullable[DataCollection]]
data_collection: NotRequired[Nullable[components_datacollection.DataCollection]]
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
- deny: use only providers which do not collect user data.
"""
zdr: NotRequired[Nullable[bool]]
r"""Whether to restrict routing to only ZDR (Zero Data Retention) endpoints. When true, only endpoints that do not retain prompts will be used."""
@@ -165,7 +206,7 @@ class CreateEmbeddingsProviderTypedDict(TypedDict):
r"""List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request."""
quantizations: NotRequired[Nullable[List[components_quantization.Quantization]]]
r"""A list of quantization levels to filter the provider by."""
sort: NotRequired[Nullable[Sort]]
sort: NotRequired[Nullable[components_providersort.ProviderSort]]
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
max_price: NotRequired[MaxPriceTypedDict]
r"""The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion."""
@@ -183,12 +224,13 @@ class CreateEmbeddingsProvider(BaseModel):
r"""Whether to filter providers to only those that support the parameters you've provided. If this setting is omitted or set to false, then providers will receive only the parameters they support, and ignore the rest."""
data_collection: Annotated[
OptionalNullable[DataCollection], PlainValidator(validate_open_enum(False))
OptionalNullable[components_datacollection.DataCollection],
PlainValidator(validate_open_enum(False)),
] = UNSET
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
- allow: (default) allow providers which store user data non-transiently and may train on it
- deny: use only providers which do not collect user data.
- deny: use only providers which do not collect user data.
"""
zdr: OptionalNullable[bool] = UNSET
@@ -217,7 +259,8 @@ class CreateEmbeddingsProvider(BaseModel):
r"""A list of quantization levels to filter the provider by."""
sort: Annotated[
OptionalNullable[Sort], PlainValidator(validate_open_enum(False))
OptionalNullable[components_providersort.ProviderSort],
PlainValidator(validate_open_enum(False)),
] = UNSET
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
@@ -278,41 +321,33 @@ class CreateEmbeddingsProvider(BaseModel):
return m
EncodingFormatBase64 = Literal["base64",]
EncodingFormatFloat = Literal["float",]
EncodingFormatTypedDict = TypeAliasType(
"EncodingFormatTypedDict", Union[EncodingFormatFloat, EncodingFormatBase64]
)
EncodingFormat = TypeAliasType(
"EncodingFormat", Union[EncodingFormatFloat, EncodingFormatBase64]
)
class CreateEmbeddingsRequestTypedDict(TypedDict):
input: InputTypedDict
input: InputUnionTypedDict
model: str
provider: NotRequired[CreateEmbeddingsProviderTypedDict]
encoding_format: NotRequired[EncodingFormatTypedDict]
encoding_format: NotRequired[EncodingFormat]
dimensions: NotRequired[int]
user: NotRequired[str]
provider: NotRequired[CreateEmbeddingsProviderTypedDict]
input_type: NotRequired[str]
class CreateEmbeddingsRequest(BaseModel):
input: Input
input: InputUnion
model: str
provider: Optional[CreateEmbeddingsProvider] = None
encoding_format: Annotated[
Optional[EncodingFormat], PlainValidator(validate_open_enum(False))
] = None
encoding_format: Optional[EncodingFormat] = None
dimensions: Optional[int] = None
user: Optional[str] = None
provider: Optional[CreateEmbeddingsProvider] = None
input_type: Optional[str] = None
Object = Literal["list",]
+2 -8
View File
@@ -39,22 +39,21 @@ GetParametersProvider = Union[
"Alibaba",
"Amazon Bedrock",
"Anthropic",
"Arcee",
"AtlasCloud",
"Atoma",
"Avian",
"Azure",
"BaseTen",
"Black Forest Labs",
"Cerebras",
"Chutes",
"Cirrascale",
"Clarifai",
"Cloudflare",
"Cohere",
"CrofAI",
"Crusoe",
"DeepInfra",
"DeepSeek",
"Enfer",
"Featherless",
"Fireworks",
"Friendli",
@@ -67,11 +66,8 @@ GetParametersProvider = Union[
"InferenceNet",
"Infermatic",
"Inflection",
"Kluster",
"Lambda",
"Liquid",
"Mancer 2",
"Meta",
"Minimax",
"ModelRun",
"Mistral",
@@ -81,7 +77,6 @@ GetParametersProvider = Union[
"NCompass",
"Nebius",
"NextBit",
"Nineteen",
"Novita",
"Nvidia",
"OpenAI",
@@ -96,7 +91,6 @@ GetParametersProvider = Union[
"Switchpoint",
"Targon",
"Together",
"Ubicloud",
"Venice",
"WandB",
"xAI",
+2 -2
View File
@@ -25,7 +25,7 @@ class Parameters(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetParametersData:
) -> operations.GetParametersResponse:
r"""Get a model's supported parameters and data about which are most popular
:param security:
@@ -136,7 +136,7 @@ class Parameters(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetParametersData:
) -> operations.GetParametersResponse:
r"""Get a model's supported parameters and data about which are most popular
:param security:
+3 -3
View File
@@ -6,7 +6,7 @@ from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, List, Mapping, Optional
from typing import Any, Mapping, Optional
class Providers(BaseSDK):
@@ -19,7 +19,7 @@ class Providers(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[operations.ListProvidersData]:
) -> operations.ListProvidersResponse:
r"""List all providers
:param retries: Override the default retry configuration for this method
@@ -103,7 +103,7 @@ class Providers(BaseSDK):
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> List[operations.ListProvidersData]:
) -> operations.ListProvidersResponse:
r"""List all providers
:param retries: Override the default retry configuration for this method
@@ -1,12 +1,26 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from typing import Any, Optional
from typing import Any, Optional, Type, TypeVar, overload
import httpx
from .serializers import unmarshal_json
from openrouter import errors
T = TypeVar("T")
@overload
def unmarshal_json_response(
typ: Type[T], http_res: httpx.Response, body: Optional[str] = None
) -> T: ...
@overload
def unmarshal_json_response(
typ: Any, http_res: httpx.Response, body: Optional[str] = None
) -> Any: ...
def unmarshal_json_response(
typ: Any, http_res: httpx.Response, body: Optional[str] = None
Generated
+1 -1
View File
@@ -211,7 +211,7 @@ wheels = [
[[package]]
name = "openrouter"
version = "0.0.15"
version = "0.0.16"
source = { editable = "." }
dependencies = [
{ name = "httpcore" },