Compare commits

...
Author SHA1 Message Date
David Alberto Adler 8d26214581 2025-09-07 21:48:10 +01:00
David Alberto Adler d66795f1d4 2025-09-07 21:45:53 +01:00
David Alberto Adler ed17d25183 2025-09-07 21:44:36 +01:00
David Alberto Adler f7f8677367 2025-09-07 21:41:34 +01:00
David Alberto Adler 041d7f8bef 2025-09-07 21:39:50 +01:00
David Alberto Adler 208909274f 2025-09-07 21:29:52 +01:00
David Alberto Adler 43720ce166 2025-09-07 21:29:07 +01:00
David Alberto Adler 7a11b80884 2025-09-07 21:28:38 +01:00
David Alberto Adler 03054b21e4 2025-09-07 21:23:12 +01:00
David Alberto Adler da48e8c4ea 2025-09-07 20:40:53 +01:00
61 changed files with 2568 additions and 1093 deletions
+1
View File
@@ -9,3 +9,4 @@ pyrightconfig.json
**/.speakeasy/temp/ **/.speakeasy/temp/
**/.speakeasy/logs/ **/.speakeasy/logs/
.speakeasy/reports .speakeasy/reports
.env
-90
View File
@@ -1,90 +0,0 @@
overlay: 1.0.0
x-speakeasy-jsonpath: rfc9535
info:
title: Overlay chat-completions-openapi.yaml => openapi.yaml
version: 0.0.0
actions:
- target: $["components"]["schemas"]["ChatCompletion"]["properties"]["system_fingerprint"]
update:
type: string
nullable: true
description: System fingerprint
- target: $["components"]["schemas"]["ChatCompletionChunk"]["properties"]["system_fingerprint"]
update:
type: string
nullable: true
- target: $["components"]["schemas"]
update:
ChatStreamCompletionCreateParams:
allOf:
- $ref: "#/components/schemas/ChatCompletionCreateParams"
- type: object
properties:
stream:
type: boolean
enum:
- true
default: true
description: Enable streaming response
- target: $["paths"]["/chat/completions"]["post"]["responses"]["200"]["content"]["application/json"]["schema"]
update:
$ref: '#/components/schemas/ChatCompletion'
- target: $["paths"]["/chat/completions"]["post"]["responses"]["200"]["content"]["application/json"]["schema"]
update:
description: Non-streaming response when stream=false
- target: $["paths"]["/chat/completions"]["post"]["responses"]["200"]["content"]["application/json"]["schema"]["oneOf"]
remove: true
- target: $["paths"]["/chat/completions"]["post"]["responses"]["200"]["content"]["text/event-stream"]
remove: true
- target: $["paths"]
update:
/chat/completions#stream:
post:
operationId: streamChatCompletion
summary: Create a chat completion
description: Creates a model response for the given chat conversation. Supports both streaming and non-streaming modes.
tags:
- Chat
requestBody:
description: Chat completion request parameters
required: true
content:
application/json:
schema:
$ref: '#/components/schemas/ChatStreamCompletionCreateParams'
responses:
'200':
description: Successful chat completion response
content:
text/event-stream:
x-speakeasy-sse-sentinel: '[DONE]'
schema:
type: object
required: [data]
properties:
data:
$ref: '#/components/schemas/ChatCompletionChunk'
'400':
description: Bad request - invalid parameters
content:
application/json:
schema:
$ref: '#/components/schemas/ChatCompletionError'
'401':
description: Unauthorized - invalid API key
content:
application/json:
schema:
$ref: '#/components/schemas/ChatCompletionError'
'429':
description: Too many requests - rate limit exceeded
content:
application/json:
schema:
$ref: '#/components/schemas/ChatCompletionError'
'500':
description: Internal server error
content:
application/json:
schema:
$ref: '#/components/schemas/ChatCompletionError'
@@ -1,28 +0,0 @@
overlay: 1.0.0
x-speakeasy-jsonpath: rfc9535
info:
title: Speakeasy Modifications
version: 0.0.2
x-speakeasy-metadata:
after: ""
before: ""
type: speakeasy-modifications
actions:
- target: $["paths"]["/chat/completions"]["post"]
update:
x-speakeasy-name-override: complete
x-speakeasy-metadata:
after: sdk.chat.complete()
before: sdk.Chat.createChatCompletion()
created_at: 1755805257797
reviewed_at: 1755805262583
type: method-name
- target: $["paths"]["/chat/completions#stream"]["post"]
update:
x-speakeasy-name-override: completeStream
x-speakeasy-metadata:
after: sdk.chat.completeStream()
before: sdk.Chat.streamChatCompletion()
created_at: 1755805257798
reviewed_at: 1755805262583
type: method-name
+12 -11
View File
@@ -1,19 +1,20 @@
lockVersion: 2.0.0 lockVersion: 2.0.0
id: 232c6d4f-b0fd-4172-8f1b-e2421566e9b4 id: 232c6d4f-b0fd-4172-8f1b-e2421566e9b4
management: management:
docChecksum: 003bbbc167e4db8bd3f147793a6648e1 docChecksum: 98b4f227e767bb91333b3b3469d93fa5
docVersion: 1.0.0 docVersion: 1.0.0
speakeasyVersion: 1.606.2 speakeasyVersion: 1.611.1
generationVersion: 2.687.1 generationVersion: 2.694.1
releaseVersion: 0.1.3 releaseVersion: 0.5.2
configChecksum: d572a56cfb69d7061ad0319f157ff5d8 configChecksum: 4619605fbeb6f4488feb5336aa62bab6
repoURL: https://github.com/speakeasy-sdks/openrouter-python-sdk.git repoURL: https://github.com/speakeasy-sdks/openrouter-python-sdk.git
installationURL: https://github.com/speakeasy-sdks/openrouter-python-sdk.git installationURL: https://github.com/speakeasy-sdks/openrouter-python-sdk.git
features: features:
python: python:
additionalDependencies: 1.0.0 additionalDependencies: 1.0.0
constsAndDefaults: 1.0.5 constsAndDefaults: 1.0.5
core: 5.19.9 core: 5.20.3
customCodeRegions: 0.1.1
defaultEnabledRetries: 0.2.0 defaultEnabledRetries: 0.2.0
devContainers: 3.0.0 devContainers: 3.0.0
enumUnions: 0.1.0 enumUnions: 0.1.0
@@ -29,7 +30,7 @@ features:
responseFormat: 1.0.1 responseFormat: 1.0.1
retries: 3.0.2 retries: 3.0.2
sdkHooks: 1.1.0 sdkHooks: 1.1.0
serverEvents: 1.0.7 serverEvents: 1.0.8
serverEventsSentinels: 0.1.0 serverEventsSentinels: 0.1.0
unions: 3.0.4 unions: 3.0.4
generatedFiles: generatedFiles:
@@ -308,16 +309,16 @@ examples:
"200": "200":
application/json: {"id": "<id>", "choices": [], "created": 6977.95, "model": "El Camino", "object": "chat.completion"} application/json: {"id": "<id>", "choices": [], "created": 6977.95, "model": "El Camino", "object": "chat.completion"}
"400": "400":
application/json: {"error": {"code": "<value>", "message": "<value>", "param": "<value>", "type": "<value>"}} application/json: {"error": {"code": null, "message": "<value>"}}
"500": "500":
application/json: {"error": {"code": "<value>", "message": "<value>", "param": "<value>", "type": "<value>"}} application/json: {"error": {"code": null, "message": "<value>"}}
streamChatCompletion: streamChatCompletion:
speakeasy-default-stream-chat-completion: speakeasy-default-stream-chat-completion:
requestBody: requestBody:
application/json: {"messages": [{"role": "user", "content": "Hello, how are you?"}], "stream": true, "temperature": 1, "top_p": 1} application/json: {"messages": [{"role": "user", "content": "Hello, how are you?"}], "stream": true, "temperature": 1, "top_p": 1}
responses: responses:
"400": "400":
application/json: {"error": {"code": "<value>", "message": "<value>", "param": "<value>", "type": "<value>"}} application/json: {"error": {"code": null, "message": "<value>"}}
"500": "500":
application/json: {"error": {"code": "<value>", "message": "<value>", "param": "<value>", "type": "<value>"}} application/json: {"error": {"code": null, "message": "<value>"}}
examplesVersion: 1.0.2 examplesVersion: 1.0.2
+6 -3
View File
@@ -25,18 +25,21 @@ generation:
generateNewTests: true generateNewTests: true
skipResponseBodyAssertions: false skipResponseBodyAssertions: false
python: python:
version: 0.1.3 version: 0.5.2
additionalDependencies: additionalDependencies:
dev: {} dev: {}
main: {} main: {}
allowedRedefinedBuiltins:
- id
- object
authors: authors:
- Speakeasy - Speakeasy
baseErrorName: OpenRouterError baseErrorName: OpenRouterError
clientServerStatusCodesAsErrors: true clientServerStatusCodesAsErrors: true
defaultErrorName: OpenRouterDefaultError defaultErrorName: OpenRouterDefaultError
description: Python Client SDK Generated by Speakeasy. description: Python Client SDK Generated by Speakeasy.
enableCustomCodeRegions: false enableCustomCodeRegions: true
enumFormat: enum enumFormat: union
envVarPrefix: OPENROUTER envVarPrefix: OPENROUTER
fixFlags: fixFlags:
responseRequiredSep2024: true responseRequiredSep2024: true
File diff suppressed because it is too large Load Diff
@@ -1545,4 +1545,4 @@ paths:
content: content:
application/json: application/json:
schema: schema:
$ref: '#/components/schemas/ChatCompletionError' $ref: '#/components/schemas/ChatCompletionError'
+30 -17
View File
@@ -17,7 +17,7 @@ servers:
default: openrouter.ai default: openrouter.ai
description: Production server description: Production server
security: security:
- BearerAuth: [] - ApiKey: []
tags: tags:
- name: Chat - name: Chat
description: Chat completion operations description: Chat completion operations
@@ -26,11 +26,17 @@ externalDocs:
url: https://openrouter.ai/docs url: https://openrouter.ai/docs
components: components:
securitySchemes: securitySchemes:
BearerAuth: ApiKey:
type: http type: http
scheme: bearer scheme: bearer
description: API key as bearer token in Authorization header description: API key as bearer token in Authorization header
schemas: schemas:
ChatCompletionChunkWrapper:
type: object
required: [data]
properties:
data:
$ref: '#/components/schemas/ChatCompletionChunk'
ChatCompletionMessageToolCall: ChatCompletionMessageToolCall:
type: object type: object
properties: properties:
@@ -450,7 +456,7 @@ components:
type: object type: object
properties: properties:
code: code:
type: string type: number
nullable: true nullable: true
message: message:
type: string type: string
@@ -462,8 +468,6 @@ components:
required: required:
- code - code
- message - message
- param
- type
description: Error object structure description: Error object structure
required: required:
- error - error
@@ -1057,7 +1061,8 @@ components:
type: string type: string
description: Unique user identifier description: Unique user identifier
models: models:
x-speakeasy-name-override: models_llm # Needed to avoid conflict with the `models` directory
x-speakeasy-name-override: fallback_models
type: array type: array
nullable: true nullable: true
items: items:
@@ -1082,15 +1087,17 @@ components:
description: > description: >
Whether to allow backup providers to serve requests Whether to allow backup providers to serve requests
- true: (default) when the primary provider (or your custom providers in "order") is unavailable, use the next best provider. - true: (default) when the primary provider (or your custom providers in "order") is unavailable, use
the next best provider.
- false: use only the primary/custom provider, and return the upstream error if it's unavailable. - false: use only the primary/custom provider, and return the upstream error if it's unavailable.
require_parameters: require_parameters:
type: boolean type: boolean
nullable: true nullable: true
description: >- 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. 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: data_collection:
type: string type: string
nullable: true nullable: true
@@ -1098,12 +1105,12 @@ components:
- deny - deny
- allow - allow
description: > description: >
Data collection setting. If no available model provider meets the requirement, your request will return an error. 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 - 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.
order: order:
type: array type: array
nullable: true nullable: true
@@ -1191,7 +1198,9 @@ components:
- Z.AI - Z.AI
- type: string - type: string
description: >- description: >-
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. 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: only:
type: array type: array
nullable: true nullable: true
@@ -1279,7 +1288,8 @@ components:
- Z.AI - Z.AI
- type: string - type: string
description: >- description: >-
List of provider slugs to allow. If provided, this list is merged with your account-wide allowed provider settings for this request. List of provider slugs to allow. If provided, this list is merged with your account-wide allowed
provider settings for this request.
ignore: ignore:
type: array type: array
nullable: true nullable: true
@@ -1367,7 +1377,8 @@ components:
- Z.AI - Z.AI
- type: string - type: string
description: >- description: >-
List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored provider settings for this request. List of provider slugs to ignore. If provided, this list is merged with your account-wide ignored
provider settings for this request.
quantizations: quantizations:
type: array type: array
nullable: true nullable: true
@@ -1392,7 +1403,8 @@ components:
- throughput - throughput
- latency - latency
description: >- description: >-
The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing is performed. The sorting strategy to use for this request, if "order" is not specified. When set, no load balancing
is performed.
max_price: max_price:
type: object type: object
properties: properties:
@@ -1423,7 +1435,8 @@ components:
- {} - {}
additionalProperties: false additionalProperties: false
description: >- description: >-
The object specifying the maximum price you want to pay for this request. USD price per million tokens, for prompt and completion. The object specifying the maximum price you want to pay for this request. USD price per million tokens,
for prompt and completion.
additionalProperties: false additionalProperties: false
description: When multiple model providers are available, optionally indicate your routing preference. description: When multiple model providers are available, optionally indicate your routing preference.
plugins: plugins:
@@ -1488,7 +1501,7 @@ components:
description: Chat completion request parameters description: Chat completion request parameters
ChatStreamCompletionCreateParams: ChatStreamCompletionCreateParams:
allOf: allOf:
- $ref: "#/components/schemas/ChatCompletionCreateParams" - $ref: '#/components/schemas/ChatCompletionCreateParams'
- type: object - type: object
properties: properties:
stream: stream:
+2 -7
View File
@@ -1,4 +1,4 @@
speakeasyVersion: 1.606.2 speakeasyVersion: 1.611.1
sources: sources:
OpenRouter Chat Completions API: OpenRouter Chat Completions API:
sourceNamespace: open-router-chat-completions-api sourceNamespace: open-router-chat-completions-api
@@ -14,18 +14,13 @@ targets:
sourceNamespace: open-router-chat-completions-api sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:30b19a8759608792fb4d27f6bf28d5982d7e2a8cf5b3faf34ba3507a62f9f106 sourceRevisionDigest: sha256:30b19a8759608792fb4d27f6bf28d5982d7e2a8cf5b3faf34ba3507a62f9f106
sourceBlobDigest: sha256:454f1b880a0882a70f78eacccb2c33e3d9d19134a0738b0e21487984a7bf2e63 sourceBlobDigest: sha256:454f1b880a0882a70f78eacccb2c33e3d9d19134a0738b0e21487984a7bf2e63
codeSamplesNamespace: open-router-chat-completions-api-python-code-samples
codeSamplesRevisionDigest: sha256:9ce1951254983ff6edc533d67fea93254d9e0d124057ce826721a1449a9ba36c
workflow: workflow:
workflowVersion: 1.0.0 workflowVersion: 1.0.0
speakeasyVersion: latest speakeasyVersion: latest
sources: sources:
OpenRouter Chat Completions API: OpenRouter Chat Completions API:
inputs: inputs:
- location: .speakeasy/OAS_files/chat-completions-openapi.yaml - location: .speakeasy/in.openapi.yaml
overlays:
- location: .speakeasy/OAS_files/overlay.yaml
- location: .speakeasy/OAS_files/speakeasy-modifications-overlay.yaml
output: .speakeasy/out.openapi.yaml output: .speakeasy/out.openapi.yaml
registry: registry:
location: registry.speakeasyapi.dev/sheldon-vaughn-test/sandbox/open-router-chat-completions-api location: registry.speakeasyapi.dev/sheldon-vaughn-test/sandbox/open-router-chat-completions-api
+1 -4
View File
@@ -3,10 +3,7 @@ speakeasyVersion: latest
sources: sources:
OpenRouter Chat Completions API: OpenRouter Chat Completions API:
inputs: inputs:
- location: .speakeasy/OAS_files/chat-completions-openapi.yaml - location: .speakeasy/in.openapi.yaml
overlays:
- location: .speakeasy/OAS_files/overlay.yaml
- location: .speakeasy/OAS_files/speakeasy-modifications-overlay.yaml
output: .speakeasy/out.openapi.yaml output: .speakeasy/out.openapi.yaml
registry: registry:
location: registry.speakeasyapi.dev/sheldon-vaughn-test/sandbox/open-router-chat-completions-api location: registry.speakeasyapi.dev/sheldon-vaughn-test/sandbox/open-router-chat-completions-api
+33 -33
View File
@@ -125,17 +125,17 @@ Generally, the SDK will work well with most IDEs out of the box. However, when u
```python ```python
# Synchronous Example # Synchronous Example
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -150,18 +150,18 @@ The same SDK client can also be used to make asynchronous requests by importing
```python ```python
# Asynchronous Example # Asynchronous Example
import asyncio import asyncio
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
async def main(): async def main():
async with OpenRouter( async with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = await open_router.chat.complete_async(messages=[ res = await open_router.chat.complete_async(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -180,23 +180,23 @@ asyncio.run(main())
This SDK supports the following security scheme globally: This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable | | Name | Type | Scheme | Environment Variable |
| ------------- | ---- | ----------- | ------------------------ | | --------- | ---- | ----------- | -------------------- |
| `bearer_auth` | http | HTTP Bearer | `OPENROUTER_BEARER_AUTH` | | `api_key` | http | HTTP Bearer | `OPENROUTER_API_KEY` |
To authenticate with the API the `bearer_auth` parameter must be set when initializing the SDK client instance. For example: To authenticate with the API the `api_key` parameter must be set when initializing the SDK client instance. For example:
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -235,17 +235,17 @@ The stream is also a [Context Manager][context-manager] and can be used with the
underlying connection when the context is exited. underlying connection when the context is exited.
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete_stream(messages=[ res = open_router.chat.complete_stream(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=True, temperature=1, top_p=1) ], stream=True, temperature=1, top_p=1)
@@ -269,18 +269,18 @@ Some of the endpoints in this SDK support retries. If you use the SDK without an
To change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call: To change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call:
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
from openrouter.utils import BackoffStrategy, RetryConfig from openrouter.utils import BackoffStrategy, RetryConfig
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1, ], stream=False, temperature=1, top_p=1,
@@ -293,19 +293,19 @@ with OpenRouter(
If you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK: If you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK:
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
from openrouter.utils import BackoffStrategy, RetryConfig from openrouter.utils import BackoffStrategy, RetryConfig
import os import os
with OpenRouter( with OpenRouter(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -332,19 +332,19 @@ with OpenRouter(
### Example ### Example
```python ```python
from openrouter import OpenRouter, errors, models from openrouter import OpenRouter, errors
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = None res = None
try: try:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -401,18 +401,18 @@ The default server `https://{provider_url}/api/v1` contains variables and is set
#### Example #### Example
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
provider_url="https://ruddy-guacamole.info/" provider_url="https://ruddy-guacamole.info/"
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -426,18 +426,18 @@ with OpenRouter(
The default server can be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example: The default server can be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example:
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
server_url="https://openrouter.ai/api/v1", server_url="https://openrouter.ai/api/v1",
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -542,7 +542,7 @@ import os
def main(): def main():
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
# Rest of application here... # Rest of application here...
@@ -551,7 +551,7 @@ def main():
async def amain(): async def amain():
async with OpenRouter( async with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
# Rest of application here... # Rest of application here...
``` ```
+33 -33
View File
@@ -125,17 +125,17 @@ Generally, the SDK will work well with most IDEs out of the box. However, when u
```python ```python
# Synchronous Example # Synchronous Example
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -150,18 +150,18 @@ The same SDK client can also be used to make asynchronous requests by importing
```python ```python
# Asynchronous Example # Asynchronous Example
import asyncio import asyncio
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
async def main(): async def main():
async with OpenRouter( async with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = await open_router.chat.complete_async(messages=[ res = await open_router.chat.complete_async(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -180,23 +180,23 @@ asyncio.run(main())
This SDK supports the following security scheme globally: This SDK supports the following security scheme globally:
| Name | Type | Scheme | Environment Variable | | Name | Type | Scheme | Environment Variable |
| ------------- | ---- | ----------- | ------------------------ | | --------- | ---- | ----------- | -------------------- |
| `bearer_auth` | http | HTTP Bearer | `OPENROUTER_BEARER_AUTH` | | `api_key` | http | HTTP Bearer | `OPENROUTER_API_KEY` |
To authenticate with the API the `bearer_auth` parameter must be set when initializing the SDK client instance. For example: To authenticate with the API the `api_key` parameter must be set when initializing the SDK client instance. For example:
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -235,17 +235,17 @@ The stream is also a [Context Manager][context-manager] and can be used with the
underlying connection when the context is exited. underlying connection when the context is exited.
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete_stream(messages=[ res = open_router.chat.complete_stream(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=True, temperature=1, top_p=1) ], stream=True, temperature=1, top_p=1)
@@ -269,18 +269,18 @@ Some of the endpoints in this SDK support retries. If you use the SDK without an
To change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call: To change the default retry strategy for a single API call, simply provide a `RetryConfig` object to the call:
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
from openrouter.utils import BackoffStrategy, RetryConfig from openrouter.utils import BackoffStrategy, RetryConfig
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1, ], stream=False, temperature=1, top_p=1,
@@ -293,19 +293,19 @@ with OpenRouter(
If you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK: If you'd like to override the default retry strategy for all operations that support retries, you can use the `retry_config` optional parameter when initializing the SDK:
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
from openrouter.utils import BackoffStrategy, RetryConfig from openrouter.utils import BackoffStrategy, RetryConfig
import os import os
with OpenRouter( with OpenRouter(
retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False), retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -332,19 +332,19 @@ with OpenRouter(
### Example ### Example
```python ```python
from openrouter import OpenRouter, errors, models from openrouter import OpenRouter, errors
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = None res = None
try: try:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -401,18 +401,18 @@ The default server `https://{provider_url}/api/v1` contains variables and is set
#### Example #### Example
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
provider_url="https://ruddy-guacamole.info/" provider_url="https://ruddy-guacamole.info/"
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -426,18 +426,18 @@ with OpenRouter(
The default server can be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example: The default server can be overridden globally by passing a URL to the `server_url: str` optional parameter when initializing the SDK client instance. For example:
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
server_url="https://openrouter.ai/api/v1", server_url="https://openrouter.ai/api/v1",
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -542,7 +542,7 @@ import os
def main(): def main():
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
# Rest of application here... # Rest of application here...
@@ -551,7 +551,7 @@ def main():
async def amain(): async def amain():
async with OpenRouter( async with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
# Rest of application here... # Rest of application here...
``` ```
+6 -6
View File
@@ -1,17 +1,17 @@
<!-- Start SDK Example Usage [usage] --> <!-- Start SDK Example Usage [usage] -->
```python ```python
# Synchronous Example # Synchronous Example
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -26,18 +26,18 @@ The same SDK client can also be used to make asynchronous requests by importing
```python ```python
# Asynchronous Example # Asynchronous Example
import asyncio import asyncio
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
async def main(): async def main():
async with OpenRouter( async with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = await open_router.chat.complete_async(messages=[ res = await open_router.chat.complete_async(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
+1 -1
View File
@@ -28,7 +28,7 @@ Chat completion request parameters
| `tools` | List[[models.ChatCompletionTool](../models/chatcompletiontool.md)] | :heavy_minus_sign: | Available tools for function calling | | | `tools` | List[[models.ChatCompletionTool](../models/chatcompletiontool.md)] | :heavy_minus_sign: | Available tools for function calling | |
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | | | `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | |
| `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | | | `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | |
| `models_llm` | List[*str*] | :heavy_minus_sign: | Order of models to fallback to for this request | | | `fallback_models` | List[*str*] | :heavy_minus_sign: | Order of models to fallback to for this request | |
| `reasoning_effort` | [OptionalNullable[models.ChatCompletionCreateParamsReasoningEffort]](../models/chatcompletioncreateparamsreasoningeffort.md) | :heavy_minus_sign: | Reasoning effort | | | `reasoning_effort` | [OptionalNullable[models.ChatCompletionCreateParamsReasoningEffort]](../models/chatcompletioncreateparamsreasoningeffort.md) | :heavy_minus_sign: | Reasoning effort | |
| `provider` | [OptionalNullable[models.ChatCompletionCreateParamsProvider]](../models/chatcompletioncreateparamsprovider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | | | `provider` | [OptionalNullable[models.ChatCompletionCreateParamsProvider]](../models/chatcompletioncreateparamsprovider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | |
| `plugins` | List[[models.ChatCompletionCreateParamsPluginUnion](../models/chatcompletioncreateparamspluginunion.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | | | `plugins` | List[[models.ChatCompletionCreateParamsPluginUnion](../models/chatcompletioncreateparamspluginunion.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
@@ -28,7 +28,7 @@ Chat completion request parameters
| `tools` | List[[models.ChatCompletionTool](../models/chatcompletiontool.md)] | :heavy_minus_sign: | Available tools for function calling | | | `tools` | List[[models.ChatCompletionTool](../models/chatcompletiontool.md)] | :heavy_minus_sign: | Available tools for function calling | |
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | | | `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | |
| `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | | | `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | |
| `models_llm` | List[*str*] | :heavy_minus_sign: | Order of models to fallback to for this request | | | `fallback_models` | List[*str*] | :heavy_minus_sign: | Order of models to fallback to for this request | |
| `reasoning_effort` | [OptionalNullable[models.ChatStreamCompletionCreateParamsReasoningEffort]](../models/chatstreamcompletioncreateparamsreasoningeffort.md) | :heavy_minus_sign: | Reasoning effort | | | `reasoning_effort` | [OptionalNullable[models.ChatStreamCompletionCreateParamsReasoningEffort]](../models/chatstreamcompletioncreateparamsreasoningeffort.md) | :heavy_minus_sign: | Reasoning effort | |
| `provider` | [OptionalNullable[models.ChatStreamCompletionCreateParamsProvider]](../models/chatstreamcompletioncreateparamsprovider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | | | `provider` | [OptionalNullable[models.ChatStreamCompletionCreateParamsProvider]](../models/chatstreamcompletioncreateparamsprovider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | |
| `plugins` | List[[models.ChatStreamCompletionCreateParamsPluginUnion](../models/chatstreamcompletioncreateparamspluginunion.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | | | `plugins` | List[[models.ChatStreamCompletionCreateParamsPluginUnion](../models/chatstreamcompletioncreateparamspluginunion.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
+6 -6
View File
@@ -5,9 +5,9 @@ Error object structure
## Fields ## Fields
| Field | Type | Required | Description | | Field | Type | Required | Description |
| ------------------ | ------------------ | ------------------ | ------------------ | | ----------------------- | ----------------------- | ----------------------- | ----------------------- |
| `code` | *Nullable[str]* | :heavy_check_mark: | N/A | | `code` | *Nullable[float]* | :heavy_check_mark: | N/A |
| `message` | *str* | :heavy_check_mark: | N/A | | `message` | *str* | :heavy_check_mark: | N/A |
| `param` | *Nullable[str]* | :heavy_check_mark: | N/A | | `param` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A |
| `type` | *str* | :heavy_check_mark: | N/A | | `type` | *Optional[str]* | :heavy_minus_sign: | N/A |
+1 -1
View File
@@ -5,4 +5,4 @@
| Field | Type | Required | Description | | Field | Type | Required | Description |
| ------------------ | ------------------ | ------------------ | ------------------ | | ------------------ | ------------------ | ------------------ | ------------------ |
| `bearer_auth` | *Optional[str]* | :heavy_minus_sign: | N/A | | `api_key` | *Optional[str]* | :heavy_minus_sign: | N/A |
+8 -8
View File
@@ -18,17 +18,17 @@ Creates a model response for the given chat conversation. Supports both streamin
<!-- UsageSnippet language="python" operationID="createChatCompletion" method="post" path="/chat/completions" --> <!-- UsageSnippet language="python" operationID="createChatCompletion" method="post" path="/chat/completions" -->
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(messages=[ res = open_router.chat.complete(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=False, temperature=1, top_p=1) ], stream=False, temperature=1, top_p=1)
@@ -63,7 +63,7 @@ with OpenRouter(
| `tools` | List[[models.ChatCompletionTool](../../models/chatcompletiontool.md)] | :heavy_minus_sign: | Available tools for function calling | | | `tools` | List[[models.ChatCompletionTool](../../models/chatcompletiontool.md)] | :heavy_minus_sign: | Available tools for function calling | |
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | | | `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | |
| `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | | | `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | |
| `models_llm` | List[*str*] | :heavy_minus_sign: | Order of models to fallback to for this request | | | `fallback_models` | List[*str*] | :heavy_minus_sign: | Order of models to fallback to for this request | |
| `reasoning_effort` | [OptionalNullable[models.ChatCompletionCreateParamsReasoningEffort]](../../models/chatcompletioncreateparamsreasoningeffort.md) | :heavy_minus_sign: | Reasoning effort | | | `reasoning_effort` | [OptionalNullable[models.ChatCompletionCreateParamsReasoningEffort]](../../models/chatcompletioncreateparamsreasoningeffort.md) | :heavy_minus_sign: | Reasoning effort | |
| `provider` | [OptionalNullable[models.ChatCompletionCreateParamsProvider]](../../models/chatcompletioncreateparamsprovider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | | | `provider` | [OptionalNullable[models.ChatCompletionCreateParamsProvider]](../../models/chatcompletioncreateparamsprovider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | |
| `plugins` | List[[models.ChatCompletionCreateParamsPluginUnion](../../models/chatcompletioncreateparamspluginunion.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | | | `plugins` | List[[models.ChatCompletionCreateParamsPluginUnion](../../models/chatcompletioncreateparamspluginunion.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
@@ -89,17 +89,17 @@ Creates a model response for the given chat conversation. Supports both streamin
<!-- UsageSnippet language="python" operationID="streamChatCompletion" method="post" path="/chat/completions#stream" --> <!-- UsageSnippet language="python" operationID="streamChatCompletion" method="post" path="/chat/completions#stream" -->
```python ```python
from openrouter import OpenRouter, models from openrouter import OpenRouter
import os import os
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_BEARER_AUTH", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete_stream(messages=[ res = open_router.chat.complete_stream(messages=[
{ {
"role": models.ChatCompletionUserMessageParamRole.USER, "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
], stream=True, temperature=1, top_p=1) ], stream=True, temperature=1, top_p=1)
@@ -136,7 +136,7 @@ with OpenRouter(
| `tools` | List[[models.ChatCompletionTool](../../models/chatcompletiontool.md)] | :heavy_minus_sign: | Available tools for function calling | | | `tools` | List[[models.ChatCompletionTool](../../models/chatcompletiontool.md)] | :heavy_minus_sign: | Available tools for function calling | |
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | | | `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | |
| `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | | | `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | |
| `models_llm` | List[*str*] | :heavy_minus_sign: | Order of models to fallback to for this request | | | `fallback_models` | List[*str*] | :heavy_minus_sign: | Order of models to fallback to for this request | |
| `reasoning_effort` | [OptionalNullable[models.ChatStreamCompletionCreateParamsReasoningEffort]](../../models/chatstreamcompletioncreateparamsreasoningeffort.md) | :heavy_minus_sign: | Reasoning effort | | | `reasoning_effort` | [OptionalNullable[models.ChatStreamCompletionCreateParamsReasoningEffort]](../../models/chatstreamcompletioncreateparamsreasoningeffort.md) | :heavy_minus_sign: | Reasoning effort | |
| `provider` | [OptionalNullable[models.ChatStreamCompletionCreateParamsProvider]](../../models/chatstreamcompletioncreateparamsprovider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | | | `provider` | [OptionalNullable[models.ChatStreamCompletionCreateParamsProvider]](../../models/chatstreamcompletioncreateparamsprovider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | |
| `plugins` | List[[models.ChatStreamCompletionCreateParamsPluginUnion](../../models/chatstreamcompletioncreateparamspluginunion.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | | | `plugins` | List[[models.ChatStreamCompletionCreateParamsPluginUnion](../../models/chatstreamcompletioncreateparamspluginunion.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
-1
View File
@@ -1 +0,0 @@
OPENROUTER_API_KEY="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"
+24
View File
@@ -0,0 +1,24 @@
dependencies = [
"openrouter",
"os",
"asyncio",
]
import os
import asyncio
from openrouter import OpenRouter
async def main():
sdk = OpenRouter(
api_key=os.getenv("OPENROUTER_API_KEY"),
)
result = await sdk.chat.complete_async(
messages=[
{"role": "user", "content": "Hello, world!"},
],
model="openai/gpt-3.5-turbo",
)
print("Basic async completion:", result)
if __name__ == "__main__":
asyncio.run(main())
+32
View File
@@ -0,0 +1,32 @@
dependencies = [
"openrouter",
"os",
"asyncio",
]
import os
import asyncio
from openrouter import OpenRouter
async def main():
open_router = OpenRouter(
api_key=os.getenv("OPENROUTER_API_KEY", ""),
)
res = await open_router.chat.complete_async(
messages=[
{
"role": "user",
"content": "Hello, how are you?",
},
],
model="openai/gpt-3.5-turbo",
stream=True
)
async for event in res: # type: ignore
if event.data.choices and event.data.choices[0].delta.content:
print(event.data.choices[0].delta.content, end='', flush=True)
print()
if __name__ == "__main__":
asyncio.run(main())
+3 -4
View File
@@ -8,13 +8,12 @@ import os
from openrouter import OpenRouter from openrouter import OpenRouter
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_API_KEY"), api_key=os.getenv("OPENROUTER_API_KEY"),
) as sdk: ) as sdk:
result = sdk.chat.complete( result = sdk.chat.complete(
model="openai/gpt-3.5-turbo",
messages=[ messages=[
{"role": "user", "content": "Hello, world!"}, {"role": "user", "content": "Hello, world!"},
], ],
model="openai/gpt-3.5-turbo",
) )
print("Basic completion:", result)
print(result)
+13 -11
View File
@@ -5,22 +5,24 @@ dependencies = [
] ]
import os import os
from openrouter import OpenRouter, models from openrouter import OpenRouter
with OpenRouter( with OpenRouter(
bearer_auth=os.getenv("OPENROUTER_API_KEY", ""), api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router: ) as open_router:
res = open_router.chat.complete(
res = open_router.chat.complete_stream(messages=[ messages=[
{ {
"role": "user", "role": "user",
"content": "Hello, how are you?", "content": "Hello, how are you?",
}, },
],
], model="openai/gpt-3.5-turbo", stream=True, temperature=1, top_p=1) model="openai/gpt-3.5-turbo",
stream=True
)
with res as event_stream: with res as event_stream:
for event in event_stream: for event in event_stream:
if event.data.choices and event.data.choices[0].delta.content: if event.data.choices and event.data.choices[0].delta.content:
print(event.data.choices[0].delta.content, end='', flush=True) print(event.data.choices[0].delta.content, end='', flush=True)
print() # New line at the end print()
+2 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "openrouter" name = "openrouter"
version = "0.1.3" version = "0.5.2"
description = "Python Client SDK Generated by Speakeasy." description = "Python Client SDK Generated by Speakeasy."
authors = [{ name = "Speakeasy" },] authors = [{ name = "Speakeasy" },]
readme = "README-PYPI.md" readme = "README-PYPI.md"
@@ -30,6 +30,7 @@ build-backend = "setuptools.build_meta"
[tool.pytest.ini_options] [tool.pytest.ini_options]
asyncio_default_fixture_loop_scope = "function" asyncio_default_fixture_loop_scope = "function"
asyncio_mode = "auto"
pythonpath = ["src"] pythonpath = ["src"]
[tool.mypy] [tool.mypy]
+3 -3
View File
@@ -3,10 +3,10 @@
import importlib.metadata import importlib.metadata
__title__: str = "openrouter" __title__: str = "openrouter"
__version__: str = "0.1.3" __version__: str = "0.5.2"
__openapi_doc_version__: str = "1.0.0" __openapi_doc_version__: str = "1.0.0"
__gen_version__: str = "2.687.1" __gen_version__: str = "2.694.1"
__user_agent__: str = "speakeasy-sdk/python 0.1.3 2.687.1 1.0.0 openrouter" __user_agent__: str = "speakeasy-sdk/python 0.5.2 2.694.1 1.0.0 openrouter"
try: try:
if __package__ is not None: if __package__ is not None:
+11 -1
View File
@@ -15,9 +15,19 @@ from urllib.parse import parse_qs, urlparse
class BaseSDK: class BaseSDK:
sdk_configuration: SDKConfiguration sdk_configuration: SDKConfiguration
parent_ref: Optional[object] = None
"""
Reference to the root SDK instance, if any. This will prevent it from
being garbage collected while there are active streams.
"""
def __init__(self, sdk_config: SDKConfiguration) -> None: def __init__(
self,
sdk_config: SDKConfiguration,
parent_ref: Optional[object] = None,
) -> None:
self.sdk_configuration = sdk_config self.sdk_configuration = sdk_config
self.parent_ref = parent_ref
def _get_url(self, base_url, url_variables): def _get_url(self, base_url, url_variables):
sdk_url, sdk_variables = self.sdk_configuration.get_server_details() sdk_url, sdk_variables = self.sdk_configuration.get_server_details()
+14 -12
View File
@@ -69,7 +69,7 @@ class Chat(BaseSDK):
] = None, ] = None,
top_p: OptionalNullable[float] = 1, top_p: OptionalNullable[float] = 1,
user: Optional[str] = None, user: Optional[str] = None,
models_llm: OptionalNullable[List[str]] = UNSET, fallback_models: OptionalNullable[List[str]] = UNSET,
reasoning_effort: OptionalNullable[ reasoning_effort: OptionalNullable[
models.ChatCompletionCreateParamsReasoningEffort models.ChatCompletionCreateParamsReasoningEffort
] = UNSET, ] = UNSET,
@@ -115,7 +115,7 @@ class Chat(BaseSDK):
:param tools: Available tools for function calling :param tools: Available tools for function calling
:param top_p: Nucleus sampling parameter (0-1) :param top_p: Nucleus sampling parameter (0-1)
:param user: Unique user identifier :param user: Unique user identifier
:param models_llm: Order of models to fallback to for this request :param fallback_models: Order of models to fallback to for this request
:param reasoning_effort: Reasoning effort :param reasoning_effort: Reasoning effort
:param provider: When multiple model providers are available, optionally indicate your routing preference. :param provider: When multiple model providers are available, optionally indicate your routing preference.
:param plugins: Plugins you want to enable for this request, including their settings. :param plugins: Plugins you want to enable for this request, including their settings.
@@ -170,7 +170,7 @@ class Chat(BaseSDK):
), ),
top_p=top_p, top_p=top_p,
user=user, user=user,
models_llm=models_llm, fallback_models=fallback_models,
reasoning_effort=reasoning_effort, reasoning_effort=reasoning_effort,
provider=utils.get_pydantic_model( provider=utils.get_pydantic_model(
provider, OptionalNullable[models.ChatCompletionCreateParamsProvider] provider, OptionalNullable[models.ChatCompletionCreateParamsProvider]
@@ -305,7 +305,7 @@ class Chat(BaseSDK):
] = None, ] = None,
top_p: OptionalNullable[float] = 1, top_p: OptionalNullable[float] = 1,
user: Optional[str] = None, user: Optional[str] = None,
models_llm: OptionalNullable[List[str]] = UNSET, fallback_models: OptionalNullable[List[str]] = UNSET,
reasoning_effort: OptionalNullable[ reasoning_effort: OptionalNullable[
models.ChatCompletionCreateParamsReasoningEffort models.ChatCompletionCreateParamsReasoningEffort
] = UNSET, ] = UNSET,
@@ -351,7 +351,7 @@ class Chat(BaseSDK):
:param tools: Available tools for function calling :param tools: Available tools for function calling
:param top_p: Nucleus sampling parameter (0-1) :param top_p: Nucleus sampling parameter (0-1)
:param user: Unique user identifier :param user: Unique user identifier
:param models_llm: Order of models to fallback to for this request :param fallback_models: Order of models to fallback to for this request
:param reasoning_effort: Reasoning effort :param reasoning_effort: Reasoning effort
:param provider: When multiple model providers are available, optionally indicate your routing preference. :param provider: When multiple model providers are available, optionally indicate your routing preference.
:param plugins: Plugins you want to enable for this request, including their settings. :param plugins: Plugins you want to enable for this request, including their settings.
@@ -406,7 +406,7 @@ class Chat(BaseSDK):
), ),
top_p=top_p, top_p=top_p,
user=user, user=user,
models_llm=models_llm, fallback_models=fallback_models,
reasoning_effort=reasoning_effort, reasoning_effort=reasoning_effort,
provider=utils.get_pydantic_model( provider=utils.get_pydantic_model(
provider, OptionalNullable[models.ChatCompletionCreateParamsProvider] provider, OptionalNullable[models.ChatCompletionCreateParamsProvider]
@@ -541,7 +541,7 @@ class Chat(BaseSDK):
] = None, ] = None,
top_p: OptionalNullable[float] = 1, top_p: OptionalNullable[float] = 1,
user: Optional[str] = None, user: Optional[str] = None,
models_llm: OptionalNullable[List[str]] = UNSET, fallback_models: OptionalNullable[List[str]] = UNSET,
reasoning_effort: OptionalNullable[ reasoning_effort: OptionalNullable[
models.ChatStreamCompletionCreateParamsReasoningEffort models.ChatStreamCompletionCreateParamsReasoningEffort
] = UNSET, ] = UNSET,
@@ -587,7 +587,7 @@ class Chat(BaseSDK):
:param tools: Available tools for function calling :param tools: Available tools for function calling
:param top_p: Nucleus sampling parameter (0-1) :param top_p: Nucleus sampling parameter (0-1)
:param user: Unique user identifier :param user: Unique user identifier
:param models_llm: Order of models to fallback to for this request :param fallback_models: Order of models to fallback to for this request
:param reasoning_effort: Reasoning effort :param reasoning_effort: Reasoning effort
:param provider: When multiple model providers are available, optionally indicate your routing preference. :param provider: When multiple model providers are available, optionally indicate your routing preference.
:param plugins: Plugins you want to enable for this request, including their settings. :param plugins: Plugins you want to enable for this request, including their settings.
@@ -643,7 +643,7 @@ class Chat(BaseSDK):
), ),
top_p=top_p, top_p=top_p,
user=user, user=user,
models_llm=models_llm, fallback_models=fallback_models,
reasoning_effort=reasoning_effort, reasoning_effort=reasoning_effort,
provider=utils.get_pydantic_model( provider=utils.get_pydantic_model(
provider, provider,
@@ -706,6 +706,7 @@ class Chat(BaseSDK):
raw, models.StreamChatCompletionResponseBody raw, models.StreamChatCompletionResponseBody
), ),
sentinel="[DONE]", sentinel="[DONE]",
client_ref=self,
) )
if utils.match_response(http_res, ["400", "401", "429"], "application/json"): if utils.match_response(http_res, ["400", "401", "429"], "application/json"):
http_res_text = utils.stream_to_text(http_res) http_res_text = utils.stream_to_text(http_res)
@@ -792,7 +793,7 @@ class Chat(BaseSDK):
] = None, ] = None,
top_p: OptionalNullable[float] = 1, top_p: OptionalNullable[float] = 1,
user: Optional[str] = None, user: Optional[str] = None,
models_llm: OptionalNullable[List[str]] = UNSET, fallback_models: OptionalNullable[List[str]] = UNSET,
reasoning_effort: OptionalNullable[ reasoning_effort: OptionalNullable[
models.ChatStreamCompletionCreateParamsReasoningEffort models.ChatStreamCompletionCreateParamsReasoningEffort
] = UNSET, ] = UNSET,
@@ -838,7 +839,7 @@ class Chat(BaseSDK):
:param tools: Available tools for function calling :param tools: Available tools for function calling
:param top_p: Nucleus sampling parameter (0-1) :param top_p: Nucleus sampling parameter (0-1)
:param user: Unique user identifier :param user: Unique user identifier
:param models_llm: Order of models to fallback to for this request :param fallback_models: Order of models to fallback to for this request
:param reasoning_effort: Reasoning effort :param reasoning_effort: Reasoning effort
:param provider: When multiple model providers are available, optionally indicate your routing preference. :param provider: When multiple model providers are available, optionally indicate your routing preference.
:param plugins: Plugins you want to enable for this request, including their settings. :param plugins: Plugins you want to enable for this request, including their settings.
@@ -894,7 +895,7 @@ class Chat(BaseSDK):
), ),
top_p=top_p, top_p=top_p,
user=user, user=user,
models_llm=models_llm, fallback_models=fallback_models,
reasoning_effort=reasoning_effort, reasoning_effort=reasoning_effort,
provider=utils.get_pydantic_model( provider=utils.get_pydantic_model(
provider, provider,
@@ -957,6 +958,7 @@ class Chat(BaseSDK):
raw, models.StreamChatCompletionResponseBody raw, models.StreamChatCompletionResponseBody
), ),
sentinel="[DONE]", sentinel="[DONE]",
client_ref=self,
) )
if utils.match_response(http_res, ["400", "401", "429"], "application/json"): if utils.match_response(http_res, ["400", "401", "429"], "application/json"):
http_res_text = await utils.stream_to_text_async(http_res) http_res_text = await utils.stream_to_text_async(http_res)
+15 -3
View File
@@ -1,14 +1,15 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .openroutererror import OpenRouterError
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from importlib import import_module from importlib import import_module
import builtins import builtins
import sys
if TYPE_CHECKING: if TYPE_CHECKING:
from .chatcompletionerror import ChatCompletionError, ChatCompletionErrorData from .chatcompletionerror import ChatCompletionError, ChatCompletionErrorData
from .no_response_error import NoResponseError from .no_response_error import NoResponseError
from .openrouterdefaulterror import OpenRouterDefaultError from .openrouterdefaulterror import OpenRouterDefaultError
from .openroutererror import OpenRouterError
from .responsevalidationerror import ResponseValidationError from .responsevalidationerror import ResponseValidationError
__all__ = [ __all__ = [
@@ -25,11 +26,22 @@ _dynamic_imports: dict[str, str] = {
"ChatCompletionErrorData": ".chatcompletionerror", "ChatCompletionErrorData": ".chatcompletionerror",
"NoResponseError": ".no_response_error", "NoResponseError": ".no_response_error",
"OpenRouterDefaultError": ".openrouterdefaulterror", "OpenRouterDefaultError": ".openrouterdefaulterror",
"OpenRouterError": ".openroutererror",
"ResponseValidationError": ".responsevalidationerror", "ResponseValidationError": ".responsevalidationerror",
} }
def dynamic_import(modname, retries=3):
for attempt in range(retries):
try:
return import_module(modname, __package__)
except KeyError:
# Clear any half-initialized module and retry
sys.modules.pop(modname, None)
if attempt == retries - 1:
break
raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")
def __getattr__(attr_name: str) -> object: def __getattr__(attr_name: str) -> object:
module_name = _dynamic_imports.get(attr_name) module_name = _dynamic_imports.get(attr_name)
if module_name is None: if module_name is None:
@@ -38,7 +50,7 @@ def __getattr__(attr_name: str) -> object:
) )
try: try:
module = import_module(module_name, __package__) module = dynamic_import(module_name)
result = getattr(module, attr_name) result = getattr(module, attr_name)
return result return result
except ImportError as e: except ImportError as e:
+14 -1
View File
@@ -3,6 +3,7 @@
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from importlib import import_module from importlib import import_module
import builtins import builtins
import sys
if TYPE_CHECKING: if TYPE_CHECKING:
from .annotationdetail import AnnotationDetail, AnnotationDetailTypedDict from .annotationdetail import AnnotationDetail, AnnotationDetailTypedDict
@@ -931,6 +932,18 @@ _dynamic_imports: dict[str, str] = {
} }
def dynamic_import(modname, retries=3):
for attempt in range(retries):
try:
return import_module(modname, __package__)
except KeyError:
# Clear any half-initialized module and retry
sys.modules.pop(modname, None)
if attempt == retries - 1:
break
raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")
def __getattr__(attr_name: str) -> object: def __getattr__(attr_name: str) -> object:
module_name = _dynamic_imports.get(attr_name) module_name = _dynamic_imports.get(attr_name)
if module_name is None: if module_name is None:
@@ -939,7 +952,7 @@ def __getattr__(attr_name: str) -> object:
) )
try: try:
module = import_module(module_name, __package__) module = dynamic_import(module_name)
result = getattr(module, attr_name) result = getattr(module, attr_name)
return result return result
except ImportError as e: except ImportError as e:
+2 -4
View File
@@ -3,7 +3,6 @@
from __future__ import annotations from __future__ import annotations
from .chatcompletionchoice import ChatCompletionChoice, ChatCompletionChoiceTypedDict from .chatcompletionchoice import ChatCompletionChoice, ChatCompletionChoiceTypedDict
from .completionusage import CompletionUsage, CompletionUsageTypedDict from .completionusage import CompletionUsage, CompletionUsageTypedDict
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -12,12 +11,11 @@ from openrouter.types import (
UNSET_SENTINEL, UNSET_SENTINEL,
) )
from pydantic import model_serializer from pydantic import model_serializer
from typing import List, Optional from typing import List, Literal, Optional
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class ChatCompletionObject(str, Enum): ChatCompletionObject = Literal["chat.completion"]
CHAT_COMPLETION = "chat.completion"
class ChatCompletionTypedDict(TypedDict): class ChatCompletionTypedDict(TypedDict):
@@ -9,7 +9,6 @@ from .chatcompletionmessagetoolcall import (
ChatCompletionMessageToolCall, ChatCompletionMessageToolCall,
ChatCompletionMessageToolCallTypedDict, ChatCompletionMessageToolCallTypedDict,
) )
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -18,13 +17,11 @@ from openrouter.types import (
UNSET_SENTINEL, UNSET_SENTINEL,
) )
from pydantic import model_serializer from pydantic import model_serializer
from typing import Any, List, Optional, Union from typing import Any, List, Literal, Optional, Union
from typing_extensions import NotRequired, TypeAliasType, TypedDict from typing_extensions import NotRequired, TypeAliasType, TypedDict
class ChatCompletionAssistantMessageParamRole(str, Enum): ChatCompletionAssistantMessageParamRole = Literal["assistant"]
ASSISTANT = "assistant"
ChatCompletionAssistantMessageParamContentTypedDict = TypeAliasType( ChatCompletionAssistantMessageParamContentTypedDict = TypeAliasType(
"ChatCompletionAssistantMessageParamContentTypedDict", "ChatCompletionAssistantMessageParamContentTypedDict",
@@ -6,7 +6,6 @@ from .chatcompletiontokenlogprobs import (
ChatCompletionTokenLogprobs, ChatCompletionTokenLogprobs,
ChatCompletionTokenLogprobsTypedDict, ChatCompletionTokenLogprobsTypedDict,
) )
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -15,17 +14,14 @@ from openrouter.types import (
UNSET_SENTINEL, UNSET_SENTINEL,
) )
from pydantic import model_serializer from pydantic import model_serializer
from typing import Literal
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class ChatCompletionChoiceFinishReason(str, Enum): ChatCompletionChoiceFinishReason = Literal[
r"""Reason the completion finished""" "tool_calls", "stop", "length", "content_filter", "error"
]
TOOL_CALLS = "tool_calls" r"""Reason the completion finished"""
STOP = "stop"
LENGTH = "length"
CONTENT_FILTER = "content_filter"
ERROR = "error"
class ChatCompletionChoiceTypedDict(TypedDict): class ChatCompletionChoiceTypedDict(TypedDict):
+2 -4
View File
@@ -6,7 +6,6 @@ from .chatcompletionchunkchoice import (
ChatCompletionChunkChoiceTypedDict, ChatCompletionChunkChoiceTypedDict,
) )
from .completionusage import CompletionUsage, CompletionUsageTypedDict from .completionusage import CompletionUsage, CompletionUsageTypedDict
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -15,12 +14,11 @@ from openrouter.types import (
UNSET_SENTINEL, UNSET_SENTINEL,
) )
from pydantic import model_serializer from pydantic import model_serializer
from typing import List, Optional from typing import List, Literal, Optional
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class ChatCompletionChunkObject(str, Enum): ChatCompletionChunkObject = Literal["chat.completion.chunk"]
CHAT_COMPLETION_CHUNK = "chat.completion.chunk"
class ChatCompletionChunkTypedDict(TypedDict): class ChatCompletionChunkTypedDict(TypedDict):
@@ -9,7 +9,6 @@ from .chatcompletiontokenlogprobs import (
ChatCompletionTokenLogprobs, ChatCompletionTokenLogprobs,
ChatCompletionTokenLogprobsTypedDict, ChatCompletionTokenLogprobsTypedDict,
) )
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -18,15 +17,13 @@ from openrouter.types import (
UNSET_SENTINEL, UNSET_SENTINEL,
) )
from pydantic import model_serializer from pydantic import model_serializer
from typing import Literal
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class ChatCompletionChunkChoiceFinishReason(str, Enum): ChatCompletionChunkChoiceFinishReason = Literal[
TOOL_CALLS = "tool_calls" "tool_calls", "stop", "length", "content_filter", "error"
STOP = "stop" ]
LENGTH = "length"
CONTENT_FILTER = "content_filter"
ERROR = "error"
class ChatCompletionChunkChoiceTypedDict(TypedDict): class ChatCompletionChunkChoiceTypedDict(TypedDict):
@@ -7,7 +7,6 @@ from .chatcompletionchunkchoicedeltatoolcall import (
ChatCompletionChunkChoiceDeltaToolCallTypedDict, ChatCompletionChunkChoiceDeltaToolCallTypedDict,
) )
from .reasoningdetail import ReasoningDetail, ReasoningDetailTypedDict from .reasoningdetail import ReasoningDetail, ReasoningDetailTypedDict
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -16,14 +15,12 @@ from openrouter.types import (
UNSET_SENTINEL, UNSET_SENTINEL,
) )
from pydantic import model_serializer from pydantic import model_serializer
from typing import List, Optional from typing import List, Literal, Optional
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class ChatCompletionChunkChoiceDeltaRole(str, Enum): ChatCompletionChunkChoiceDeltaRole = Literal["assistant"]
r"""The role of the message author""" r"""The role of the message author"""
ASSISTANT = "assistant"
class ChatCompletionChunkChoiceDeltaTypedDict(TypedDict): class ChatCompletionChunkChoiceDeltaTypedDict(TypedDict):
@@ -1,16 +1,13 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import Optional from typing import Literal, Optional
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class ChatCompletionChunkChoiceDeltaToolCallType(str, Enum): ChatCompletionChunkChoiceDeltaToolCallType = Literal["function"]
r"""Tool call type""" r"""Tool call type"""
FUNCTION = "function"
class ChatCompletionChunkChoiceDeltaToolCallFunctionTypedDict(TypedDict): class ChatCompletionChunkChoiceDeltaToolCallFunctionTypedDict(TypedDict):
@@ -1,26 +1,18 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
import pydantic import pydantic
from typing import Literal
from typing_extensions import Annotated, TypedDict from typing_extensions import Annotated, TypedDict
class ChatCompletionContentPartAudioType(str, Enum): ChatCompletionContentPartAudioType = Literal["input_audio"]
INPUT_AUDIO = "input_audio"
ChatCompletionContentPartAudioFormat = Literal[
class ChatCompletionContentPartAudioFormat(str, Enum): "wav", "mp3", "flac", "m4a", "ogg", "pcm16", "pcm24"
r"""Audio format""" ]
r"""Audio format"""
WAV = "wav"
MP3 = "mp3"
FLAC = "flac"
M4A = "m4a"
OGG = "ogg"
PCM16 = "pcm16"
PCM24 = "pcm24"
class InputAudioTypedDict(TypedDict): class InputAudioTypedDict(TypedDict):
@@ -1,22 +1,15 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import Optional from typing import Literal, Optional
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class ChatCompletionContentPartImageType(str, Enum): ChatCompletionContentPartImageType = Literal["image_url"]
IMAGE_URL = "image_url"
Detail = Literal["auto", "low", "high"]
class Detail(str, Enum): r"""Image detail level for vision models"""
r"""Image detail level for vision models"""
AUTO = "auto"
LOW = "low"
HIGH = "high"
class ChatCompletionContentPartImageImageURLTypedDict(TypedDict): class ChatCompletionContentPartImageImageURLTypedDict(TypedDict):
@@ -1,13 +1,12 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import Literal
from typing_extensions import TypedDict from typing_extensions import TypedDict
class ChatCompletionContentPartTextType(str, Enum): ChatCompletionContentPartTextType = Literal["text"]
TEXT = "text"
class ChatCompletionContentPartTextTypedDict(TypedDict): class ChatCompletionContentPartTextTypedDict(TypedDict):
@@ -14,7 +14,6 @@ from .responseformatjsonschemaschema import (
ResponseFormatJSONSchemaSchema, ResponseFormatJSONSchemaSchema,
ResponseFormatJSONSchemaSchemaTypedDict, ResponseFormatJSONSchemaSchemaTypedDict,
) )
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -24,17 +23,12 @@ from openrouter.types import (
) )
import pydantic import pydantic
from pydantic import model_serializer from pydantic import model_serializer
from typing import Any, Dict, List, Optional, Union from typing import Any, Dict, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
class ChatCompletionCreateParamsEffort(str, Enum): ChatCompletionCreateParamsEffort = Literal["high", "medium", "low", "minimal"]
r"""OpenAI-style reasoning effort setting""" r"""OpenAI-style reasoning effort setting"""
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
MINIMAL = "minimal"
class ChatCompletionCreateParamsReasoningTypedDict(TypedDict): class ChatCompletionCreateParamsReasoningTypedDict(TypedDict):
@@ -94,8 +88,7 @@ class ChatCompletionCreateParamsReasoning(BaseModel):
return m return m
class ChatCompletionCreateParamsTypePython(str, Enum): ChatCompletionCreateParamsTypePython = Literal["python"]
PYTHON = "python"
class ChatCompletionCreateParamsResponseFormatPythonTypedDict(TypedDict): class ChatCompletionCreateParamsResponseFormatPythonTypedDict(TypedDict):
@@ -110,8 +103,7 @@ class ChatCompletionCreateParamsResponseFormatPython(BaseModel):
type: ChatCompletionCreateParamsTypePython type: ChatCompletionCreateParamsTypePython
class ChatCompletionCreateParamsTypeGrammar(str, Enum): ChatCompletionCreateParamsTypeGrammar = Literal["grammar"]
GRAMMAR = "grammar"
class ChatCompletionCreateParamsResponseFormatGrammarTypedDict(TypedDict): class ChatCompletionCreateParamsResponseFormatGrammarTypedDict(TypedDict):
@@ -131,8 +123,7 @@ class ChatCompletionCreateParamsResponseFormatGrammar(BaseModel):
r"""Custom grammar for text generation""" r"""Custom grammar for text generation"""
class ChatCompletionCreateParamsTypeJSONSchema(str, Enum): ChatCompletionCreateParamsTypeJSONSchema = Literal["json_schema"]
JSON_SCHEMA = "json_schema"
class ChatCompletionCreateParamsJSONSchemaTypedDict(TypedDict): class ChatCompletionCreateParamsJSONSchemaTypedDict(TypedDict):
@@ -207,8 +198,7 @@ class ChatCompletionCreateParamsResponseFormatJSONSchema(BaseModel):
json_schema: ChatCompletionCreateParamsJSONSchema json_schema: ChatCompletionCreateParamsJSONSchema
class ChatCompletionCreateParamsTypeJSONObject(str, Enum): ChatCompletionCreateParamsTypeJSONObject = Literal["json_object"]
JSON_OBJECT = "json_object"
class ChatCompletionCreateParamsResponseFormatJSONObjectTypedDict(TypedDict): class ChatCompletionCreateParamsResponseFormatJSONObjectTypedDict(TypedDict):
@@ -223,8 +213,7 @@ class ChatCompletionCreateParamsResponseFormatJSONObject(BaseModel):
type: ChatCompletionCreateParamsTypeJSONObject type: ChatCompletionCreateParamsTypeJSONObject
class ChatCompletionCreateParamsTypeText(str, Enum): ChatCompletionCreateParamsTypeText = Literal["text"]
TEXT = "text"
class ChatCompletionCreateParamsResponseFormatTextTypedDict(TypedDict): class ChatCompletionCreateParamsResponseFormatTextTypedDict(TypedDict):
@@ -291,106 +280,96 @@ class ChatCompletionCreateParamsStreamOptions(BaseModel):
r"""Include usage information in streaming response""" r"""Include usage information in streaming response"""
class ChatCompletionCreateParamsReasoningEffort(str, Enum): ChatCompletionCreateParamsReasoningEffort = Literal["high", "medium", "low", "minimal"]
r"""Reasoning effort""" r"""Reasoning effort"""
HIGH = "high" ChatCompletionCreateParamsDataCollection = Literal["deny", "allow"]
MEDIUM = "medium" r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
LOW = "low" - allow: (default) allow providers which store user data non-transiently and may train on it
MINIMAL = "minimal" - deny: use only providers which do not collect user data.
"""
class ChatCompletionCreateParamsDataCollection(str, Enum): ChatCompletionCreateParamsOrderEnum = Literal[
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error. "AnyScale",
- allow: (default) allow providers which store user data non-transiently and may train on it "Cent-ML",
- deny: use only providers which do not collect user data. "HuggingFace",
"Hyperbolic 2",
""" "Lepton",
"Lynn 2",
DENY = "deny" "Lynn",
ALLOW = "allow" "Mancer",
"Modal",
"OctoAI",
class ChatCompletionCreateParamsOrderEnum(str, Enum): "Recursal",
ANY_SCALE = "AnyScale" "Reflection",
CENT_ML = "Cent-ML" "Replicate",
HUGGING_FACE = "HuggingFace" "SambaNova 2",
HYPERBOLIC_2 = "Hyperbolic 2" "SF Compute",
LEPTON = "Lepton" "Together 2",
LYNN_2 = "Lynn 2" "01.AI",
LYNN = "Lynn" "AI21",
MANCER = "Mancer" "AionLabs",
MODAL = "Modal" "Alibaba",
OCTO_AI = "OctoAI" "Amazon Bedrock",
RECURSAL = "Recursal" "Anthropic",
REFLECTION = "Reflection" "AtlasCloud",
REPLICATE = "Replicate" "Atoma",
SAMBA_NOVA_2 = "SambaNova 2" "Avian",
SF_COMPUTE = "SF Compute" "Azure",
TOGETHER_2 = "Together 2" "BaseTen",
ONE_DOT_AI = "01.AI" "Cerebras",
AI21 = "AI21" "Chutes",
AION_LABS = "AionLabs" "Cloudflare",
ALIBABA = "Alibaba" "Cohere",
AMAZON_BEDROCK = "Amazon Bedrock" "CrofAI",
ANTHROPIC = "Anthropic" "Crusoe",
ATLAS_CLOUD = "AtlasCloud" "DeepInfra",
ATOMA = "Atoma" "DeepSeek",
AVIAN = "Avian" "Enfer",
AZURE = "Azure" "Featherless",
BASE_TEN = "BaseTen" "Fireworks",
CEREBRAS = "Cerebras" "Friendli",
CHUTES = "Chutes" "GMICloud",
CLOUDFLARE = "Cloudflare" "Google",
COHERE = "Cohere" "Google AI Studio",
CROF_AI = "CrofAI" "Groq",
CRUSOE = "Crusoe" "Hyperbolic",
DEEP_INFRA = "DeepInfra" "Inception",
DEEP_SEEK = "DeepSeek" "InferenceNet",
ENFER = "Enfer" "Infermatic",
FEATHERLESS = "Featherless" "Inflection",
FIREWORKS = "Fireworks" "InoCloud",
FRIENDLI = "Friendli" "Kluster",
GMI_CLOUD = "GMICloud" "Lambda",
GOOGLE = "Google" "Liquid",
GOOGLE_AI_STUDIO = "Google AI Studio" "Mancer 2",
GROQ = "Groq" "Meta",
HYPERBOLIC = "Hyperbolic" "Minimax",
INCEPTION = "Inception" "Mistral",
INFERENCE_NET = "InferenceNet" "Moonshot AI",
INFERMATIC = "Infermatic" "Morph",
INFLECTION = "Inflection" "NCompass",
INO_CLOUD = "InoCloud" "Nebius",
KLUSTER = "Kluster" "NextBit",
LAMBDA = "Lambda" "Nineteen",
LIQUID = "Liquid" "Novita",
MANCER_2 = "Mancer 2" "OpenAI",
META = "Meta" "OpenInference",
MINIMAX = "Minimax" "Parasail",
MISTRAL = "Mistral" "Perplexity",
MOONSHOT_AI = "Moonshot AI" "Phala",
MORPH = "Morph" "SambaNova",
N_COMPASS = "NCompass" "Stealth",
NEBIUS = "Nebius" "Switchpoint",
NEXT_BIT = "NextBit" "Targon",
NINETEEN = "Nineteen" "Together",
NOVITA = "Novita" "Ubicloud",
OPEN_AI = "OpenAI" "Venice",
OPEN_INFERENCE = "OpenInference" "WandB",
PARASAIL = "Parasail" "xAI",
PERPLEXITY = "Perplexity" "Z.AI",
PHALA = "Phala" ]
SAMBA_NOVA = "SambaNova"
STEALTH = "Stealth"
SWITCHPOINT = "Switchpoint"
TARGON = "Targon"
TOGETHER = "Together"
UBICLOUD = "Ubicloud"
VENICE = "Venice"
WAND_B = "WandB"
X_AI = "xAI"
Z_AI = "Z.AI"
ChatCompletionCreateParamsOrderUnionTypedDict = TypeAliasType( ChatCompletionCreateParamsOrderUnionTypedDict = TypeAliasType(
"ChatCompletionCreateParamsOrderUnionTypedDict", "ChatCompletionCreateParamsOrderUnionTypedDict",
@@ -404,86 +383,86 @@ ChatCompletionCreateParamsOrderUnion = TypeAliasType(
) )
class ChatCompletionCreateParamsOnlyEnum(str, Enum): ChatCompletionCreateParamsOnlyEnum = Literal[
ANY_SCALE = "AnyScale" "AnyScale",
CENT_ML = "Cent-ML" "Cent-ML",
HUGGING_FACE = "HuggingFace" "HuggingFace",
HYPERBOLIC_2 = "Hyperbolic 2" "Hyperbolic 2",
LEPTON = "Lepton" "Lepton",
LYNN_2 = "Lynn 2" "Lynn 2",
LYNN = "Lynn" "Lynn",
MANCER = "Mancer" "Mancer",
MODAL = "Modal" "Modal",
OCTO_AI = "OctoAI" "OctoAI",
RECURSAL = "Recursal" "Recursal",
REFLECTION = "Reflection" "Reflection",
REPLICATE = "Replicate" "Replicate",
SAMBA_NOVA_2 = "SambaNova 2" "SambaNova 2",
SF_COMPUTE = "SF Compute" "SF Compute",
TOGETHER_2 = "Together 2" "Together 2",
ONE_DOT_AI = "01.AI" "01.AI",
AI21 = "AI21" "AI21",
AION_LABS = "AionLabs" "AionLabs",
ALIBABA = "Alibaba" "Alibaba",
AMAZON_BEDROCK = "Amazon Bedrock" "Amazon Bedrock",
ANTHROPIC = "Anthropic" "Anthropic",
ATLAS_CLOUD = "AtlasCloud" "AtlasCloud",
ATOMA = "Atoma" "Atoma",
AVIAN = "Avian" "Avian",
AZURE = "Azure" "Azure",
BASE_TEN = "BaseTen" "BaseTen",
CEREBRAS = "Cerebras" "Cerebras",
CHUTES = "Chutes" "Chutes",
CLOUDFLARE = "Cloudflare" "Cloudflare",
COHERE = "Cohere" "Cohere",
CROF_AI = "CrofAI" "CrofAI",
CRUSOE = "Crusoe" "Crusoe",
DEEP_INFRA = "DeepInfra" "DeepInfra",
DEEP_SEEK = "DeepSeek" "DeepSeek",
ENFER = "Enfer" "Enfer",
FEATHERLESS = "Featherless" "Featherless",
FIREWORKS = "Fireworks" "Fireworks",
FRIENDLI = "Friendli" "Friendli",
GMI_CLOUD = "GMICloud" "GMICloud",
GOOGLE = "Google" "Google",
GOOGLE_AI_STUDIO = "Google AI Studio" "Google AI Studio",
GROQ = "Groq" "Groq",
HYPERBOLIC = "Hyperbolic" "Hyperbolic",
INCEPTION = "Inception" "Inception",
INFERENCE_NET = "InferenceNet" "InferenceNet",
INFERMATIC = "Infermatic" "Infermatic",
INFLECTION = "Inflection" "Inflection",
INO_CLOUD = "InoCloud" "InoCloud",
KLUSTER = "Kluster" "Kluster",
LAMBDA = "Lambda" "Lambda",
LIQUID = "Liquid" "Liquid",
MANCER_2 = "Mancer 2" "Mancer 2",
META = "Meta" "Meta",
MINIMAX = "Minimax" "Minimax",
MISTRAL = "Mistral" "Mistral",
MOONSHOT_AI = "Moonshot AI" "Moonshot AI",
MORPH = "Morph" "Morph",
N_COMPASS = "NCompass" "NCompass",
NEBIUS = "Nebius" "Nebius",
NEXT_BIT = "NextBit" "NextBit",
NINETEEN = "Nineteen" "Nineteen",
NOVITA = "Novita" "Novita",
OPEN_AI = "OpenAI" "OpenAI",
OPEN_INFERENCE = "OpenInference" "OpenInference",
PARASAIL = "Parasail" "Parasail",
PERPLEXITY = "Perplexity" "Perplexity",
PHALA = "Phala" "Phala",
SAMBA_NOVA = "SambaNova" "SambaNova",
STEALTH = "Stealth" "Stealth",
SWITCHPOINT = "Switchpoint" "Switchpoint",
TARGON = "Targon" "Targon",
TOGETHER = "Together" "Together",
UBICLOUD = "Ubicloud" "Ubicloud",
VENICE = "Venice" "Venice",
WAND_B = "WandB" "WandB",
X_AI = "xAI" "xAI",
Z_AI = "Z.AI" "Z.AI",
]
ChatCompletionCreateParamsOnlyUnionTypedDict = TypeAliasType( ChatCompletionCreateParamsOnlyUnionTypedDict = TypeAliasType(
"ChatCompletionCreateParamsOnlyUnionTypedDict", "ChatCompletionCreateParamsOnlyUnionTypedDict",
@@ -497,86 +476,86 @@ ChatCompletionCreateParamsOnlyUnion = TypeAliasType(
) )
class ChatCompletionCreateParamsIgnoreEnum(str, Enum): ChatCompletionCreateParamsIgnoreEnum = Literal[
ANY_SCALE = "AnyScale" "AnyScale",
CENT_ML = "Cent-ML" "Cent-ML",
HUGGING_FACE = "HuggingFace" "HuggingFace",
HYPERBOLIC_2 = "Hyperbolic 2" "Hyperbolic 2",
LEPTON = "Lepton" "Lepton",
LYNN_2 = "Lynn 2" "Lynn 2",
LYNN = "Lynn" "Lynn",
MANCER = "Mancer" "Mancer",
MODAL = "Modal" "Modal",
OCTO_AI = "OctoAI" "OctoAI",
RECURSAL = "Recursal" "Recursal",
REFLECTION = "Reflection" "Reflection",
REPLICATE = "Replicate" "Replicate",
SAMBA_NOVA_2 = "SambaNova 2" "SambaNova 2",
SF_COMPUTE = "SF Compute" "SF Compute",
TOGETHER_2 = "Together 2" "Together 2",
ONE_DOT_AI = "01.AI" "01.AI",
AI21 = "AI21" "AI21",
AION_LABS = "AionLabs" "AionLabs",
ALIBABA = "Alibaba" "Alibaba",
AMAZON_BEDROCK = "Amazon Bedrock" "Amazon Bedrock",
ANTHROPIC = "Anthropic" "Anthropic",
ATLAS_CLOUD = "AtlasCloud" "AtlasCloud",
ATOMA = "Atoma" "Atoma",
AVIAN = "Avian" "Avian",
AZURE = "Azure" "Azure",
BASE_TEN = "BaseTen" "BaseTen",
CEREBRAS = "Cerebras" "Cerebras",
CHUTES = "Chutes" "Chutes",
CLOUDFLARE = "Cloudflare" "Cloudflare",
COHERE = "Cohere" "Cohere",
CROF_AI = "CrofAI" "CrofAI",
CRUSOE = "Crusoe" "Crusoe",
DEEP_INFRA = "DeepInfra" "DeepInfra",
DEEP_SEEK = "DeepSeek" "DeepSeek",
ENFER = "Enfer" "Enfer",
FEATHERLESS = "Featherless" "Featherless",
FIREWORKS = "Fireworks" "Fireworks",
FRIENDLI = "Friendli" "Friendli",
GMI_CLOUD = "GMICloud" "GMICloud",
GOOGLE = "Google" "Google",
GOOGLE_AI_STUDIO = "Google AI Studio" "Google AI Studio",
GROQ = "Groq" "Groq",
HYPERBOLIC = "Hyperbolic" "Hyperbolic",
INCEPTION = "Inception" "Inception",
INFERENCE_NET = "InferenceNet" "InferenceNet",
INFERMATIC = "Infermatic" "Infermatic",
INFLECTION = "Inflection" "Inflection",
INO_CLOUD = "InoCloud" "InoCloud",
KLUSTER = "Kluster" "Kluster",
LAMBDA = "Lambda" "Lambda",
LIQUID = "Liquid" "Liquid",
MANCER_2 = "Mancer 2" "Mancer 2",
META = "Meta" "Meta",
MINIMAX = "Minimax" "Minimax",
MISTRAL = "Mistral" "Mistral",
MOONSHOT_AI = "Moonshot AI" "Moonshot AI",
MORPH = "Morph" "Morph",
N_COMPASS = "NCompass" "NCompass",
NEBIUS = "Nebius" "Nebius",
NEXT_BIT = "NextBit" "NextBit",
NINETEEN = "Nineteen" "Nineteen",
NOVITA = "Novita" "Novita",
OPEN_AI = "OpenAI" "OpenAI",
OPEN_INFERENCE = "OpenInference" "OpenInference",
PARASAIL = "Parasail" "Parasail",
PERPLEXITY = "Perplexity" "Perplexity",
PHALA = "Phala" "Phala",
SAMBA_NOVA = "SambaNova" "SambaNova",
STEALTH = "Stealth" "Stealth",
SWITCHPOINT = "Switchpoint" "Switchpoint",
TARGON = "Targon" "Targon",
TOGETHER = "Together" "Together",
UBICLOUD = "Ubicloud" "Ubicloud",
VENICE = "Venice" "Venice",
WAND_B = "WandB" "WandB",
X_AI = "xAI" "xAI",
Z_AI = "Z.AI" "Z.AI",
]
ChatCompletionCreateParamsIgnoreUnionTypedDict = TypeAliasType( ChatCompletionCreateParamsIgnoreUnionTypedDict = TypeAliasType(
"ChatCompletionCreateParamsIgnoreUnionTypedDict", "ChatCompletionCreateParamsIgnoreUnionTypedDict",
@@ -590,25 +569,12 @@ ChatCompletionCreateParamsIgnoreUnion = TypeAliasType(
) )
class ChatCompletionCreateParamsQuantization(str, Enum): ChatCompletionCreateParamsQuantization = Literal[
INT4 = "int4" "int4", "int8", "fp4", "fp6", "fp8", "fp16", "bf16", "fp32", "unknown"
INT8 = "int8" ]
FP4 = "fp4"
FP6 = "fp6"
FP8 = "fp8"
FP16 = "fp16"
BF16 = "bf16"
FP32 = "fp32"
UNKNOWN = "unknown"
class ChatCompletionCreateParamsSort(str, Enum):
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
PRICE = "price"
THROUGHPUT = "throughput"
LATENCY = "latency"
ChatCompletionCreateParamsSort = Literal["price", "throughput", "latency"]
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
ChatCompletionCreateParamsPromptTypedDict = TypeAliasType( ChatCompletionCreateParamsPromptTypedDict = TypeAliasType(
"ChatCompletionCreateParamsPromptTypedDict", Union[float, str, Any] "ChatCompletionCreateParamsPromptTypedDict", Union[float, str, Any]
@@ -805,14 +771,9 @@ class ChatCompletionCreateParamsProvider(BaseModel):
return m return m
class ChatCompletionCreateParamsIDFileParser(str, Enum): ChatCompletionCreateParamsIDFileParser = Literal["file-parser"]
FILE_PARSER = "file-parser"
ChatCompletionCreateParamsPdfEngine = Literal["mistral-ocr", "pdf-text", "native"]
class ChatCompletionCreateParamsPdfEngine(str, Enum):
MISTRAL_OCR = "mistral-ocr"
PDF_TEXT = "pdf-text"
NATIVE = "native"
class ChatCompletionCreateParamsPdfTypedDict(TypedDict): class ChatCompletionCreateParamsPdfTypedDict(TypedDict):
@@ -837,8 +798,7 @@ class ChatCompletionCreateParamsPluginFileParser(BaseModel):
pdf: Optional[ChatCompletionCreateParamsPdf] = None pdf: Optional[ChatCompletionCreateParamsPdf] = None
class ChatCompletionCreateParamsIDChainOfThought(str, Enum): ChatCompletionCreateParamsIDChainOfThought = Literal["chain-of-thought"]
CHAIN_OF_THOUGHT = "chain-of-thought"
class ChatCompletionCreateParamsPluginChainOfThoughtTypedDict(TypedDict): class ChatCompletionCreateParamsPluginChainOfThoughtTypedDict(TypedDict):
@@ -849,13 +809,9 @@ class ChatCompletionCreateParamsPluginChainOfThought(BaseModel):
id: ChatCompletionCreateParamsIDChainOfThought id: ChatCompletionCreateParamsIDChainOfThought
class ChatCompletionCreateParamsIDWeb(str, Enum): ChatCompletionCreateParamsIDWeb = Literal["web"]
WEB = "web"
ChatCompletionCreateParamsEngine = Literal["native", "exa"]
class ChatCompletionCreateParamsEngine(str, Enum):
NATIVE = "native"
EXA = "exa"
class ChatCompletionCreateParamsPluginWebTypedDict(TypedDict): class ChatCompletionCreateParamsPluginWebTypedDict(TypedDict):
@@ -875,8 +831,7 @@ class ChatCompletionCreateParamsPluginWeb(BaseModel):
engine: Optional[ChatCompletionCreateParamsEngine] = None engine: Optional[ChatCompletionCreateParamsEngine] = None
class ChatCompletionCreateParamsIDModeration(str, Enum): ChatCompletionCreateParamsIDModeration = Literal["moderation"]
MODERATION = "moderation"
class ChatCompletionCreateParamsPluginModerationTypedDict(TypedDict): class ChatCompletionCreateParamsPluginModerationTypedDict(TypedDict):
@@ -955,7 +910,7 @@ class ChatCompletionCreateParamsTypedDict(TypedDict):
r"""Nucleus sampling parameter (0-1)""" r"""Nucleus sampling parameter (0-1)"""
user: NotRequired[str] user: NotRequired[str]
r"""Unique user identifier""" r"""Unique user identifier"""
models_llm: NotRequired[Nullable[List[str]]] fallback_models: NotRequired[Nullable[List[str]]]
r"""Order of models to fallback to for this request""" r"""Order of models to fallback to for this request"""
reasoning_effort: NotRequired[Nullable[ChatCompletionCreateParamsReasoningEffort]] reasoning_effort: NotRequired[Nullable[ChatCompletionCreateParamsReasoningEffort]]
r"""Reasoning effort""" r"""Reasoning effort"""
@@ -1030,7 +985,7 @@ class ChatCompletionCreateParams(BaseModel):
user: Optional[str] = None user: Optional[str] = None
r"""Unique user identifier""" r"""Unique user identifier"""
models_llm: Annotated[ fallback_models: Annotated[
OptionalNullable[List[str]], pydantic.Field(alias="models") OptionalNullable[List[str]], pydantic.Field(alias="models")
] = UNSET ] = UNSET
r"""Order of models to fallback to for this request""" r"""Order of models to fallback to for this request"""
@@ -1069,7 +1024,7 @@ class ChatCompletionCreateParams(BaseModel):
"tools", "tools",
"top_p", "top_p",
"user", "user",
"models_llm", "fallback_models",
"reasoning_effort", "reasoning_effort",
"provider", "provider",
"plugins", "plugins",
@@ -1089,7 +1044,7 @@ class ChatCompletionCreateParams(BaseModel):
"stream_options", "stream_options",
"temperature", "temperature",
"top_p", "top_p",
"models_llm", "fallback_models",
"reasoning_effort", "reasoning_effort",
"provider", "provider",
] ]
+16 -9
View File
@@ -1,34 +1,41 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from pydantic import model_serializer from pydantic import model_serializer
from typing_extensions import TypedDict from typing import Optional
from typing_extensions import NotRequired, TypedDict
class ErrorTypedDict(TypedDict): class ErrorTypedDict(TypedDict):
r"""Error object structure""" r"""Error object structure"""
code: Nullable[str] code: Nullable[float]
message: str message: str
param: Nullable[str] param: NotRequired[Nullable[str]]
type: str type: NotRequired[str]
class Error(BaseModel): class Error(BaseModel):
r"""Error object structure""" r"""Error object structure"""
code: Nullable[str] code: Nullable[float]
message: str message: str
param: Nullable[str] param: OptionalNullable[str] = UNSET
type: str type: Optional[str] = None
@model_serializer(mode="wrap") @model_serializer(mode="wrap")
def serialize_model(self, handler): def serialize_model(self, handler):
optional_fields = [] optional_fields = ["param", "type"]
nullable_fields = ["code", "param"] nullable_fields = ["code", "param"]
null_default_fields = [] null_default_fields = []
@@ -7,7 +7,6 @@ from .chatcompletionmessagetoolcall import (
ChatCompletionMessageToolCallTypedDict, ChatCompletionMessageToolCallTypedDict,
) )
from .reasoningdetail import ReasoningDetail, ReasoningDetailTypedDict from .reasoningdetail import ReasoningDetail, ReasoningDetailTypedDict
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -16,12 +15,11 @@ from openrouter.types import (
UNSET_SENTINEL, UNSET_SENTINEL,
) )
from pydantic import model_serializer from pydantic import model_serializer
from typing import List, Optional from typing import List, Literal, Optional
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class ChatCompletionMessageRole(str, Enum): ChatCompletionMessageRole = Literal["assistant"]
ASSISTANT = "assistant"
class ChatCompletionMessageTypedDict(TypedDict): class ChatCompletionMessageTypedDict(TypedDict):
@@ -1,13 +1,12 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import Literal
from typing_extensions import TypedDict from typing_extensions import TypedDict
class ChatCompletionMessageToolCallType(str, Enum): ChatCompletionMessageToolCallType = Literal["function"]
FUNCTION = "function"
class ChatCompletionMessageToolCallFunctionTypedDict(TypedDict): class ChatCompletionMessageToolCallFunctionTypedDict(TypedDict):
@@ -1,13 +1,12 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import Literal
from typing_extensions import TypedDict from typing_extensions import TypedDict
class ChatCompletionNamedToolChoiceType(str, Enum): ChatCompletionNamedToolChoiceType = Literal["function"]
FUNCTION = "function"
class ChatCompletionNamedToolChoiceFunctionTypedDict(TypedDict): class ChatCompletionNamedToolChoiceFunctionTypedDict(TypedDict):
@@ -5,15 +5,12 @@ from .chatcompletioncontentparttext import (
ChatCompletionContentPartText, ChatCompletionContentPartText,
ChatCompletionContentPartTextTypedDict, ChatCompletionContentPartTextTypedDict,
) )
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import List, Optional, Union from typing import List, Literal, Optional, Union
from typing_extensions import NotRequired, TypeAliasType, TypedDict from typing_extensions import NotRequired, TypeAliasType, TypedDict
class ChatCompletionSystemMessageParamRole(str, Enum): ChatCompletionSystemMessageParamRole = Literal["system"]
SYSTEM = "system"
ChatCompletionSystemMessageParamContentTypedDict = TypeAliasType( ChatCompletionSystemMessageParamContentTypedDict = TypeAliasType(
"ChatCompletionSystemMessageParamContentTypedDict", "ChatCompletionSystemMessageParamContentTypedDict",
+2 -4
View File
@@ -1,7 +1,6 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -10,12 +9,11 @@ from openrouter.types import (
UNSET_SENTINEL, UNSET_SENTINEL,
) )
from pydantic import model_serializer from pydantic import model_serializer
from typing import Optional from typing import Literal, Optional
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class ChatCompletionToolType(str, Enum): ChatCompletionToolType = Literal["function"]
FUNCTION = "function"
class ParametersTypedDict(TypedDict): class ParametersTypedDict(TypedDict):
@@ -5,22 +5,15 @@ from .chatcompletionnamedtoolchoice import (
ChatCompletionNamedToolChoice, ChatCompletionNamedToolChoice,
ChatCompletionNamedToolChoiceTypedDict, ChatCompletionNamedToolChoiceTypedDict,
) )
from enum import Enum from typing import Literal, Union
from typing import Union
from typing_extensions import TypeAliasType from typing_extensions import TypeAliasType
class ChatCompletionToolChoiceOptionRequired(str, Enum): ChatCompletionToolChoiceOptionRequired = Literal["required"]
REQUIRED = "required"
ChatCompletionToolChoiceOptionAuto = Literal["auto"]
class ChatCompletionToolChoiceOptionAuto(str, Enum): ChatCompletionToolChoiceOptionNone = Literal["none"]
AUTO = "auto"
class ChatCompletionToolChoiceOptionNone(str, Enum):
NONE = "none"
ChatCompletionToolChoiceOptionTypedDict = TypeAliasType( ChatCompletionToolChoiceOptionTypedDict = TypeAliasType(
"ChatCompletionToolChoiceOptionTypedDict", "ChatCompletionToolChoiceOptionTypedDict",
@@ -5,15 +5,12 @@ from .chatcompletioncontentpart import (
ChatCompletionContentPart, ChatCompletionContentPart,
ChatCompletionContentPartTypedDict, ChatCompletionContentPartTypedDict,
) )
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import List, Union from typing import List, Literal, Union
from typing_extensions import TypeAliasType, TypedDict from typing_extensions import TypeAliasType, TypedDict
class ChatCompletionToolMessageParamRole(str, Enum): ChatCompletionToolMessageParamRole = Literal["tool"]
TOOL = "tool"
ChatCompletionToolMessageParamContentTypedDict = TypeAliasType( ChatCompletionToolMessageParamContentTypedDict = TypeAliasType(
"ChatCompletionToolMessageParamContentTypedDict", "ChatCompletionToolMessageParamContentTypedDict",
@@ -5,15 +5,12 @@ from .chatcompletioncontentpart import (
ChatCompletionContentPart, ChatCompletionContentPart,
ChatCompletionContentPartTypedDict, ChatCompletionContentPartTypedDict,
) )
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import List, Optional, Union from typing import List, Literal, Optional, Union
from typing_extensions import NotRequired, TypeAliasType, TypedDict from typing_extensions import NotRequired, TypeAliasType, TypedDict
class ChatCompletionUserMessageParamRole(str, Enum): ChatCompletionUserMessageParamRole = Literal["user"]
USER = "user"
ChatCompletionUserMessageParamContentTypedDict = TypeAliasType( ChatCompletionUserMessageParamContentTypedDict = TypeAliasType(
"ChatCompletionUserMessageParamContentTypedDict", "ChatCompletionUserMessageParamContentTypedDict",
@@ -14,7 +14,6 @@ from .responseformatjsonschemaschema import (
ResponseFormatJSONSchemaSchema, ResponseFormatJSONSchemaSchema,
ResponseFormatJSONSchemaSchemaTypedDict, ResponseFormatJSONSchemaSchemaTypedDict,
) )
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -24,17 +23,12 @@ from openrouter.types import (
) )
import pydantic import pydantic
from pydantic import model_serializer from pydantic import model_serializer
from typing import Any, Dict, List, Optional, Union from typing import Any, Dict, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
class ChatStreamCompletionCreateParamsEffort(str, Enum): ChatStreamCompletionCreateParamsEffort = Literal["high", "medium", "low", "minimal"]
r"""OpenAI-style reasoning effort setting""" r"""OpenAI-style reasoning effort setting"""
HIGH = "high"
MEDIUM = "medium"
LOW = "low"
MINIMAL = "minimal"
class ChatStreamCompletionCreateParamsReasoningTypedDict(TypedDict): class ChatStreamCompletionCreateParamsReasoningTypedDict(TypedDict):
@@ -94,8 +88,7 @@ class ChatStreamCompletionCreateParamsReasoning(BaseModel):
return m return m
class ChatStreamCompletionCreateParamsTypePython(str, Enum): ChatStreamCompletionCreateParamsTypePython = Literal["python"]
PYTHON = "python"
class ChatStreamCompletionCreateParamsResponseFormatPythonTypedDict(TypedDict): class ChatStreamCompletionCreateParamsResponseFormatPythonTypedDict(TypedDict):
@@ -110,8 +103,7 @@ class ChatStreamCompletionCreateParamsResponseFormatPython(BaseModel):
type: ChatStreamCompletionCreateParamsTypePython type: ChatStreamCompletionCreateParamsTypePython
class ChatStreamCompletionCreateParamsTypeGrammar(str, Enum): ChatStreamCompletionCreateParamsTypeGrammar = Literal["grammar"]
GRAMMAR = "grammar"
class ChatStreamCompletionCreateParamsResponseFormatGrammarTypedDict(TypedDict): class ChatStreamCompletionCreateParamsResponseFormatGrammarTypedDict(TypedDict):
@@ -131,8 +123,7 @@ class ChatStreamCompletionCreateParamsResponseFormatGrammar(BaseModel):
r"""Custom grammar for text generation""" r"""Custom grammar for text generation"""
class ChatStreamCompletionCreateParamsTypeJSONSchema(str, Enum): ChatStreamCompletionCreateParamsTypeJSONSchema = Literal["json_schema"]
JSON_SCHEMA = "json_schema"
class ChatStreamCompletionCreateParamsJSONSchemaTypedDict(TypedDict): class ChatStreamCompletionCreateParamsJSONSchemaTypedDict(TypedDict):
@@ -207,8 +198,7 @@ class ChatStreamCompletionCreateParamsResponseFormatJSONSchema(BaseModel):
json_schema: ChatStreamCompletionCreateParamsJSONSchema json_schema: ChatStreamCompletionCreateParamsJSONSchema
class ChatStreamCompletionCreateParamsTypeJSONObject(str, Enum): ChatStreamCompletionCreateParamsTypeJSONObject = Literal["json_object"]
JSON_OBJECT = "json_object"
class ChatStreamCompletionCreateParamsResponseFormatJSONObjectTypedDict(TypedDict): class ChatStreamCompletionCreateParamsResponseFormatJSONObjectTypedDict(TypedDict):
@@ -223,8 +213,7 @@ class ChatStreamCompletionCreateParamsResponseFormatJSONObject(BaseModel):
type: ChatStreamCompletionCreateParamsTypeJSONObject type: ChatStreamCompletionCreateParamsTypeJSONObject
class ChatStreamCompletionCreateParamsTypeText(str, Enum): ChatStreamCompletionCreateParamsTypeText = Literal["text"]
TEXT = "text"
class ChatStreamCompletionCreateParamsResponseFormatTextTypedDict(TypedDict): class ChatStreamCompletionCreateParamsResponseFormatTextTypedDict(TypedDict):
@@ -291,106 +280,98 @@ class ChatStreamCompletionCreateParamsStreamOptions(BaseModel):
r"""Include usage information in streaming response""" r"""Include usage information in streaming response"""
class ChatStreamCompletionCreateParamsReasoningEffort(str, Enum): ChatStreamCompletionCreateParamsReasoningEffort = Literal[
r"""Reasoning effort""" "high", "medium", "low", "minimal"
]
r"""Reasoning effort"""
HIGH = "high" ChatStreamCompletionCreateParamsDataCollection = Literal["deny", "allow"]
MEDIUM = "medium" r"""Data collection setting. If no available model provider meets the requirement, your request will return an error.
LOW = "low" - allow: (default) allow providers which store user data non-transiently and may train on it
MINIMAL = "minimal" - deny: use only providers which do not collect user data.
"""
class ChatStreamCompletionCreateParamsDataCollection(str, Enum): ChatStreamCompletionCreateParamsOrderEnum = Literal[
r"""Data collection setting. If no available model provider meets the requirement, your request will return an error. "AnyScale",
- allow: (default) allow providers which store user data non-transiently and may train on it "Cent-ML",
- deny: use only providers which do not collect user data. "HuggingFace",
"Hyperbolic 2",
""" "Lepton",
"Lynn 2",
DENY = "deny" "Lynn",
ALLOW = "allow" "Mancer",
"Modal",
"OctoAI",
class ChatStreamCompletionCreateParamsOrderEnum(str, Enum): "Recursal",
ANY_SCALE = "AnyScale" "Reflection",
CENT_ML = "Cent-ML" "Replicate",
HUGGING_FACE = "HuggingFace" "SambaNova 2",
HYPERBOLIC_2 = "Hyperbolic 2" "SF Compute",
LEPTON = "Lepton" "Together 2",
LYNN_2 = "Lynn 2" "01.AI",
LYNN = "Lynn" "AI21",
MANCER = "Mancer" "AionLabs",
MODAL = "Modal" "Alibaba",
OCTO_AI = "OctoAI" "Amazon Bedrock",
RECURSAL = "Recursal" "Anthropic",
REFLECTION = "Reflection" "AtlasCloud",
REPLICATE = "Replicate" "Atoma",
SAMBA_NOVA_2 = "SambaNova 2" "Avian",
SF_COMPUTE = "SF Compute" "Azure",
TOGETHER_2 = "Together 2" "BaseTen",
ONE_DOT_AI = "01.AI" "Cerebras",
AI21 = "AI21" "Chutes",
AION_LABS = "AionLabs" "Cloudflare",
ALIBABA = "Alibaba" "Cohere",
AMAZON_BEDROCK = "Amazon Bedrock" "CrofAI",
ANTHROPIC = "Anthropic" "Crusoe",
ATLAS_CLOUD = "AtlasCloud" "DeepInfra",
ATOMA = "Atoma" "DeepSeek",
AVIAN = "Avian" "Enfer",
AZURE = "Azure" "Featherless",
BASE_TEN = "BaseTen" "Fireworks",
CEREBRAS = "Cerebras" "Friendli",
CHUTES = "Chutes" "GMICloud",
CLOUDFLARE = "Cloudflare" "Google",
COHERE = "Cohere" "Google AI Studio",
CROF_AI = "CrofAI" "Groq",
CRUSOE = "Crusoe" "Hyperbolic",
DEEP_INFRA = "DeepInfra" "Inception",
DEEP_SEEK = "DeepSeek" "InferenceNet",
ENFER = "Enfer" "Infermatic",
FEATHERLESS = "Featherless" "Inflection",
FIREWORKS = "Fireworks" "InoCloud",
FRIENDLI = "Friendli" "Kluster",
GMI_CLOUD = "GMICloud" "Lambda",
GOOGLE = "Google" "Liquid",
GOOGLE_AI_STUDIO = "Google AI Studio" "Mancer 2",
GROQ = "Groq" "Meta",
HYPERBOLIC = "Hyperbolic" "Minimax",
INCEPTION = "Inception" "Mistral",
INFERENCE_NET = "InferenceNet" "Moonshot AI",
INFERMATIC = "Infermatic" "Morph",
INFLECTION = "Inflection" "NCompass",
INO_CLOUD = "InoCloud" "Nebius",
KLUSTER = "Kluster" "NextBit",
LAMBDA = "Lambda" "Nineteen",
LIQUID = "Liquid" "Novita",
MANCER_2 = "Mancer 2" "OpenAI",
META = "Meta" "OpenInference",
MINIMAX = "Minimax" "Parasail",
MISTRAL = "Mistral" "Perplexity",
MOONSHOT_AI = "Moonshot AI" "Phala",
MORPH = "Morph" "SambaNova",
N_COMPASS = "NCompass" "Stealth",
NEBIUS = "Nebius" "Switchpoint",
NEXT_BIT = "NextBit" "Targon",
NINETEEN = "Nineteen" "Together",
NOVITA = "Novita" "Ubicloud",
OPEN_AI = "OpenAI" "Venice",
OPEN_INFERENCE = "OpenInference" "WandB",
PARASAIL = "Parasail" "xAI",
PERPLEXITY = "Perplexity" "Z.AI",
PHALA = "Phala" ]
SAMBA_NOVA = "SambaNova"
STEALTH = "Stealth"
SWITCHPOINT = "Switchpoint"
TARGON = "Targon"
TOGETHER = "Together"
UBICLOUD = "Ubicloud"
VENICE = "Venice"
WAND_B = "WandB"
X_AI = "xAI"
Z_AI = "Z.AI"
ChatStreamCompletionCreateParamsOrderUnionTypedDict = TypeAliasType( ChatStreamCompletionCreateParamsOrderUnionTypedDict = TypeAliasType(
"ChatStreamCompletionCreateParamsOrderUnionTypedDict", "ChatStreamCompletionCreateParamsOrderUnionTypedDict",
@@ -404,86 +385,86 @@ ChatStreamCompletionCreateParamsOrderUnion = TypeAliasType(
) )
class ChatStreamCompletionCreateParamsOnlyEnum(str, Enum): ChatStreamCompletionCreateParamsOnlyEnum = Literal[
ANY_SCALE = "AnyScale" "AnyScale",
CENT_ML = "Cent-ML" "Cent-ML",
HUGGING_FACE = "HuggingFace" "HuggingFace",
HYPERBOLIC_2 = "Hyperbolic 2" "Hyperbolic 2",
LEPTON = "Lepton" "Lepton",
LYNN_2 = "Lynn 2" "Lynn 2",
LYNN = "Lynn" "Lynn",
MANCER = "Mancer" "Mancer",
MODAL = "Modal" "Modal",
OCTO_AI = "OctoAI" "OctoAI",
RECURSAL = "Recursal" "Recursal",
REFLECTION = "Reflection" "Reflection",
REPLICATE = "Replicate" "Replicate",
SAMBA_NOVA_2 = "SambaNova 2" "SambaNova 2",
SF_COMPUTE = "SF Compute" "SF Compute",
TOGETHER_2 = "Together 2" "Together 2",
ONE_DOT_AI = "01.AI" "01.AI",
AI21 = "AI21" "AI21",
AION_LABS = "AionLabs" "AionLabs",
ALIBABA = "Alibaba" "Alibaba",
AMAZON_BEDROCK = "Amazon Bedrock" "Amazon Bedrock",
ANTHROPIC = "Anthropic" "Anthropic",
ATLAS_CLOUD = "AtlasCloud" "AtlasCloud",
ATOMA = "Atoma" "Atoma",
AVIAN = "Avian" "Avian",
AZURE = "Azure" "Azure",
BASE_TEN = "BaseTen" "BaseTen",
CEREBRAS = "Cerebras" "Cerebras",
CHUTES = "Chutes" "Chutes",
CLOUDFLARE = "Cloudflare" "Cloudflare",
COHERE = "Cohere" "Cohere",
CROF_AI = "CrofAI" "CrofAI",
CRUSOE = "Crusoe" "Crusoe",
DEEP_INFRA = "DeepInfra" "DeepInfra",
DEEP_SEEK = "DeepSeek" "DeepSeek",
ENFER = "Enfer" "Enfer",
FEATHERLESS = "Featherless" "Featherless",
FIREWORKS = "Fireworks" "Fireworks",
FRIENDLI = "Friendli" "Friendli",
GMI_CLOUD = "GMICloud" "GMICloud",
GOOGLE = "Google" "Google",
GOOGLE_AI_STUDIO = "Google AI Studio" "Google AI Studio",
GROQ = "Groq" "Groq",
HYPERBOLIC = "Hyperbolic" "Hyperbolic",
INCEPTION = "Inception" "Inception",
INFERENCE_NET = "InferenceNet" "InferenceNet",
INFERMATIC = "Infermatic" "Infermatic",
INFLECTION = "Inflection" "Inflection",
INO_CLOUD = "InoCloud" "InoCloud",
KLUSTER = "Kluster" "Kluster",
LAMBDA = "Lambda" "Lambda",
LIQUID = "Liquid" "Liquid",
MANCER_2 = "Mancer 2" "Mancer 2",
META = "Meta" "Meta",
MINIMAX = "Minimax" "Minimax",
MISTRAL = "Mistral" "Mistral",
MOONSHOT_AI = "Moonshot AI" "Moonshot AI",
MORPH = "Morph" "Morph",
N_COMPASS = "NCompass" "NCompass",
NEBIUS = "Nebius" "Nebius",
NEXT_BIT = "NextBit" "NextBit",
NINETEEN = "Nineteen" "Nineteen",
NOVITA = "Novita" "Novita",
OPEN_AI = "OpenAI" "OpenAI",
OPEN_INFERENCE = "OpenInference" "OpenInference",
PARASAIL = "Parasail" "Parasail",
PERPLEXITY = "Perplexity" "Perplexity",
PHALA = "Phala" "Phala",
SAMBA_NOVA = "SambaNova" "SambaNova",
STEALTH = "Stealth" "Stealth",
SWITCHPOINT = "Switchpoint" "Switchpoint",
TARGON = "Targon" "Targon",
TOGETHER = "Together" "Together",
UBICLOUD = "Ubicloud" "Ubicloud",
VENICE = "Venice" "Venice",
WAND_B = "WandB" "WandB",
X_AI = "xAI" "xAI",
Z_AI = "Z.AI" "Z.AI",
]
ChatStreamCompletionCreateParamsOnlyUnionTypedDict = TypeAliasType( ChatStreamCompletionCreateParamsOnlyUnionTypedDict = TypeAliasType(
"ChatStreamCompletionCreateParamsOnlyUnionTypedDict", "ChatStreamCompletionCreateParamsOnlyUnionTypedDict",
@@ -497,86 +478,86 @@ ChatStreamCompletionCreateParamsOnlyUnion = TypeAliasType(
) )
class ChatStreamCompletionCreateParamsIgnoreEnum(str, Enum): ChatStreamCompletionCreateParamsIgnoreEnum = Literal[
ANY_SCALE = "AnyScale" "AnyScale",
CENT_ML = "Cent-ML" "Cent-ML",
HUGGING_FACE = "HuggingFace" "HuggingFace",
HYPERBOLIC_2 = "Hyperbolic 2" "Hyperbolic 2",
LEPTON = "Lepton" "Lepton",
LYNN_2 = "Lynn 2" "Lynn 2",
LYNN = "Lynn" "Lynn",
MANCER = "Mancer" "Mancer",
MODAL = "Modal" "Modal",
OCTO_AI = "OctoAI" "OctoAI",
RECURSAL = "Recursal" "Recursal",
REFLECTION = "Reflection" "Reflection",
REPLICATE = "Replicate" "Replicate",
SAMBA_NOVA_2 = "SambaNova 2" "SambaNova 2",
SF_COMPUTE = "SF Compute" "SF Compute",
TOGETHER_2 = "Together 2" "Together 2",
ONE_DOT_AI = "01.AI" "01.AI",
AI21 = "AI21" "AI21",
AION_LABS = "AionLabs" "AionLabs",
ALIBABA = "Alibaba" "Alibaba",
AMAZON_BEDROCK = "Amazon Bedrock" "Amazon Bedrock",
ANTHROPIC = "Anthropic" "Anthropic",
ATLAS_CLOUD = "AtlasCloud" "AtlasCloud",
ATOMA = "Atoma" "Atoma",
AVIAN = "Avian" "Avian",
AZURE = "Azure" "Azure",
BASE_TEN = "BaseTen" "BaseTen",
CEREBRAS = "Cerebras" "Cerebras",
CHUTES = "Chutes" "Chutes",
CLOUDFLARE = "Cloudflare" "Cloudflare",
COHERE = "Cohere" "Cohere",
CROF_AI = "CrofAI" "CrofAI",
CRUSOE = "Crusoe" "Crusoe",
DEEP_INFRA = "DeepInfra" "DeepInfra",
DEEP_SEEK = "DeepSeek" "DeepSeek",
ENFER = "Enfer" "Enfer",
FEATHERLESS = "Featherless" "Featherless",
FIREWORKS = "Fireworks" "Fireworks",
FRIENDLI = "Friendli" "Friendli",
GMI_CLOUD = "GMICloud" "GMICloud",
GOOGLE = "Google" "Google",
GOOGLE_AI_STUDIO = "Google AI Studio" "Google AI Studio",
GROQ = "Groq" "Groq",
HYPERBOLIC = "Hyperbolic" "Hyperbolic",
INCEPTION = "Inception" "Inception",
INFERENCE_NET = "InferenceNet" "InferenceNet",
INFERMATIC = "Infermatic" "Infermatic",
INFLECTION = "Inflection" "Inflection",
INO_CLOUD = "InoCloud" "InoCloud",
KLUSTER = "Kluster" "Kluster",
LAMBDA = "Lambda" "Lambda",
LIQUID = "Liquid" "Liquid",
MANCER_2 = "Mancer 2" "Mancer 2",
META = "Meta" "Meta",
MINIMAX = "Minimax" "Minimax",
MISTRAL = "Mistral" "Mistral",
MOONSHOT_AI = "Moonshot AI" "Moonshot AI",
MORPH = "Morph" "Morph",
N_COMPASS = "NCompass" "NCompass",
NEBIUS = "Nebius" "Nebius",
NEXT_BIT = "NextBit" "NextBit",
NINETEEN = "Nineteen" "Nineteen",
NOVITA = "Novita" "Novita",
OPEN_AI = "OpenAI" "OpenAI",
OPEN_INFERENCE = "OpenInference" "OpenInference",
PARASAIL = "Parasail" "Parasail",
PERPLEXITY = "Perplexity" "Perplexity",
PHALA = "Phala" "Phala",
SAMBA_NOVA = "SambaNova" "SambaNova",
STEALTH = "Stealth" "Stealth",
SWITCHPOINT = "Switchpoint" "Switchpoint",
TARGON = "Targon" "Targon",
TOGETHER = "Together" "Together",
UBICLOUD = "Ubicloud" "Ubicloud",
VENICE = "Venice" "Venice",
WAND_B = "WandB" "WandB",
X_AI = "xAI" "xAI",
Z_AI = "Z.AI" "Z.AI",
]
ChatStreamCompletionCreateParamsIgnoreUnionTypedDict = TypeAliasType( ChatStreamCompletionCreateParamsIgnoreUnionTypedDict = TypeAliasType(
"ChatStreamCompletionCreateParamsIgnoreUnionTypedDict", "ChatStreamCompletionCreateParamsIgnoreUnionTypedDict",
@@ -590,25 +571,12 @@ ChatStreamCompletionCreateParamsIgnoreUnion = TypeAliasType(
) )
class ChatStreamCompletionCreateParamsQuantization(str, Enum): ChatStreamCompletionCreateParamsQuantization = Literal[
INT4 = "int4" "int4", "int8", "fp4", "fp6", "fp8", "fp16", "bf16", "fp32", "unknown"
INT8 = "int8" ]
FP4 = "fp4"
FP6 = "fp6"
FP8 = "fp8"
FP16 = "fp16"
BF16 = "bf16"
FP32 = "fp32"
UNKNOWN = "unknown"
class ChatStreamCompletionCreateParamsSort(str, Enum):
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
PRICE = "price"
THROUGHPUT = "throughput"
LATENCY = "latency"
ChatStreamCompletionCreateParamsSort = Literal["price", "throughput", "latency"]
r"""The sorting strategy to use for this request, if \"order\" is not specified. When set, no load balancing is performed."""
ChatStreamCompletionCreateParamsPromptTypedDict = TypeAliasType( ChatStreamCompletionCreateParamsPromptTypedDict = TypeAliasType(
"ChatStreamCompletionCreateParamsPromptTypedDict", Union[float, str, Any] "ChatStreamCompletionCreateParamsPromptTypedDict", Union[float, str, Any]
@@ -817,14 +785,9 @@ class ChatStreamCompletionCreateParamsProvider(BaseModel):
return m return m
class ChatStreamCompletionCreateParamsIDFileParser(str, Enum): ChatStreamCompletionCreateParamsIDFileParser = Literal["file-parser"]
FILE_PARSER = "file-parser"
ChatStreamCompletionCreateParamsPdfEngine = Literal["mistral-ocr", "pdf-text", "native"]
class ChatStreamCompletionCreateParamsPdfEngine(str, Enum):
MISTRAL_OCR = "mistral-ocr"
PDF_TEXT = "pdf-text"
NATIVE = "native"
class ChatStreamCompletionCreateParamsPdfTypedDict(TypedDict): class ChatStreamCompletionCreateParamsPdfTypedDict(TypedDict):
@@ -849,8 +812,7 @@ class ChatStreamCompletionCreateParamsPluginFileParser(BaseModel):
pdf: Optional[ChatStreamCompletionCreateParamsPdf] = None pdf: Optional[ChatStreamCompletionCreateParamsPdf] = None
class ChatStreamCompletionCreateParamsIDChainOfThought(str, Enum): ChatStreamCompletionCreateParamsIDChainOfThought = Literal["chain-of-thought"]
CHAIN_OF_THOUGHT = "chain-of-thought"
class ChatStreamCompletionCreateParamsPluginChainOfThoughtTypedDict(TypedDict): class ChatStreamCompletionCreateParamsPluginChainOfThoughtTypedDict(TypedDict):
@@ -861,13 +823,9 @@ class ChatStreamCompletionCreateParamsPluginChainOfThought(BaseModel):
id: ChatStreamCompletionCreateParamsIDChainOfThought id: ChatStreamCompletionCreateParamsIDChainOfThought
class ChatStreamCompletionCreateParamsIDWeb(str, Enum): ChatStreamCompletionCreateParamsIDWeb = Literal["web"]
WEB = "web"
ChatStreamCompletionCreateParamsEngine = Literal["native", "exa"]
class ChatStreamCompletionCreateParamsEngine(str, Enum):
NATIVE = "native"
EXA = "exa"
class ChatStreamCompletionCreateParamsPluginWebTypedDict(TypedDict): class ChatStreamCompletionCreateParamsPluginWebTypedDict(TypedDict):
@@ -887,8 +845,7 @@ class ChatStreamCompletionCreateParamsPluginWeb(BaseModel):
engine: Optional[ChatStreamCompletionCreateParamsEngine] = None engine: Optional[ChatStreamCompletionCreateParamsEngine] = None
class ChatStreamCompletionCreateParamsIDModeration(str, Enum): ChatStreamCompletionCreateParamsIDModeration = Literal["moderation"]
MODERATION = "moderation"
class ChatStreamCompletionCreateParamsPluginModerationTypedDict(TypedDict): class ChatStreamCompletionCreateParamsPluginModerationTypedDict(TypedDict):
@@ -969,7 +926,7 @@ class ChatStreamCompletionCreateParamsTypedDict(TypedDict):
r"""Nucleus sampling parameter (0-1)""" r"""Nucleus sampling parameter (0-1)"""
user: NotRequired[str] user: NotRequired[str]
r"""Unique user identifier""" r"""Unique user identifier"""
models_llm: NotRequired[Nullable[List[str]]] fallback_models: NotRequired[Nullable[List[str]]]
r"""Order of models to fallback to for this request""" r"""Order of models to fallback to for this request"""
reasoning_effort: NotRequired[ reasoning_effort: NotRequired[
Nullable[ChatStreamCompletionCreateParamsReasoningEffort] Nullable[ChatStreamCompletionCreateParamsReasoningEffort]
@@ -1050,7 +1007,7 @@ class ChatStreamCompletionCreateParams(BaseModel):
user: Optional[str] = None user: Optional[str] = None
r"""Unique user identifier""" r"""Unique user identifier"""
models_llm: Annotated[ fallback_models: Annotated[
OptionalNullable[List[str]], pydantic.Field(alias="models") OptionalNullable[List[str]], pydantic.Field(alias="models")
] = UNSET ] = UNSET
r"""Order of models to fallback to for this request""" r"""Order of models to fallback to for this request"""
@@ -1089,7 +1046,7 @@ class ChatStreamCompletionCreateParams(BaseModel):
"tools", "tools",
"top_p", "top_p",
"user", "user",
"models_llm", "fallback_models",
"reasoning_effort", "reasoning_effort",
"provider", "provider",
"plugins", "plugins",
@@ -1108,7 +1065,7 @@ class ChatStreamCompletionCreateParams(BaseModel):
"stream_options", "stream_options",
"temperature", "temperature",
"top_p", "top_p",
"models_llm", "fallback_models",
"reasoning_effort", "reasoning_effort",
"provider", "provider",
] ]
@@ -1,18 +1,14 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import List, Optional, Union from typing import List, Literal, Optional, Union
from typing_extensions import NotRequired, TypeAliasType, TypedDict from typing_extensions import NotRequired, TypeAliasType, TypedDict
class TypeFile(str, Enum): TypeFile = Literal["file"]
FILE = "file"
ContentTypeImageURL = Literal["image_url"]
class ContentTypeImageURL(str, Enum):
IMAGE_URL = "image_url"
class FileAnnotationDetailImageURLTypedDict(TypedDict): class FileAnnotationDetailImageURLTypedDict(TypedDict):
@@ -34,8 +30,7 @@ class ContentImageURL(BaseModel):
image_url: FileAnnotationDetailImageURL image_url: FileAnnotationDetailImageURL
class ContentTypeText(str, Enum): ContentTypeText = Literal["text"]
TEXT = "text"
class ContentTextTypedDict(TypedDict): class ContentTextTypedDict(TypedDict):
@@ -1,7 +1,6 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -11,18 +10,15 @@ from openrouter.types import (
) )
import pydantic import pydantic
from pydantic import model_serializer from pydantic import model_serializer
from typing import Optional from typing import Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict from typing_extensions import Annotated, NotRequired, TypedDict
class ReasoningDetailEncryptedType(str, Enum): ReasoningDetailEncryptedType = Literal["reasoning.encrypted"]
REASONING_ENCRYPTED = "reasoning.encrypted"
ReasoningDetailEncryptedFormat = Literal[
class ReasoningDetailEncryptedFormat(str, Enum): "unknown", "openai-responses-v1", "anthropic-claude-v1"
UNKNOWN = "unknown" ]
OPENAI_RESPONSES_V1 = "openai-responses-v1"
ANTHROPIC_CLAUDE_V1 = "anthropic-claude-v1"
class ReasoningDetailEncryptedTypedDict(TypedDict): class ReasoningDetailEncryptedTypedDict(TypedDict):
@@ -46,7 +42,7 @@ class ReasoningDetailEncrypted(BaseModel):
format_: Annotated[ format_: Annotated[
OptionalNullable[ReasoningDetailEncryptedFormat], pydantic.Field(alias="format") OptionalNullable[ReasoningDetailEncryptedFormat], pydantic.Field(alias="format")
] = ReasoningDetailEncryptedFormat.ANTHROPIC_CLAUDE_V1 ] = "anthropic-claude-v1"
index: Optional[float] = None index: Optional[float] = None
@@ -1,7 +1,6 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -11,18 +10,15 @@ from openrouter.types import (
) )
import pydantic import pydantic
from pydantic import model_serializer from pydantic import model_serializer
from typing import Optional from typing import Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict from typing_extensions import Annotated, NotRequired, TypedDict
class ReasoningDetailSummaryType(str, Enum): ReasoningDetailSummaryType = Literal["reasoning.summary"]
REASONING_SUMMARY = "reasoning.summary"
ReasoningDetailSummaryFormat = Literal[
class ReasoningDetailSummaryFormat(str, Enum): "unknown", "openai-responses-v1", "anthropic-claude-v1"
UNKNOWN = "unknown" ]
OPENAI_RESPONSES_V1 = "openai-responses-v1"
ANTHROPIC_CLAUDE_V1 = "anthropic-claude-v1"
class ReasoningDetailSummaryTypedDict(TypedDict): class ReasoningDetailSummaryTypedDict(TypedDict):
@@ -46,7 +42,7 @@ class ReasoningDetailSummary(BaseModel):
format_: Annotated[ format_: Annotated[
OptionalNullable[ReasoningDetailSummaryFormat], pydantic.Field(alias="format") OptionalNullable[ReasoningDetailSummaryFormat], pydantic.Field(alias="format")
] = ReasoningDetailSummaryFormat.ANTHROPIC_CLAUDE_V1 ] = "anthropic-claude-v1"
index: Optional[float] = None index: Optional[float] = None
+6 -10
View File
@@ -1,7 +1,6 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import ( from openrouter.types import (
BaseModel, BaseModel,
Nullable, Nullable,
@@ -11,18 +10,15 @@ from openrouter.types import (
) )
import pydantic import pydantic
from pydantic import model_serializer from pydantic import model_serializer
from typing import Optional from typing import Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict from typing_extensions import Annotated, NotRequired, TypedDict
class ReasoningDetailTextType(str, Enum): ReasoningDetailTextType = Literal["reasoning.text"]
REASONING_TEXT = "reasoning.text"
ReasoningDetailTextFormat = Literal[
class ReasoningDetailTextFormat(str, Enum): "unknown", "openai-responses-v1", "anthropic-claude-v1"
UNKNOWN = "unknown" ]
OPENAI_RESPONSES_V1 = "openai-responses-v1"
ANTHROPIC_CLAUDE_V1 = "anthropic-claude-v1"
class ReasoningDetailTextTypedDict(TypedDict): class ReasoningDetailTextTypedDict(TypedDict):
@@ -49,7 +45,7 @@ class ReasoningDetailText(BaseModel):
format_: Annotated[ format_: Annotated[
OptionalNullable[ReasoningDetailTextFormat], pydantic.Field(alias="format") OptionalNullable[ReasoningDetailTextFormat], pydantic.Field(alias="format")
] = ReasoningDetailTextFormat.ANTHROPIC_CLAUDE_V1 ] = "anthropic-claude-v1"
index: Optional[float] = None index: Optional[float] = None
+2 -2
View File
@@ -8,11 +8,11 @@ from typing_extensions import Annotated, NotRequired, TypedDict
class SecurityTypedDict(TypedDict): class SecurityTypedDict(TypedDict):
bearer_auth: NotRequired[str] api_key: NotRequired[str]
class Security(BaseModel): class Security(BaseModel):
bearer_auth: Annotated[ api_key: Annotated[
Optional[str], Optional[str],
FieldMetadata( FieldMetadata(
security=SecurityMetadata( security=SecurityMetadata(
@@ -1,14 +1,12 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations from __future__ import annotations
from enum import Enum
from openrouter.types import BaseModel from openrouter.types import BaseModel
from typing import Optional from typing import Literal, Optional
from typing_extensions import NotRequired, TypedDict from typing_extensions import NotRequired, TypedDict
class URLCitationAnnotationDetailType(str, Enum): URLCitationAnnotationDetailType = Literal["url_citation"]
URL_CITATION = "url_citation"
class URLCitationTypedDict(TypedDict): class URLCitationTypedDict(TypedDict):
+20 -7
View File
@@ -10,6 +10,7 @@ import importlib
from openrouter import models, utils from openrouter import models, utils
from openrouter._hooks import SDKHooks from openrouter._hooks import SDKHooks
from openrouter.types import OptionalNullable, UNSET from openrouter.types import OptionalNullable, UNSET
import sys
from typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union, cast from typing import Any, Callable, Dict, List, Optional, TYPE_CHECKING, Union, cast
import weakref import weakref
@@ -30,7 +31,7 @@ class OpenRouter(BaseSDK):
def __init__( def __init__(
self, self,
bearer_auth: Optional[Union[Optional[str], Callable[[], Optional[str]]]] = None, api_key: Optional[Union[Optional[str], Callable[[], Optional[str]]]] = None,
provider_url: Optional[str] = None, provider_url: Optional[str] = None,
server_idx: Optional[int] = None, server_idx: Optional[int] = None,
server_url: Optional[str] = None, server_url: Optional[str] = None,
@@ -43,7 +44,7 @@ class OpenRouter(BaseSDK):
) -> None: ) -> None:
r"""Instantiates the SDK configuring it with the provided parameters. r"""Instantiates the SDK configuring it with the provided parameters.
:param bearer_auth: The bearer_auth required for authentication :param api_key: The api_key required for authentication
:param provider_url: Allows setting the provider_url variable for url substitution :param provider_url: Allows setting the provider_url variable for url substitution
:param server_idx: The index of the server to use for all methods :param server_idx: The index of the server to use for all methods
:param server_url: The server URL to use for all methods :param server_url: The server URL to use for all methods
@@ -75,11 +76,11 @@ class OpenRouter(BaseSDK):
), "The provided async_client must implement the AsyncHttpClient protocol." ), "The provided async_client must implement the AsyncHttpClient protocol."
security: Any = None security: Any = None
if callable(bearer_auth): if callable(api_key):
# pylint: disable=unnecessary-lambda-assignment # pylint: disable=unnecessary-lambda-assignment
security = lambda: models.Security(bearer_auth=bearer_auth()) security = lambda: models.Security(api_key=api_key())
else: else:
security = models.Security(bearer_auth=bearer_auth) security = models.Security(api_key=api_key)
if server_url is not None: if server_url is not None:
if url_params is not None: if url_params is not None:
@@ -105,6 +106,7 @@ class OpenRouter(BaseSDK):
timeout_ms=timeout_ms, timeout_ms=timeout_ms,
debug_logger=debug_logger, debug_logger=debug_logger,
), ),
parent_ref=self,
) )
hooks = SDKHooks() hooks = SDKHooks()
@@ -124,13 +126,24 @@ class OpenRouter(BaseSDK):
self.sdk_configuration.async_client_supplied, self.sdk_configuration.async_client_supplied,
) )
def dynamic_import(self, modname, retries=3):
for attempt in range(retries):
try:
return importlib.import_module(modname)
except KeyError:
# Clear any half-initialized module and retry
sys.modules.pop(modname, None)
if attempt == retries - 1:
break
raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")
def __getattr__(self, name: str): def __getattr__(self, name: str):
if name in self._sub_sdk_map: if name in self._sub_sdk_map:
module_path, class_name = self._sub_sdk_map[name] module_path, class_name = self._sub_sdk_map[name]
try: try:
module = importlib.import_module(module_path) module = self.dynamic_import(module_path)
klass = getattr(module, class_name) klass = getattr(module, class_name)
instance = klass(self.sdk_configuration) instance = klass(self.sdk_configuration, parent_ref=self)
setattr(self, name, instance) setattr(self, name, instance)
return instance return instance
except ImportError as e: except ImportError as e:
+15 -3
View File
@@ -3,6 +3,7 @@
from typing import TYPE_CHECKING from typing import TYPE_CHECKING
from importlib import import_module from importlib import import_module
import builtins import builtins
import sys
if TYPE_CHECKING: if TYPE_CHECKING:
from .annotations import get_discriminator from .annotations import get_discriminator
@@ -162,6 +163,18 @@ _dynamic_imports: dict[str, str] = {
} }
def dynamic_import(modname, retries=3):
for attempt in range(retries):
try:
return import_module(modname, __package__)
except KeyError:
# Clear any half-initialized module and retry
sys.modules.pop(modname, None)
if attempt == retries - 1:
break
raise KeyError(f"Failed to import module '{modname}' after {retries} attempts")
def __getattr__(attr_name: str) -> object: def __getattr__(attr_name: str) -> object:
module_name = _dynamic_imports.get(attr_name) module_name = _dynamic_imports.get(attr_name)
if module_name is None: if module_name is None:
@@ -170,9 +183,8 @@ def __getattr__(attr_name: str) -> object:
) )
try: try:
module = import_module(module_name, __package__) module = dynamic_import(module_name)
result = getattr(module, attr_name) return getattr(module, attr_name)
return result
except ImportError as e: except ImportError as e:
raise ImportError( raise ImportError(
f"Failed to import {attr_name} from {module_name}: {e}" f"Failed to import {attr_name} from {module_name}: {e}"
+10
View File
@@ -17,6 +17,9 @@ T = TypeVar("T")
class EventStream(Generic[T]): class EventStream(Generic[T]):
# Holds a reference to the SDK client to avoid it being garbage collected
# and cause termination of the underlying httpx client.
client_ref: Optional[object]
response: httpx.Response response: httpx.Response
generator: Generator[T, None, None] generator: Generator[T, None, None]
@@ -25,9 +28,11 @@ class EventStream(Generic[T]):
response: httpx.Response, response: httpx.Response,
decoder: Callable[[str], T], decoder: Callable[[str], T],
sentinel: Optional[str] = None, sentinel: Optional[str] = None,
client_ref: Optional[object] = None,
): ):
self.response = response self.response = response
self.generator = stream_events(response, decoder, sentinel) self.generator = stream_events(response, decoder, sentinel)
self.client_ref = client_ref
def __iter__(self): def __iter__(self):
return self return self
@@ -43,6 +48,9 @@ class EventStream(Generic[T]):
class EventStreamAsync(Generic[T]): class EventStreamAsync(Generic[T]):
# Holds a reference to the SDK client to avoid it being garbage collected
# and cause termination of the underlying httpx client.
client_ref: Optional[object]
response: httpx.Response response: httpx.Response
generator: AsyncGenerator[T, None] generator: AsyncGenerator[T, None]
@@ -51,9 +59,11 @@ class EventStreamAsync(Generic[T]):
response: httpx.Response, response: httpx.Response,
decoder: Callable[[str], T], decoder: Callable[[str], T],
sentinel: Optional[str] = None, sentinel: Optional[str] = None,
client_ref: Optional[object] = None,
): ):
self.response = response self.response = response
self.generator = stream_events_async(response, decoder, sentinel) self.generator = stream_events_async(response, decoder, sentinel)
self.client_ref = client_ref
def __aiter__(self): def __aiter__(self):
return self return self
+2 -2
View File
@@ -64,8 +64,8 @@ def get_security_from_env(security: Any, security_class: Any) -> Optional[BaseMo
security_dict: Any = {} security_dict: Any = {}
if os.getenv("OPENROUTER_BEARER_AUTH"): if os.getenv("OPENROUTER_API_KEY"):
security_dict["bearer_auth"] = os.getenv("OPENROUTER_BEARER_AUTH") security_dict["api_key"] = os.getenv("OPENROUTER_API_KEY")
return security_class(**security_dict) if security_dict else None return security_class(**security_dict) if security_dict else None
Generated
+1 -1
View File
@@ -201,7 +201,7 @@ wheels = [
[[package]] [[package]]
name = "openrouter" name = "openrouter"
version = "0.1.3" version = "0.5.2"
source = { editable = "." } source = { editable = "." }
dependencies = [ dependencies = [
{ name = "httpcore" }, { name = "httpcore" },