Compare commits

..
Author SHA1 Message Date
Matt Apperson 8f34360adc fixes 2025-11-18 15:34:20 -05:00
Matt Apperson c07f60e7b1 chore: regenerate Python SDK v0.0.21
Adds support for ChatMessageContentItemFile to enable file attachments in chat messages. Updates OpenAPI spec with file content type, adds overlays for open enums and RSS responses, and regenerates SDK components.
2025-11-18 15:28:28 -05:00
95 changed files with 8975 additions and 9385 deletions
+2 -1
View File
@@ -1,7 +1,8 @@
{
"permissions": {
"allow": [
"Bash(python3:*)"
"Bash(python3:*)",
"Bash(git push:*)"
],
"deny": [],
"ask": []
+18 -27
View File
@@ -1,12 +1,12 @@
lockVersion: 2.0.0
id: cfd52247-6a25-4c6d-bbce-fe6fce0cd69d
management:
docChecksum: d2e69fbbac1477d094fdfc212c13670c
docChecksum: 459a4007b7391a38a6e9c7249c84c3bf
docVersion: 1.0.0
speakeasyVersion: 1.668.0
generationVersion: 2.770.0
releaseVersion: 0.1.0
configChecksum: fa0d13fb5fd38982a589d64e64b0d87d
speakeasyVersion: 1.658.2
generationVersion: 2.755.9
releaseVersion: 0.0.22
configChecksum: dbd5388c5e9e39132e6f3418d4959462
repoURL: https://github.com/OpenRouterTeam/python-sdk.git
installationURL: https://github.com/OpenRouterTeam/python-sdk.git
published: true
@@ -15,7 +15,7 @@ features:
acceptHeaders: 3.0.0
additionalDependencies: 1.0.0
constsAndDefaults: 1.0.5
core: 5.23.13
core: 5.23.9
defaultEnabledRetries: 0.2.0
deprecations: 3.0.2
devContainers: 3.0.0
@@ -27,7 +27,6 @@ features:
globalSecurityCallbacks: 1.0.0
globalSecurityFlattening: 1.0.0
globalServerURLs: 3.2.0
globals: 3.0.0
groups: 3.0.1
methodArguments: 1.0.2
methodSecurity: 3.0.1
@@ -35,8 +34,8 @@ features:
nullables: 1.0.1
openEnums: 1.0.1
responseFormat: 1.0.1
retries: 3.0.3
sdkHooks: 1.2.0
retries: 3.0.2
sdkHooks: 1.1.0
serverEvents: 1.0.11
serverEventsSentinels: 0.1.0
serverIDs: 3.0.0
@@ -66,14 +65,16 @@ generatedFiles:
- docs/components/chatgenerationtokenusage.md
- docs/components/chatmessagecontentitem.md
- docs/components/chatmessagecontentitemaudio.md
- docs/components/chatmessagecontentitemaudioformat.md
- docs/components/chatmessagecontentitemaudioinputaudio.md
- docs/components/chatmessagecontentitemcachecontrol.md
- docs/components/chatmessagecontentitemfile.md
- docs/components/chatmessagecontentitemimage.md
- docs/components/chatmessagecontentitemimagedetail.md
- docs/components/chatmessagecontentitemtext.md
- docs/components/chatmessagecontentitemvideo.md
- docs/components/chatmessagecontentitemvideoinputvideo.md
- docs/components/chatmessagecontentitemvideovideourl.md
- docs/components/chatmessagecontentitemvideovideourlvideourl.md
- docs/components/chatmessagetokenlogprob.md
- docs/components/chatmessagetokenlogprobs.md
- docs/components/chatmessagetoolcall.md
@@ -106,12 +107,12 @@ generatedFiles:
- docs/components/costdetails.md
- docs/components/createchargerequest.md
- docs/components/datacollection.md
- docs/components/debug.md
- docs/components/defaultparameters.md
- docs/components/edgenetworktimeoutresponseerrordata.md
- docs/components/effort.md
- docs/components/endpointstatus.md
- docs/components/engine.md
- docs/components/file.md
- docs/components/filecitation.md
- docs/components/filecitationtype.md
- docs/components/filepath.md
@@ -119,7 +120,6 @@ generatedFiles:
- docs/components/forbiddenresponseerrordata.md
- docs/components/idfileparser.md
- docs/components/idmoderation.md
- docs/components/idresponsehealing.md
- docs/components/idweb.md
- docs/components/ignore.md
- docs/components/imagegenerationstatus.md
@@ -303,7 +303,6 @@ generatedFiles:
- docs/components/plugin.md
- docs/components/pluginfileparser.md
- docs/components/pluginmoderation.md
- docs/components/pluginresponsehealing.md
- docs/components/pluginweb.md
- docs/components/pricing.md
- docs/components/prompt.md
@@ -395,7 +394,6 @@ generatedFiles:
- docs/components/toplogprob.md
- docs/components/topproviderinfo.md
- docs/components/truncation.md
- docs/components/ttl.md
- docs/components/type.md
- docs/components/typeresponsecompleted.md
- docs/components/typeresponsecontentpartadded.md
@@ -421,8 +419,7 @@ generatedFiles:
- docs/components/usermessage.md
- docs/components/usermessagecontent.md
- docs/components/variables.md
- docs/components/videourl1.md
- docs/components/videourl2.md
- docs/components/videourl.md
- docs/components/websearchpreviewtooluserlocation.md
- docs/components/websearchpreviewtooluserlocationtype.md
- docs/components/websearchstatus.md
@@ -441,7 +438,6 @@ generatedFiles:
- docs/errors/toomanyrequestsresponseerror.md
- docs/errors/unauthorizedresponseerror.md
- docs/errors/unprocessableentityresponseerror.md
- docs/models/internal/globals.md
- docs/models/utils/retryconfig.md
- docs/operations/apitype.md
- docs/operations/calldata.md
@@ -459,6 +455,7 @@ generatedFiles:
- docs/operations/createembeddingsprovider.md
- docs/operations/createembeddingsrequest.md
- docs/operations/createembeddingsresponse.md
- docs/operations/createembeddingsresponsebody.md
- docs/operations/createkeysdata.md
- docs/operations/createkeyslimitreset.md
- docs/operations/createkeysrequest.md
@@ -472,7 +469,6 @@ generatedFiles:
- docs/operations/exchangeauthcodeforapikeycodechallengemethod.md
- docs/operations/exchangeauthcodeforapikeyrequest.md
- docs/operations/exchangeauthcodeforapikeyresponse.md
- docs/operations/getcreditsdata.md
- docs/operations/getcreditsresponse.md
- docs/operations/getcurrentkeydata.md
- docs/operations/getcurrentkeyresponse.md
@@ -555,13 +551,12 @@ generatedFiles:
- src/openrouter/components/assistantmessage.py
- src/openrouter/components/badgatewayresponseerrordata.py
- src/openrouter/components/badrequestresponseerrordata.py
- src/openrouter/components/chatcompletionfinishreason.py
- src/openrouter/components/chaterror.py
- src/openrouter/components/chatgenerationparams.py
- src/openrouter/components/chatgenerationtokenusage.py
- src/openrouter/components/chatmessagecontentitem.py
- src/openrouter/components/chatmessagecontentitemaudio.py
- src/openrouter/components/chatmessagecontentitemcachecontrol.py
- src/openrouter/components/chatmessagecontentitemfile.py
- src/openrouter/components/chatmessagecontentitemimage.py
- src/openrouter/components/chatmessagecontentitemtext.py
- src/openrouter/components/chatmessagecontentitemvideo.py
@@ -570,7 +565,6 @@ generatedFiles:
- src/openrouter/components/chatmessagetoolcall.py
- src/openrouter/components/chatresponse.py
- src/openrouter/components/chatresponsechoice.py
- src/openrouter/components/chatstreamingchoice.py
- src/openrouter/components/chatstreamingmessagechunk.py
- src/openrouter/components/chatstreamingmessagetoolcall.py
- src/openrouter/components/chatstreamingresponsechunk.py
@@ -693,6 +687,7 @@ generatedFiles:
- src/openrouter/components/unprocessableentityresponseerrordata.py
- src/openrouter/components/urlcitation.py
- src/openrouter/components/usermessage.py
- src/openrouter/components/videourl.py
- src/openrouter/components/websearchpreviewtooluserlocation.py
- src/openrouter/components/websearchstatus.py
- src/openrouter/credits.py
@@ -720,9 +715,6 @@ generatedFiles:
- src/openrouter/errors/unprocessableentityresponse_error.py
- src/openrouter/generations.py
- src/openrouter/httpclient.py
- src/openrouter/models/__init__.py
- src/openrouter/models/internal/__init__.py
- src/openrouter/models/internal/globals.py
- src/openrouter/models_.py
- src/openrouter/oauth.py
- src/openrouter/operations/__init__.py
@@ -776,7 +768,7 @@ examples:
createResponses:
speakeasy-default-create-responses:
requestBody:
application/json: {"input": [{"type": "message", "role": "user", "content": "Hello, how are you?"}], "tools": [{"type": "function", "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": {"type": "object", "properties": {"location": {"type": "string"}}}}], "model": "anthropic/claude-4.5-sonnet-20250929", "temperature": 0.7, "top_p": 0.9, "store": false, "service_tier": "auto", "stream": false}
application/json: {"input": [{"type": "message", "role": "user", "content": "Hello, how are you?"}], "tools": [{"type": "function", "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": {"type": "object", "properties": {"location": {"type": "string"}}}}], "model": "anthropic/claude-4.5-sonnet-20250929", "temperature": 0.7, "top_p": 0.9, "stream": false}
responses:
"200":
application/json: {"id": "resp-abc123", "object": "response", "created_at": 1704067200, "model": "gpt-4", "status": "completed", "output": [{"id": "msg-abc123", "role": "assistant", "type": "message", "status": "completed", "content": [{"type": "output_text", "text": "Hello! How can I help you today?", "annotations": []}]}], "error": null, "incomplete_details": null, "usage": {"input_tokens": 10, "input_tokens_details": {"cached_tokens": 0}, "output_tokens": 25, "output_tokens_details": {"reasoning_tokens": 0}, "total_tokens": 35}, "max_output_tokens": null, "temperature": null, "top_p": null, "instructions": null, "metadata": null, "tools": [], "tool_choice": "auto", "parallel_tool_calls": true}
@@ -826,7 +818,7 @@ examples:
speakeasy-default-get-credits:
responses:
"200":
application/json: {"data": {"total_credits": 100.5, "total_usage": 25.75}}
application/json: {}
"401":
application/json: {"error": {"code": 401, "message": "Missing Authentication header"}}
"403":
@@ -1116,4 +1108,3 @@ examples:
"500":
application/json: {"error": {"code": "<value>", "message": "<value>"}}
examplesVersion: 1.0.2
releaseNotes: "## Python SDK Changes:\n* `open_router.beta.responses.send()`: `request` **Changed** **Breaking** :warning:\n* `open_router.embeddings.generate()`: `response.status[200].content[text/event-stream` **Removed** **Breaking** :warning:\n* `open_router.chat.send()`: \n * `request` **Changed** **Breaking** :warning:\n * `response.choices.[].message.content.[array].[]` **Changed** **Breaking** :warning:\n* `open_router.credits.get_credits()`: `response.data` **Added**\n* `open_router.parameters.get_parameters()`: `request.provider` **Changed**\n* `open_router.completions.generate()`: `response` **Changed**\n"
+1 -3
View File
@@ -30,7 +30,7 @@ generation:
generateNewTests: true
skipResponseBodyAssertions: false
python:
version: 0.1.0
version: 0.0.22
additionalDependencies:
dev: {}
main: {}
@@ -62,14 +62,12 @@ python:
operations: operations
shared: components
webhooks: ""
inferUnionDiscriminators: true
inputModelSuffix: input
legacyPyright: false
license: Apache-2.0
maxMethodParams: 999
methodArguments: infer-optional-args
moduleName: ""
multipartArrayFormat: legacy
outputModelSuffix: output
packageManager: uv
packageName: openrouter
+30 -6
View File
@@ -4647,12 +4647,7 @@ components:
type: string
const: input_video
video_url:
type: object
properties:
url:
type: string
required:
- url
$ref: '#/components/schemas/VideoURL'
required:
- type
- video_url
@@ -4672,12 +4667,40 @@ components:
- type
- video_url
type: object
VideoURL:
type: object
properties:
url:
type: string
required:
- url
ChatMessageContentItemFile:
type: object
properties:
type:
type: string
const: file
file:
type: object
properties:
file_data:
type: string
file_id:
type: string
filename:
type: string
required:
- file_data
required:
- type
- file
ChatMessageContentItem:
oneOf:
- $ref: '#/components/schemas/ChatMessageContentItemText'
- $ref: '#/components/schemas/ChatMessageContentItemImage'
- $ref: '#/components/schemas/ChatMessageContentItemAudio'
- $ref: '#/components/schemas/ChatMessageContentItemVideo'
- $ref: '#/components/schemas/ChatMessageContentItemFile'
type: object
discriminator:
propertyName: type
@@ -4687,6 +4710,7 @@ components:
input_audio: '#/components/schemas/ChatMessageContentItemAudio'
input_video: '#/components/schemas/ChatMessageContentItemVideo'
video_url: '#/components/schemas/ChatMessageContentItemVideo'
file: '#/components/schemas/ChatMessageContentItemFile'
ChatMessageToolCall:
type: object
properties:
+8330 -8358
View File
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,10 @@
overlay: 1.0.0
x-speakeasy-jsonpath: rfc9535
info:
title: Add open enums
version: 0.0.0
actions:
- target: $..[?length(@.enum) > 1]
description: Automatically open all enums that have length > 1
update:
x-speakeasy-unknown-values: allow
@@ -0,0 +1,15 @@
overlay: 1.0.0
x-speakeasy-jsonpath: rfc9535
info:
title: Remove RSS+XML response schemas and related parameters
version: 0.0.0
actions:
- target: $..responses.*.content["application/rss+xml"]
description: Remove application/rss+xml response schemas
remove: true
- target: $..parameters[?@.name == "use_rss"]
description: Remove use_rss parameter
remove: true
- target: $..parameters[?@.name == "use_rss_chat_links"]
description: Remove use_rss_chat_links parameter
remove: true
+25 -11
View File
@@ -1,32 +1,46 @@
speakeasyVersion: 1.668.0
speakeasyVersion: 1.658.2
sources:
-OAS:
sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:697f956356ab0195b9a9b9a5106e4ac979caa551709b3614c723df972c661829
sourceBlobDigest: sha256:a286a09ceced7f78a685731aef81d1498b89a6a46f3794219dc93fa2d822853b
sourceRevisionDigest: sha256:fc0c90dc8ebb69ef4a571e4e63dcd7f8f33c3254c17ad2583b628fbbf3d1ac05
sourceBlobDigest: sha256:635d63fd18db468c1dcc23700382af788de76594ba3b8292fae9b14c0e5c22c4
tags:
- latest
- speakeasy-sdk-regen-1763684529
OpenRouter API:
sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:f1b59b9b643de5e20d6e3299a8274783d8c0854615876f5d7f6f081814842695
sourceBlobDigest: sha256:ee1f2422281b3ed5b38951c74636ad192c9bb160f216069c1f7931ccc4e52553
tags:
- latest
- 1.0.0
targets:
open-router:
source: -OAS
sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:697f956356ab0195b9a9b9a5106e4ac979caa551709b3614c723df972c661829
sourceBlobDigest: sha256:a286a09ceced7f78a685731aef81d1498b89a6a46f3794219dc93fa2d822853b
sourceRevisionDigest: sha256:fc0c90dc8ebb69ef4a571e4e63dcd7f8f33c3254c17ad2583b628fbbf3d1ac05
sourceBlobDigest: sha256:635d63fd18db468c1dcc23700382af788de76594ba3b8292fae9b14c0e5c22c4
openrouter:
source: OpenRouter API
sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:f1b59b9b643de5e20d6e3299a8274783d8c0854615876f5d7f6f081814842695
sourceBlobDigest: sha256:ee1f2422281b3ed5b38951c74636ad192c9bb160f216069c1f7931ccc4e52553
workflow:
workflowVersion: 1.0.0
speakeasyVersion: latest
sources:
-OAS:
OpenRouter API:
inputs:
- location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api:main
- location: .speakeasy/in.openapi.yaml
overlays:
- location: .speakeasy/overlays/open-enums.overlay.yaml
- location: .speakeasy/overlays/remove-rss-responses.overlay.yaml
output: .speakeasy/out.openapi.yaml
registry:
location: registry.speakeasyapi.dev/openrouter/sdk/-oas
location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api
targets:
open-router:
openrouter:
target: python
source: -OAS
source: OpenRouter API
publish:
pypi:
token: $pypi_token
+8 -5
View File
@@ -1,16 +1,19 @@
workflowVersion: 1.0.0
speakeasyVersion: latest
sources:
-OAS:
OpenRouter API:
inputs:
- location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api:main
- location: .speakeasy/in.openapi.yaml
overlays:
- location: .speakeasy/overlays/open-enums.overlay.yaml
- location: .speakeasy/overlays/remove-rss-responses.overlay.yaml
output: .speakeasy/out.openapi.yaml
registry:
location: registry.speakeasyapi.dev/openrouter/sdk/-oas
location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api
targets:
open-router:
openrouter:
target: python
source: -OAS
source: OpenRouter API
publish:
pypi:
token: $pypi_token
+1 -11
View File
@@ -8,14 +8,4 @@ Based on:
### Generated
- [python v0.0.16] .
### Releases
- [PyPI v0.0.16] https://pypi.org/project/openrouter/0.0.16 - .
## 2025-12-04 00:22:56
### Changes
Based on:
- OpenAPI Doc
- Speakeasy CLI 1.668.0 (2.770.0) https://github.com/speakeasy-api/speakeasy
### Generated
- [python v0.1.0] .
### Releases
- [PyPI v0.1.0] https://pypi.org/project/openrouter/0.1.0 - .
- [PyPI v0.0.16] https://pypi.org/project/openrouter/0.0.16 - .
+1 -2
View File
@@ -26,5 +26,4 @@
| `tool_choice` | *Optional[Any]* | :heavy_minus_sign: | N/A |
| `tools` | List[[components.ToolDefinitionJSON](../components/tooldefinitionjson.md)] | :heavy_minus_sign: | N/A |
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
| `user` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `debug` | [Optional[components.Debug]](../components/debug.md) | :heavy_minus_sign: | N/A |
| `user` | *Optional[str]* | :heavy_minus_sign: | N/A |
@@ -33,3 +33,9 @@ value: components.ChatMessageContentItemVideo = /* values here */
value: components.ChatMessageContentItemVideo = /* values here */
```
### `components.ChatMessageContentItemFile`
```python
value: components.ChatMessageContentItemFile = /* values here */
```
@@ -0,0 +1,14 @@
# ChatMessageContentItemAudioFormat
## Values
| Name | Value |
| ------- | ------- |
| `WAV` | wav |
| `MP3` | mp3 |
| `FLAC` | flac |
| `M4A` | m4a |
| `OGG` | ogg |
| `PCM16` | pcm16 |
| `PCM24` | pcm24 |
@@ -3,7 +3,7 @@
## Fields
| Field | Type | Required | Description |
| ------------------ | ------------------ | ------------------ | ------------------ |
| `data` | *str* | :heavy_check_mark: | N/A |
| `format_` | *str* | :heavy_check_mark: | N/A |
| Field | Type | Required | Description |
| -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------- |
| `data` | *str* | :heavy_check_mark: | N/A |
| `format_` | [components.ChatMessageContentItemAudioFormat](../components/chatmessagecontentitemaudioformat.md) | :heavy_check_mark: | N/A |
@@ -1,9 +0,0 @@
# ChatMessageContentItemCacheControl
## Fields
| Field | Type | Required | Description |
| ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ |
| `type` | *Literal["ephemeral"]* | :heavy_check_mark: | N/A |
| `ttl` | [Optional[components.TTL]](../components/ttl.md) | :heavy_minus_sign: | N/A |
@@ -0,0 +1,9 @@
# ChatMessageContentItemFile
## Fields
| Field | Type | Required | Description |
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| `type` | *Literal["file"]* | :heavy_check_mark: | N/A |
| `file` | [components.File](../components/file.md) | :heavy_check_mark: | N/A |
@@ -3,8 +3,7 @@
## Fields
| Field | Type | Required | Description |
| -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `type` | *Literal["text"]* | :heavy_check_mark: | N/A |
| `text` | *str* | :heavy_check_mark: | N/A |
| `cache_control` | [Optional[components.ChatMessageContentItemCacheControl]](../components/chatmessagecontentitemcachecontrol.md) | :heavy_minus_sign: | N/A |
| Field | Type | Required | Description |
| ------------------ | ------------------ | ------------------ | ------------------ |
| `type` | *Literal["text"]* | :heavy_check_mark: | N/A |
| `text` | *str* | :heavy_check_mark: | N/A |
@@ -3,7 +3,7 @@
## Fields
| Field | Type | Required | Description |
| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- |
| `type` | *Literal["input_video"]* | :heavy_check_mark: | N/A |
| `video_url` | [components.VideoURL1](../components/videourl1.md) | :heavy_check_mark: | N/A |
| Field | Type | Required | Description |
| ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ | ------------------------------------------------ |
| `type` | *Literal["input_video"]* | :heavy_check_mark: | N/A |
| `video_url` | [components.VideoURL](../components/videourl.md) | :heavy_check_mark: | N/A |
@@ -3,7 +3,7 @@
## Fields
| Field | Type | Required | Description |
| -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- | -------------------------------------------------- |
| `type` | *Literal["video_url"]* | :heavy_check_mark: | N/A |
| `video_url` | [components.VideoURL2](../components/videourl2.md) | :heavy_check_mark: | N/A |
| Field | Type | Required | Description |
| ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
| `type` | *Literal["video_url"]* | :heavy_check_mark: | N/A |
| `video_url` | [components.ChatMessageContentItemVideoVideoURLVideoURL](../components/chatmessagecontentitemvideovideourlvideourl.md) | :heavy_check_mark: | N/A |
@@ -1,4 +1,4 @@
# VideoURL2
# ChatMessageContentItemVideoVideoURLVideoURL
## Fields
+1 -3
View File
@@ -8,6 +8,4 @@
| `text` | *str* | :heavy_check_mark: | N/A |
| `index` | *float* | :heavy_check_mark: | N/A |
| `logprobs` | [Nullable[components.CompletionLogprobs]](../components/completionlogprobs.md) | :heavy_check_mark: | N/A |
| `finish_reason` | [Nullable[components.CompletionFinishReason]](../components/completionfinishreason.md) | :heavy_check_mark: | N/A |
| `native_finish_reason` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `reasoning` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A |
| `finish_reason` | [Nullable[components.CompletionFinishReason]](../components/completionfinishreason.md) | :heavy_check_mark: | N/A |
-1
View File
@@ -9,7 +9,6 @@
| `object` | *Literal["text_completion"]* | :heavy_check_mark: | N/A |
| `created` | *float* | :heavy_check_mark: | N/A |
| `model` | *str* | :heavy_check_mark: | N/A |
| `provider` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `system_fingerprint` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `choices` | List[[components.CompletionChoice](../components/completionchoice.md)] | :heavy_check_mark: | N/A |
| `usage` | [Optional[components.CompletionUsage]](../components/completionusage.md) | :heavy_minus_sign: | N/A |
-8
View File
@@ -1,8 +0,0 @@
# Debug
## Fields
| Field | Type | Required | Description |
| -------------------- | -------------------- | -------------------- | -------------------- |
| `echo_upstream_body` | *Optional[bool]* | :heavy_minus_sign: | N/A |
+10
View File
@@ -0,0 +1,10 @@
# File
## Fields
| Field | Type | Required | Description |
| ------------------ | ------------------ | ------------------ | ------------------ |
| `file_data` | *str* | :heavy_check_mark: | N/A |
| `file_id` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `filename` | *Optional[str]* | :heavy_minus_sign: | N/A |
-8
View File
@@ -1,8 +0,0 @@
# IDResponseHealing
## Values
| Name | Value |
| ------------------ | ------------------ |
| `RESPONSE_HEALING` | response-healing |
+2 -2
View File
@@ -27,8 +27,8 @@ Request schema for Responses endpoint
| `include` | List[[components.OpenAIResponsesIncludable](../components/openairesponsesincludable.md)] | :heavy_minus_sign: | N/A | |
| `background` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
| `safety_identifier` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `store` | *Optional[Literal[False]]* | :heavy_minus_sign: | N/A | |
| `service_tier` | [Optional[components.ServiceTier]](../components/servicetier.md) | :heavy_minus_sign: | N/A | |
| `store` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
| `service_tier` | [OptionalNullable[components.ServiceTier]](../components/servicetier.md) | :heavy_minus_sign: | N/A | auto |
| `truncation` | [OptionalNullable[components.Truncation]](../components/truncation.md) | :heavy_minus_sign: | N/A | auto |
| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | |
| `provider` | [OptionalNullable[components.Provider]](../components/provider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | |
-6
View File
@@ -21,9 +21,3 @@ value: components.PluginWeb = /* values here */
value: components.PluginFileParser = /* values here */
```
### `components.PluginResponseHealing`
```python
value: components.PluginResponseHealing = /* values here */
```
-8
View File
@@ -1,8 +0,0 @@
# PluginResponseHealing
## Fields
| Field | Type | Required | Description |
| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ |
| `id` | [components.IDResponseHealing](../components/idresponsehealing.md) | :heavy_check_mark: | N/A |
+1 -5
View File
@@ -9,14 +9,12 @@
| `AION_LABS` | AionLabs |
| `ALIBABA` | Alibaba |
| `AMAZON_BEDROCK` | Amazon Bedrock |
| `AMAZON_NOVA` | Amazon Nova |
| `ANTHROPIC` | Anthropic |
| `ARCEE_AI` | Arcee AI |
| `ARCEE` | Arcee |
| `ATLAS_CLOUD` | AtlasCloud |
| `AVIAN` | Avian |
| `AZURE` | Azure |
| `BASE_TEN` | BaseTen |
| `BYTE_PLUS` | BytePlus |
| `BLACK_FOREST_LABS` | Black Forest Labs |
| `CEREBRAS` | Cerebras |
| `CHUTES` | Chutes |
@@ -31,7 +29,6 @@
| `FIREWORKS` | Fireworks |
| `FRIENDLI` | Friendli |
| `GMI_CLOUD` | GMICloud |
| `GO_POMELO` | GoPomelo |
| `GOOGLE` | Google |
| `GOOGLE_AI_STUDIO` | Google AI Studio |
| `GROQ` | Groq |
@@ -62,7 +59,6 @@
| `SAMBA_NOVA` | SambaNova |
| `SILICON_FLOW` | SiliconFlow |
| `STEALTH` | Stealth |
| `STREAM_LAKE` | StreamLake |
| `SWITCHPOINT` | Switchpoint |
| `TARGON` | Targon |
| `TOGETHER` | Together |
+7 -3
View File
@@ -3,6 +3,10 @@
## Values
| Name | Value |
| ------ | ------ |
| `AUTO` | auto |
| Name | Value |
| ---------- | ---------- |
| `AUTO` | auto |
| `DEFAULT` | default |
| `FLEX` | flex |
| `PRIORITY` | priority |
| `SCALE` | scale |
-9
View File
@@ -1,9 +0,0 @@
# TTL
## Values
| Name | Value |
| ------- | ------- |
| `FIVEM` | 5m |
| `ONEH` | 1h |
@@ -1,4 +1,4 @@
# VideoURL1
# VideoURL
## Fields
-9
View File
@@ -1,9 +0,0 @@
# Globals
## Fields
| Field | Type | Required | Description |
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `http_referer` | *Optional[str]* | :heavy_minus_sign: | The app identifier should be your app's URL and is used as the primary identifier for rankings.<br/>This is used to track API usage per application.<br/> |
| `x_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> |
+12 -9
View File
@@ -1,14 +1,17 @@
# CreateEmbeddingsResponse
Embedding response
## Supported Types
## Fields
### `operations.CreateEmbeddingsResponseBody`
```python
value: operations.CreateEmbeddingsResponseBody = /* values here */
```
### `str`
```python
value: str = /* values here */
```
| Field | Type | Required | Description |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| `id` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `object` | [operations.Object](../operations/object.md) | :heavy_check_mark: | N/A |
| `data` | List[[operations.CreateEmbeddingsData](../operations/createembeddingsdata.md)] | :heavy_check_mark: | N/A |
| `model` | *str* | :heavy_check_mark: | N/A |
| `usage` | [Optional[operations.Usage]](../operations/usage.md) | :heavy_minus_sign: | N/A |
@@ -0,0 +1,14 @@
# CreateEmbeddingsResponseBody
Embedding response
## Fields
| Field | Type | Required | Description |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| `id` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `object` | [operations.Object](../operations/object.md) | :heavy_check_mark: | N/A |
| `data` | List[[operations.CreateEmbeddingsData](../operations/createembeddingsdata.md)] | :heavy_check_mark: | N/A |
| `model` | *str* | :heavy_check_mark: | N/A |
| `usage` | [Optional[operations.Usage]](../operations/usage.md) | :heavy_minus_sign: | N/A |
-9
View File
@@ -1,9 +0,0 @@
# GetCreditsData
## Fields
| Field | Type | Required | Description | Example |
| ----------------------- | ----------------------- | ----------------------- | ----------------------- | ----------------------- |
| `total_credits` | *float* | :heavy_check_mark: | Total credits purchased | 100.5 |
| `total_usage` | *float* | :heavy_check_mark: | Total credits used | 25.75 |
+2 -3
View File
@@ -5,6 +5,5 @@ Total credits purchased and used
## Fields
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
| `data` | [operations.GetCreditsData](../operations/getcreditsdata.md) | :heavy_check_mark: | N/A | {<br/>"total_credits": 100.5,<br/>"total_usage": 25.75<br/>} |
| Field | Type | Required | Description |
| ----------- | ----------- | ----------- | ----------- |
+1 -5
View File
@@ -9,14 +9,12 @@
| `AION_LABS` | AionLabs |
| `ALIBABA` | Alibaba |
| `AMAZON_BEDROCK` | Amazon Bedrock |
| `AMAZON_NOVA` | Amazon Nova |
| `ANTHROPIC` | Anthropic |
| `ARCEE_AI` | Arcee AI |
| `ARCEE` | Arcee |
| `ATLAS_CLOUD` | AtlasCloud |
| `AVIAN` | Avian |
| `AZURE` | Azure |
| `BASE_TEN` | BaseTen |
| `BYTE_PLUS` | BytePlus |
| `BLACK_FOREST_LABS` | Black Forest Labs |
| `CEREBRAS` | Cerebras |
| `CHUTES` | Chutes |
@@ -31,7 +29,6 @@
| `FIREWORKS` | Fireworks |
| `FRIENDLI` | Friendli |
| `GMI_CLOUD` | GMICloud |
| `GO_POMELO` | GoPomelo |
| `GOOGLE` | Google |
| `GOOGLE_AI_STUDIO` | Google AI Studio |
| `GROQ` | Groq |
@@ -62,7 +59,6 @@
| `SAMBA_NOVA` | SambaNova |
| `SILICON_FLOW` | SiliconFlow |
| `STEALTH` | Stealth |
| `STREAM_LAKE` | StreamLake |
| `SWITCHPOINT` | Switchpoint |
| `TARGON` | Targon |
| `TOGETHER` | Together |
-1
View File
@@ -58,7 +58,6 @@ with OpenRouter(
| `tools` | List[[components.ToolDefinitionJSON](../../components/tooldefinitionjson.md)] | :heavy_minus_sign: | N/A |
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
| `user` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `debug` | [Optional[components.Debug]](../../components/debug.md) | :heavy_minus_sign: | N/A |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. |
### Response
+2 -1
View File
@@ -112,7 +112,8 @@ with OpenRouter(
| `include` | List[[components.OpenAIResponsesIncludable](../../components/openairesponsesincludable.md)] | :heavy_minus_sign: | N/A | |
| `background` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
| `safety_identifier` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `service_tier` | [Optional[components.ServiceTier]](../../components/servicetier.md) | :heavy_minus_sign: | N/A | |
| `store` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
| `service_tier` | [OptionalNullable[components.ServiceTier]](../../components/servicetier.md) | :heavy_minus_sign: | N/A | auto |
| `truncation` | [OptionalNullable[components.Truncation]](../../components/truncation.md) | :heavy_minus_sign: | N/A | auto |
| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | |
| `provider` | [OptionalNullable[components.Provider]](../../components/provider.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | |
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "openrouter"
version = "0.1.0"
version = "0.0.22"
description = "Official Python Client SDK for OpenRouter."
authors = [{ name = "OpenRouter" },]
readme = "README-PYPI.md"
+3 -3
View File
@@ -3,10 +3,10 @@
import importlib.metadata
__title__: str = "openrouter"
__version__: str = "0.1.0"
__version__: str = "0.0.22"
__openapi_doc_version__: str = "1.0.0"
__gen_version__: str = "2.770.0"
__user_agent__: str = "speakeasy-sdk/python 0.1.0 2.770.0 1.0.0 openrouter"
__gen_version__: str = "2.755.9"
__user_agent__: str = "speakeasy-sdk/python 0.0.22 2.755.9 1.0.0 openrouter"
try:
if __package__ is not None:
-2
View File
@@ -58,7 +58,6 @@ class Analytics(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -167,7 +166,6 @@ class Analytics(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
-12
View File
@@ -60,7 +60,6 @@ class APIKeys(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -165,7 +164,6 @@ class APIKeys(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -282,7 +280,6 @@ class APIKeys(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", operations.CreateKeysRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -404,7 +401,6 @@ class APIKeys(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", operations.CreateKeysRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -531,7 +527,6 @@ class APIKeys(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request.body, False, False, "json", operations.UpdateKeysRequestBody
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -663,7 +658,6 @@ class APIKeys(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request.body, False, False, "json", operations.UpdateKeysRequestBody
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -775,7 +769,6 @@ class APIKeys(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -882,7 +875,6 @@ class APIKeys(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -989,7 +981,6 @@ class APIKeys(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -1096,7 +1087,6 @@ class APIKeys(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -1198,7 +1188,6 @@ class APIKeys(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -1290,7 +1279,6 @@ class APIKeys(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
-6
View File
@@ -60,7 +60,6 @@ class BaseSDK:
] = None,
url_override: Optional[str] = None,
http_headers: Optional[Mapping[str, str]] = None,
allow_empty_value: Optional[List[str]] = None,
) -> httpx.Request:
client = self.sdk_configuration.async_client
return self._build_request_with_client(
@@ -81,7 +80,6 @@ class BaseSDK:
get_serialized_body,
url_override,
http_headers,
allow_empty_value,
)
def _build_request(
@@ -104,7 +102,6 @@ class BaseSDK:
] = None,
url_override: Optional[str] = None,
http_headers: Optional[Mapping[str, str]] = None,
allow_empty_value: Optional[List[str]] = None,
) -> httpx.Request:
client = self.sdk_configuration.client
return self._build_request_with_client(
@@ -125,7 +122,6 @@ class BaseSDK:
get_serialized_body,
url_override,
http_headers,
allow_empty_value,
)
def _build_request_with_client(
@@ -149,7 +145,6 @@ class BaseSDK:
] = None,
url_override: Optional[str] = None,
http_headers: Optional[Mapping[str, str]] = None,
allow_empty_value: Optional[List[str]] = None,
) -> httpx.Request:
query_params = {}
@@ -165,7 +160,6 @@ class BaseSDK:
query_params = utils.get_query_params(
request if request_has_query_params else None,
_globals if request_has_query_params else None,
allow_empty_value,
)
else:
# Pick up the query parameter from the override so they can be
-16
View File
@@ -61,7 +61,6 @@ class Chat(BaseSDK):
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
debug: Optional[Union[components.Debug, components.DebugTypedDict]] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -93,7 +92,6 @@ class Chat(BaseSDK):
:param tools:
:param top_p:
:param user:
:param debug:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
@@ -146,7 +144,6 @@ class Chat(BaseSDK):
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
debug: Optional[Union[components.Debug, components.DebugTypedDict]] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -178,7 +175,6 @@ class Chat(BaseSDK):
:param tools:
:param top_p:
:param user:
:param debug:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
@@ -230,7 +226,6 @@ class Chat(BaseSDK):
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
debug: Optional[Union[components.Debug, components.DebugTypedDict]] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -262,7 +257,6 @@ class Chat(BaseSDK):
:param tools:
:param top_p:
:param user:
:param debug:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
@@ -311,7 +305,6 @@ class Chat(BaseSDK):
),
top_p=top_p,
user=user,
debug=utils.get_pydantic_model(debug, Optional[components.Debug]),
)
req = self._build_request(
@@ -330,7 +323,6 @@ class Chat(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", components.ChatGenerationParams
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -446,7 +438,6 @@ class Chat(BaseSDK):
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
debug: Optional[Union[components.Debug, components.DebugTypedDict]] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -478,7 +469,6 @@ class Chat(BaseSDK):
:param tools:
:param top_p:
:param user:
:param debug:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
@@ -531,7 +521,6 @@ class Chat(BaseSDK):
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
debug: Optional[Union[components.Debug, components.DebugTypedDict]] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -563,7 +552,6 @@ class Chat(BaseSDK):
:param tools:
:param top_p:
:param user:
:param debug:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
@@ -615,7 +603,6 @@ class Chat(BaseSDK):
] = None,
top_p: OptionalNullable[float] = UNSET,
user: Optional[str] = None,
debug: Optional[Union[components.Debug, components.DebugTypedDict]] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -647,7 +634,6 @@ class Chat(BaseSDK):
:param tools:
:param top_p:
:param user:
:param debug:
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
@@ -696,7 +682,6 @@ class Chat(BaseSDK):
),
top_p=top_p,
user=user,
debug=utils.get_pydantic_model(debug, Optional[components.Debug]),
)
req = self._build_request_async(
@@ -715,7 +700,6 @@ class Chat(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", components.ChatGenerationParams
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
-2
View File
@@ -136,7 +136,6 @@ class Completions(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", components.CompletionCreateParams
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -311,7 +310,6 @@ class Completions(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", components.CompletionCreateParams
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
+37 -43
View File
@@ -21,7 +21,6 @@ if TYPE_CHECKING:
BadRequestResponseErrorData,
BadRequestResponseErrorDataTypedDict,
)
from .chatcompletionfinishreason import ChatCompletionFinishReason
from .chaterror import ChatErrorError, ChatErrorErrorTypedDict, Code, CodeTypedDict
from .chatgenerationparams import (
ChatGenerationParams,
@@ -36,8 +35,6 @@ if TYPE_CHECKING:
ChatGenerationParamsStop,
ChatGenerationParamsStopTypedDict,
ChatGenerationParamsTypedDict,
Debug,
DebugTypedDict,
Effort,
Reasoning,
ReasoningTypedDict,
@@ -56,14 +53,16 @@ if TYPE_CHECKING:
)
from .chatmessagecontentitemaudio import (
ChatMessageContentItemAudio,
ChatMessageContentItemAudioFormat,
ChatMessageContentItemAudioInputAudio,
ChatMessageContentItemAudioInputAudioTypedDict,
ChatMessageContentItemAudioTypedDict,
)
from .chatmessagecontentitemcachecontrol import (
ChatMessageContentItemCacheControl,
ChatMessageContentItemCacheControlTypedDict,
TTL,
from .chatmessagecontentitemfile import (
ChatMessageContentItemFile,
ChatMessageContentItemFileTypedDict,
File,
FileTypedDict,
)
from .chatmessagecontentitemimage import (
ChatMessageContentItemImage,
@@ -83,10 +82,8 @@ if TYPE_CHECKING:
ChatMessageContentItemVideoTypedDict,
ChatMessageContentItemVideoVideoURL,
ChatMessageContentItemVideoVideoURLTypedDict,
VideoURL1,
VideoURL1TypedDict,
VideoURL2,
VideoURL2TypedDict,
ChatMessageContentItemVideoVideoURLVideoURL,
ChatMessageContentItemVideoVideoURLVideoURLTypedDict,
)
from .chatmessagetokenlogprob import (
ChatMessageTokenLogprob,
@@ -105,8 +102,13 @@ if TYPE_CHECKING:
ChatMessageToolCallTypedDict,
)
from .chatresponse import ChatResponse, ChatResponseTypedDict
from .chatresponsechoice import ChatResponseChoice, ChatResponseChoiceTypedDict
from .chatstreamingchoice import ChatStreamingChoice, ChatStreamingChoiceTypedDict
from .chatresponsechoice import (
ChatCompletionFinishReason,
ChatResponseChoice,
ChatResponseChoiceTypedDict,
ChatStreamingChoice,
ChatStreamingChoiceTypedDict,
)
from .chatstreamingmessagechunk import (
ChatStreamingMessageChunk,
ChatStreamingMessageChunkRole,
@@ -424,7 +426,6 @@ if TYPE_CHECKING:
Engine,
IDFileParser,
IDModeration,
IDResponseHealing,
IDWeb,
Ignore,
IgnoreTypedDict,
@@ -449,8 +450,6 @@ if TYPE_CHECKING:
PluginFileParserTypedDict,
PluginModeration,
PluginModerationTypedDict,
PluginResponseHealing,
PluginResponseHealingTypedDict,
PluginTypedDict,
PluginWeb,
PluginWebTypedDict,
@@ -785,6 +784,7 @@ if TYPE_CHECKING:
UserMessageContentTypedDict,
UserMessageTypedDict,
)
from .videourl import VideoURL, VideoURLTypedDict
from .websearchpreviewtooluserlocation import (
WebSearchPreviewToolUserLocation,
WebSearchPreviewToolUserLocationType,
@@ -825,11 +825,12 @@ __all__ = [
"ChatGenerationTokenUsageTypedDict",
"ChatMessageContentItem",
"ChatMessageContentItemAudio",
"ChatMessageContentItemAudioFormat",
"ChatMessageContentItemAudioInputAudio",
"ChatMessageContentItemAudioInputAudioTypedDict",
"ChatMessageContentItemAudioTypedDict",
"ChatMessageContentItemCacheControl",
"ChatMessageContentItemCacheControlTypedDict",
"ChatMessageContentItemFile",
"ChatMessageContentItemFileTypedDict",
"ChatMessageContentItemImage",
"ChatMessageContentItemImageDetail",
"ChatMessageContentItemImageTypedDict",
@@ -842,6 +843,8 @@ __all__ = [
"ChatMessageContentItemVideoTypedDict",
"ChatMessageContentItemVideoVideoURL",
"ChatMessageContentItemVideoVideoURLTypedDict",
"ChatMessageContentItemVideoVideoURLVideoURL",
"ChatMessageContentItemVideoVideoURLVideoURLTypedDict",
"ChatMessageTokenLogprob",
"ChatMessageTokenLogprobTypedDict",
"ChatMessageTokenLogprobs",
@@ -902,8 +905,6 @@ __all__ = [
"CreateChargeRequest",
"CreateChargeRequestTypedDict",
"DataCollection",
"Debug",
"DebugTypedDict",
"DefaultParameters",
"DefaultParametersTypedDict",
"EdgeNetworkTimeoutResponseErrorData",
@@ -911,17 +912,18 @@ __all__ = [
"Effort",
"EndpointStatus",
"Engine",
"File",
"FileCitation",
"FileCitationType",
"FileCitationTypedDict",
"FilePath",
"FilePathType",
"FilePathTypedDict",
"FileTypedDict",
"ForbiddenResponseErrorData",
"ForbiddenResponseErrorDataTypedDict",
"IDFileParser",
"IDModeration",
"IDResponseHealing",
"IDWeb",
"Ignore",
"IgnoreTypedDict",
@@ -1215,8 +1217,6 @@ __all__ = [
"PluginFileParserTypedDict",
"PluginModeration",
"PluginModerationTypedDict",
"PluginResponseHealing",
"PluginResponseHealingTypedDict",
"PluginTypedDict",
"PluginWeb",
"PluginWebTypedDict",
@@ -1342,7 +1342,6 @@ __all__ = [
"SystemMessageContent",
"SystemMessageContentTypedDict",
"SystemMessageTypedDict",
"TTL",
"Tokenizer",
"TooManyRequestsResponseErrorData",
"TooManyRequestsResponseErrorDataTypedDict",
@@ -1392,10 +1391,8 @@ __all__ = [
"UserMessageTypedDict",
"Variables",
"VariablesTypedDict",
"VideoURL1",
"VideoURL1TypedDict",
"VideoURL2",
"VideoURL2TypedDict",
"VideoURL",
"VideoURLTypedDict",
"WebSearchPreviewToolUserLocation",
"WebSearchPreviewToolUserLocationType",
"WebSearchPreviewToolUserLocationTypedDict",
@@ -1413,7 +1410,6 @@ _dynamic_imports: dict[str, str] = {
"BadGatewayResponseErrorDataTypedDict": ".badgatewayresponseerrordata",
"BadRequestResponseErrorData": ".badrequestresponseerrordata",
"BadRequestResponseErrorDataTypedDict": ".badrequestresponseerrordata",
"ChatCompletionFinishReason": ".chatcompletionfinishreason",
"ChatErrorError": ".chaterror",
"ChatErrorErrorTypedDict": ".chaterror",
"Code": ".chaterror",
@@ -1430,8 +1426,6 @@ _dynamic_imports: dict[str, str] = {
"ChatGenerationParamsStop": ".chatgenerationparams",
"ChatGenerationParamsStopTypedDict": ".chatgenerationparams",
"ChatGenerationParamsTypedDict": ".chatgenerationparams",
"Debug": ".chatgenerationparams",
"DebugTypedDict": ".chatgenerationparams",
"Effort": ".chatgenerationparams",
"Reasoning": ".chatgenerationparams",
"ReasoningTypedDict": ".chatgenerationparams",
@@ -1444,12 +1438,14 @@ _dynamic_imports: dict[str, str] = {
"ChatMessageContentItem": ".chatmessagecontentitem",
"ChatMessageContentItemTypedDict": ".chatmessagecontentitem",
"ChatMessageContentItemAudio": ".chatmessagecontentitemaudio",
"ChatMessageContentItemAudioFormat": ".chatmessagecontentitemaudio",
"ChatMessageContentItemAudioInputAudio": ".chatmessagecontentitemaudio",
"ChatMessageContentItemAudioInputAudioTypedDict": ".chatmessagecontentitemaudio",
"ChatMessageContentItemAudioTypedDict": ".chatmessagecontentitemaudio",
"ChatMessageContentItemCacheControl": ".chatmessagecontentitemcachecontrol",
"ChatMessageContentItemCacheControlTypedDict": ".chatmessagecontentitemcachecontrol",
"TTL": ".chatmessagecontentitemcachecontrol",
"ChatMessageContentItemFile": ".chatmessagecontentitemfile",
"ChatMessageContentItemFileTypedDict": ".chatmessagecontentitemfile",
"File": ".chatmessagecontentitemfile",
"FileTypedDict": ".chatmessagecontentitemfile",
"ChatMessageContentItemImage": ".chatmessagecontentitemimage",
"ChatMessageContentItemImageDetail": ".chatmessagecontentitemimage",
"ChatMessageContentItemImageTypedDict": ".chatmessagecontentitemimage",
@@ -1463,10 +1459,8 @@ _dynamic_imports: dict[str, str] = {
"ChatMessageContentItemVideoTypedDict": ".chatmessagecontentitemvideo",
"ChatMessageContentItemVideoVideoURL": ".chatmessagecontentitemvideo",
"ChatMessageContentItemVideoVideoURLTypedDict": ".chatmessagecontentitemvideo",
"VideoURL1": ".chatmessagecontentitemvideo",
"VideoURL1TypedDict": ".chatmessagecontentitemvideo",
"VideoURL2": ".chatmessagecontentitemvideo",
"VideoURL2TypedDict": ".chatmessagecontentitemvideo",
"ChatMessageContentItemVideoVideoURLVideoURL": ".chatmessagecontentitemvideo",
"ChatMessageContentItemVideoVideoURLVideoURLTypedDict": ".chatmessagecontentitemvideo",
"ChatMessageTokenLogprob": ".chatmessagetokenlogprob",
"ChatMessageTokenLogprobTypedDict": ".chatmessagetokenlogprob",
"TopLogprob": ".chatmessagetokenlogprob",
@@ -1479,10 +1473,11 @@ _dynamic_imports: dict[str, str] = {
"ChatMessageToolCallTypedDict": ".chatmessagetoolcall",
"ChatResponse": ".chatresponse",
"ChatResponseTypedDict": ".chatresponse",
"ChatCompletionFinishReason": ".chatresponsechoice",
"ChatResponseChoice": ".chatresponsechoice",
"ChatResponseChoiceTypedDict": ".chatresponsechoice",
"ChatStreamingChoice": ".chatstreamingchoice",
"ChatStreamingChoiceTypedDict": ".chatstreamingchoice",
"ChatStreamingChoice": ".chatresponsechoice",
"ChatStreamingChoiceTypedDict": ".chatresponsechoice",
"ChatStreamingMessageChunk": ".chatstreamingmessagechunk",
"ChatStreamingMessageChunkRole": ".chatstreamingmessagechunk",
"ChatStreamingMessageChunkTypedDict": ".chatstreamingmessagechunk",
@@ -1729,7 +1724,6 @@ _dynamic_imports: dict[str, str] = {
"Engine": ".openresponsesrequest",
"IDFileParser": ".openresponsesrequest",
"IDModeration": ".openresponsesrequest",
"IDResponseHealing": ".openresponsesrequest",
"IDWeb": ".openresponsesrequest",
"Ignore": ".openresponsesrequest",
"IgnoreTypedDict": ".openresponsesrequest",
@@ -1754,8 +1748,6 @@ _dynamic_imports: dict[str, str] = {
"PluginFileParserTypedDict": ".openresponsesrequest",
"PluginModeration": ".openresponsesrequest",
"PluginModerationTypedDict": ".openresponsesrequest",
"PluginResponseHealing": ".openresponsesrequest",
"PluginResponseHealingTypedDict": ".openresponsesrequest",
"PluginTypedDict": ".openresponsesrequest",
"PluginWeb": ".openresponsesrequest",
"PluginWebTypedDict": ".openresponsesrequest",
@@ -2006,6 +1998,8 @@ _dynamic_imports: dict[str, str] = {
"UserMessageContent": ".usermessage",
"UserMessageContentTypedDict": ".usermessage",
"UserMessageTypedDict": ".usermessage",
"VideoURL": ".videourl",
"VideoURLTypedDict": ".videourl",
"WebSearchPreviewToolUserLocation": ".websearchpreviewtooluserlocation",
"WebSearchPreviewToolUserLocationType": ".websearchpreviewtooluserlocation",
"WebSearchPreviewToolUserLocationTypedDict": ".websearchpreviewtooluserlocation",
@@ -1,17 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import UnrecognizedStr
from typing import Literal, Union
ChatCompletionFinishReason = Union[
Literal[
"tool_calls",
"stop",
"length",
"content_filter",
"error",
],
UnrecognizedStr,
]
@@ -21,9 +21,9 @@ from openrouter.types import (
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import get_discriminator, validate_const, validate_open_enum
from openrouter.utils import validate_const, validate_open_enum
import pydantic
from pydantic import Discriminator, Tag, model_serializer
from pydantic import model_serializer
from pydantic.functional_validators import AfterValidator, PlainValidator
from typing import Any, Dict, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
@@ -134,16 +134,16 @@ ChatGenerationParamsResponseFormatUnionTypedDict = TypeAliasType(
)
ChatGenerationParamsResponseFormatUnion = Annotated[
ChatGenerationParamsResponseFormatUnion = TypeAliasType(
"ChatGenerationParamsResponseFormatUnion",
Union[
Annotated[ChatGenerationParamsResponseFormatText, Tag("text")],
Annotated[ChatGenerationParamsResponseFormatJSONObject, Tag("json_object")],
Annotated[ResponseFormatJSONSchema, Tag("json_schema")],
Annotated[ResponseFormatTextGrammar, Tag("grammar")],
Annotated[ChatGenerationParamsResponseFormatPython, Tag("python")],
ChatGenerationParamsResponseFormatText,
ChatGenerationParamsResponseFormatJSONObject,
ChatGenerationParamsResponseFormatPython,
ResponseFormatJSONSchema,
ResponseFormatTextGrammar,
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
)
ChatGenerationParamsStopTypedDict = TypeAliasType(
@@ -156,14 +156,6 @@ ChatGenerationParamsStop = TypeAliasType(
)
class DebugTypedDict(TypedDict):
echo_upstream_body: NotRequired[bool]
class Debug(BaseModel):
echo_upstream_body: Optional[bool] = None
class ChatGenerationParamsTypedDict(TypedDict):
messages: List[MessageTypedDict]
model: NotRequired[str]
@@ -187,7 +179,6 @@ class ChatGenerationParamsTypedDict(TypedDict):
tools: NotRequired[List[ToolDefinitionJSONTypedDict]]
top_p: NotRequired[Nullable[float]]
user: NotRequired[str]
debug: NotRequired[DebugTypedDict]
class ChatGenerationParams(BaseModel):
@@ -235,8 +226,6 @@ class ChatGenerationParams(BaseModel):
user: Optional[str] = None
debug: Optional[Debug] = None
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = [
@@ -261,7 +250,6 @@ class ChatGenerationParams(BaseModel):
"tools",
"top_p",
"user",
"debug",
]
nullable_fields = [
"frequency_penalty",
@@ -5,6 +5,10 @@ from .chatmessagecontentitemaudio import (
ChatMessageContentItemAudio,
ChatMessageContentItemAudioTypedDict,
)
from .chatmessagecontentitemfile import (
ChatMessageContentItemFile,
ChatMessageContentItemFileTypedDict,
)
from .chatmessagecontentitemimage import (
ChatMessageContentItemImage,
ChatMessageContentItemImageTypedDict,
@@ -26,9 +30,10 @@ from typing_extensions import Annotated, TypeAliasType
ChatMessageContentItemTypedDict = TypeAliasType(
"ChatMessageContentItemTypedDict",
Union[
ChatMessageContentItemTextTypedDict,
ChatMessageContentItemImageTypedDict,
ChatMessageContentItemAudioTypedDict,
ChatMessageContentItemTextTypedDict,
ChatMessageContentItemFileTypedDict,
ChatMessageContentItemVideoTypedDict,
],
)
@@ -41,6 +46,7 @@ ChatMessageContentItem = Annotated[
Annotated[ChatMessageContentItemAudio, Tag("input_audio")],
Annotated[ChatMessageContentItemVideo, Tag("input_video")],
Annotated[ChatMessageContentItemVideo, Tag("video_url")],
Annotated[ChatMessageContentItemFile, Tag("file")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
@@ -1,23 +1,42 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import validate_const
from openrouter.types import BaseModel, UnrecognizedStr
from openrouter.utils import validate_const, validate_open_enum
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import Literal
from pydantic.functional_validators import AfterValidator, PlainValidator
from typing import Literal, Union
from typing_extensions import Annotated, TypedDict
ChatMessageContentItemAudioFormat = Union[
Literal[
"wav",
"mp3",
"flac",
"m4a",
"ogg",
"pcm16",
"pcm24",
],
UnrecognizedStr,
]
class ChatMessageContentItemAudioInputAudioTypedDict(TypedDict):
data: str
format_: str
format_: ChatMessageContentItemAudioFormat
class ChatMessageContentItemAudioInputAudio(BaseModel):
data: str
format_: Annotated[str, pydantic.Field(alias="format")]
format_: Annotated[
Annotated[
ChatMessageContentItemAudioFormat, PlainValidator(validate_open_enum(False))
],
pydantic.Field(alias="format"),
]
class ChatMessageContentItemAudioTypedDict(TypedDict):
@@ -1,32 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, UnrecognizedStr
from openrouter.utils import validate_const, validate_open_enum
import pydantic
from pydantic.functional_validators import AfterValidator, PlainValidator
from typing import Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypedDict
TTL = Union[
Literal[
"5m",
"1h",
],
UnrecognizedStr,
]
class ChatMessageContentItemCacheControlTypedDict(TypedDict):
type: Literal["ephemeral"]
ttl: NotRequired[TTL]
class ChatMessageContentItemCacheControl(BaseModel):
TYPE: Annotated[
Annotated[Literal["ephemeral"], AfterValidator(validate_const("ephemeral"))],
pydantic.Field(alias="type"),
] = "ephemeral"
ttl: Annotated[Optional[TTL], PlainValidator(validate_open_enum(False))] = None
@@ -0,0 +1,37 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class FileTypedDict(TypedDict):
file_data: str
file_id: NotRequired[str]
filename: NotRequired[str]
class File(BaseModel):
file_data: str
file_id: Optional[str] = None
filename: Optional[str] = None
class ChatMessageContentItemFileTypedDict(TypedDict):
file: FileTypedDict
type: Literal["file"]
class ChatMessageContentItemFile(BaseModel):
file: File
TYPE: Annotated[
Annotated[Literal["file"], AfterValidator(validate_const("file"))],
pydantic.Field(alias="type"),
] = "file"
@@ -1,22 +1,17 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatmessagecontentitemcachecontrol import (
ChatMessageContentItemCacheControl,
ChatMessageContentItemCacheControlTypedDict,
)
from openrouter.types import BaseModel
from openrouter.utils import validate_const
import pydantic
from pydantic.functional_validators import AfterValidator
from typing import Literal, Optional
from typing_extensions import Annotated, NotRequired, TypedDict
from typing import Literal
from typing_extensions import Annotated, TypedDict
class ChatMessageContentItemTextTypedDict(TypedDict):
text: str
type: Literal["text"]
cache_control: NotRequired[ChatMessageContentItemCacheControlTypedDict]
class ChatMessageContentItemText(BaseModel):
@@ -26,5 +21,3 @@ class ChatMessageContentItemText(BaseModel):
Annotated[Literal["text"], AfterValidator(validate_const("text"))],
pydantic.Field(alias="type"),
] = "text"
cache_control: Optional[ChatMessageContentItemCacheControl] = None
@@ -1,30 +1,30 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .videourl import VideoURL, VideoURLTypedDict
from openrouter.types import BaseModel
from openrouter.utils import get_discriminator, validate_const
from openrouter.utils import validate_const
import pydantic
from pydantic import Discriminator, Tag
from pydantic.functional_validators import AfterValidator
from typing import Literal, Union
from typing_extensions import Annotated, TypeAliasType, TypedDict
class VideoURL2TypedDict(TypedDict):
class ChatMessageContentItemVideoVideoURLVideoURLTypedDict(TypedDict):
url: str
class VideoURL2(BaseModel):
class ChatMessageContentItemVideoVideoURLVideoURL(BaseModel):
url: str
class ChatMessageContentItemVideoVideoURLTypedDict(TypedDict):
video_url: VideoURL2TypedDict
video_url: ChatMessageContentItemVideoVideoURLVideoURLTypedDict
type: Literal["video_url"]
class ChatMessageContentItemVideoVideoURL(BaseModel):
video_url: VideoURL2
video_url: ChatMessageContentItemVideoVideoURLVideoURL
TYPE: Annotated[
Annotated[Literal["video_url"], AfterValidator(validate_const("video_url"))],
@@ -32,21 +32,13 @@ class ChatMessageContentItemVideoVideoURL(BaseModel):
] = "video_url"
class VideoURL1TypedDict(TypedDict):
url: str
class VideoURL1(BaseModel):
url: str
class ChatMessageContentItemVideoInputVideoTypedDict(TypedDict):
video_url: VideoURL1TypedDict
video_url: VideoURLTypedDict
type: Literal["input_video"]
class ChatMessageContentItemVideoInputVideo(BaseModel):
video_url: VideoURL1
video_url: VideoURL
TYPE: Annotated[
Annotated[
@@ -65,10 +57,7 @@ ChatMessageContentItemVideoTypedDict = TypeAliasType(
)
ChatMessageContentItemVideo = Annotated[
Union[
Annotated[ChatMessageContentItemVideoInputVideo, Tag("input_video")],
Annotated[ChatMessageContentItemVideoVideoURL, Tag("video_url")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
ChatMessageContentItemVideo = TypeAliasType(
"ChatMessageContentItemVideo",
Union[ChatMessageContentItemVideoInputVideo, ChatMessageContentItemVideoVideoURL],
)
@@ -2,24 +2,41 @@
from __future__ import annotations
from .assistantmessage import AssistantMessage, AssistantMessageTypedDict
from .chatcompletionfinishreason import ChatCompletionFinishReason
from .chatmessagetokenlogprobs import (
ChatMessageTokenLogprobs,
ChatMessageTokenLogprobsTypedDict,
)
from .chatstreamingmessagechunk import (
ChatStreamingMessageChunk,
ChatStreamingMessageChunkTypedDict,
)
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Literal, Union
from typing_extensions import Annotated, NotRequired, TypedDict
ChatCompletionFinishReason = Union[
Literal[
"tool_calls",
"stop",
"length",
"content_filter",
"error",
],
UnrecognizedStr,
]
class ChatResponseChoiceTypedDict(TypedDict):
finish_reason: Nullable[ChatCompletionFinishReason]
index: float
@@ -67,3 +84,52 @@ class ChatResponseChoice(BaseModel):
m[k] = val
return m
class ChatStreamingChoiceTypedDict(TypedDict):
delta: ChatStreamingMessageChunkTypedDict
finish_reason: Nullable[ChatCompletionFinishReason]
index: float
logprobs: NotRequired[Nullable[ChatMessageTokenLogprobsTypedDict]]
class ChatStreamingChoice(BaseModel):
delta: ChatStreamingMessageChunk
finish_reason: Annotated[
Nullable[ChatCompletionFinishReason], PlainValidator(validate_open_enum(False))
]
index: float
logprobs: OptionalNullable[ChatMessageTokenLogprobs] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["logprobs"]
nullable_fields = ["finish_reason", "logprobs"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -1,72 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .chatcompletionfinishreason import ChatCompletionFinishReason
from .chatmessagetokenlogprobs import (
ChatMessageTokenLogprobs,
ChatMessageTokenLogprobsTypedDict,
)
from .chatstreamingmessagechunk import (
ChatStreamingMessageChunk,
ChatStreamingMessageChunkTypedDict,
)
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing_extensions import Annotated, NotRequired, TypedDict
class ChatStreamingChoiceTypedDict(TypedDict):
delta: ChatStreamingMessageChunkTypedDict
finish_reason: Nullable[ChatCompletionFinishReason]
index: float
logprobs: NotRequired[Nullable[ChatMessageTokenLogprobsTypedDict]]
class ChatStreamingChoice(BaseModel):
delta: ChatStreamingMessageChunk
finish_reason: Annotated[
Nullable[ChatCompletionFinishReason], PlainValidator(validate_open_enum(False))
]
index: float
logprobs: OptionalNullable[ChatMessageTokenLogprobs] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["logprobs"]
nullable_fields = ["finish_reason", "logprobs"]
null_default_fields = []
serialized = handler(self)
m = {}
for n, f in type(self).model_fields.items():
k = f.alias or n
val = serialized.get(k)
serialized.pop(k, None)
optional_nullable = k in optional_fields and k in nullable_fields
is_set = (
self.__pydantic_fields_set__.intersection({n})
or k in null_default_fields
) # pylint: disable=no-member
if val is not None and val != UNSET_SENTINEL:
m[k] = val
elif val != UNSET_SENTINEL and (
not k in optional_fields or (optional_nullable and is_set)
):
m[k] = val
return m
@@ -5,7 +5,7 @@ from .chatgenerationtokenusage import (
ChatGenerationTokenUsage,
ChatGenerationTokenUsageTypedDict,
)
from .chatstreamingchoice import ChatStreamingChoice, ChatStreamingChoiceTypedDict
from .chatresponsechoice import ChatStreamingChoice, ChatStreamingChoiceTypedDict
from openrouter.types import (
BaseModel,
Nullable,
+5 -18
View File
@@ -2,19 +2,12 @@
from __future__ import annotations
from .completionlogprobs import CompletionLogprobs, CompletionLogprobsTypedDict
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL, UnrecognizedStr
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypedDict
from typing import Literal, Union
from typing_extensions import Annotated, TypedDict
CompletionFinishReason = Union[
@@ -32,8 +25,6 @@ class CompletionChoiceTypedDict(TypedDict):
index: float
logprobs: Nullable[CompletionLogprobsTypedDict]
finish_reason: Nullable[CompletionFinishReason]
native_finish_reason: NotRequired[str]
reasoning: NotRequired[Nullable[str]]
class CompletionChoice(BaseModel):
@@ -47,14 +38,10 @@ class CompletionChoice(BaseModel):
Nullable[CompletionFinishReason], PlainValidator(validate_open_enum(False))
]
native_finish_reason: Optional[str] = None
reasoning: OptionalNullable[str] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["native_finish_reason", "reasoning"]
nullable_fields = ["logprobs", "finish_reason", "reasoning"]
optional_fields = []
nullable_fields = ["logprobs", "finish_reason"]
null_default_fields = []
serialized = handler(self)
@@ -16,9 +16,9 @@ from openrouter.types import (
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import get_discriminator, validate_const
from openrouter.utils import validate_const
import pydantic
from pydantic import Discriminator, Tag, model_serializer
from pydantic import model_serializer
from pydantic.functional_validators import AfterValidator
from typing import Dict, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
@@ -127,16 +127,16 @@ CompletionCreateParamsResponseFormatUnionTypedDict = TypeAliasType(
)
CompletionCreateParamsResponseFormatUnion = Annotated[
CompletionCreateParamsResponseFormatUnion = TypeAliasType(
"CompletionCreateParamsResponseFormatUnion",
Union[
Annotated[CompletionCreateParamsResponseFormatText, Tag("text")],
Annotated[CompletionCreateParamsResponseFormatJSONObject, Tag("json_object")],
Annotated[ResponseFormatJSONSchema, Tag("json_schema")],
Annotated[ResponseFormatTextGrammar, Tag("grammar")],
Annotated[CompletionCreateParamsResponseFormatPython, Tag("python")],
CompletionCreateParamsResponseFormatText,
CompletionCreateParamsResponseFormatJSONObject,
CompletionCreateParamsResponseFormatPython,
ResponseFormatJSONSchema,
ResponseFormatTextGrammar,
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
)
class CompletionCreateParamsTypedDict(TypedDict):
@@ -17,7 +17,6 @@ class CompletionResponseTypedDict(TypedDict):
model: str
choices: List[CompletionChoiceTypedDict]
object: Literal["text_completion"]
provider: NotRequired[str]
system_fingerprint: NotRequired[str]
usage: NotRequired[CompletionUsageTypedDict]
@@ -39,8 +38,6 @@ class CompletionResponse(BaseModel):
pydantic.Field(alias="object"),
] = "text_completion"
provider: Optional[str] = None
system_fingerprint: Optional[str] = None
usage: Optional[CompletionUsage] = None
+9 -10
View File
@@ -10,9 +10,8 @@ from .systemmessage import SystemMessage, SystemMessageTypedDict
from .toolresponsemessage import ToolResponseMessage, ToolResponseMessageTypedDict
from .usermessage import UserMessage, UserMessageTypedDict
from openrouter.types import BaseModel
from openrouter.utils import get_discriminator, validate_const
from openrouter.utils import validate_const
import pydantic
from pydantic import Discriminator, Tag
from pydantic.functional_validators import AfterValidator
from typing import List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
@@ -57,13 +56,13 @@ MessageTypedDict = TypeAliasType(
)
Message = Annotated[
Message = TypeAliasType(
"Message",
Union[
Annotated[SystemMessage, Tag("system")],
Annotated[UserMessage, Tag("user")],
Annotated[MessageDeveloper, Tag("developer")],
Annotated[AssistantMessage, Tag("assistant")],
Annotated[ToolResponseMessage, Tag("tool")],
SystemMessage,
UserMessage,
MessageDeveloper,
ToolResponseMessage,
AssistantMessage,
],
Discriminator(lambda m: get_discriminator(m, "role", "role")),
]
)
@@ -4,10 +4,8 @@ from __future__ import annotations
from .filecitation import FileCitation, FileCitationTypedDict
from .filepath import FilePath, FilePathTypedDict
from .urlcitation import URLCitation, URLCitationTypedDict
from openrouter.utils import get_discriminator
from pydantic import Discriminator, Tag
from typing import Union
from typing_extensions import Annotated, TypeAliasType
from typing_extensions import TypeAliasType
OpenAIResponsesAnnotationTypedDict = TypeAliasType(
@@ -16,11 +14,6 @@ OpenAIResponsesAnnotationTypedDict = TypeAliasType(
)
OpenAIResponsesAnnotation = Annotated[
Union[
Annotated[FileCitation, Tag("file_citation")],
Annotated[URLCitation, Tag("url_citation")],
Annotated[FilePath, Tag("file_path")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
OpenAIResponsesAnnotation = TypeAliasType(
"OpenAIResponsesAnnotation", Union[FilePath, FileCitation, URLCitation]
)
@@ -48,8 +48,8 @@ from openrouter.types import (
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import get_discriminator, validate_open_enum
from pydantic import Discriminator, Tag, model_serializer
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Any, Dict, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
@@ -127,19 +127,16 @@ OpenResponsesNonStreamingResponseToolUnionTypedDict = TypeAliasType(
)
OpenResponsesNonStreamingResponseToolUnion = Annotated[
OpenResponsesNonStreamingResponseToolUnion = TypeAliasType(
"OpenResponsesNonStreamingResponseToolUnion",
Union[
Annotated[OpenResponsesNonStreamingResponseToolFunction, Tag("function")],
Annotated[OpenResponsesWebSearchPreviewTool, Tag("web_search_preview")],
Annotated[
OpenResponsesWebSearchPreview20250311Tool,
Tag("web_search_preview_2025_03_11"),
],
Annotated[OpenResponsesWebSearchTool, Tag("web_search")],
Annotated[OpenResponsesWebSearch20250826Tool, Tag("web_search_2025_08_26")],
OpenResponsesWebSearchPreviewTool,
OpenResponsesWebSearchPreview20250311Tool,
OpenResponsesWebSearchTool,
OpenResponsesWebSearch20250826Tool,
OpenResponsesNonStreamingResponseToolFunction,
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
)
class OpenResponsesNonStreamingResponseTypedDict(TypedDict):
@@ -44,10 +44,9 @@ from openrouter.types import (
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import get_discriminator, validate_const, validate_open_enum
import pydantic
from pydantic import Discriminator, Tag, model_serializer
from pydantic.functional_validators import AfterValidator, PlainValidator
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Any, Dict, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
@@ -121,24 +120,30 @@ OpenResponsesRequestToolUnionTypedDict = TypeAliasType(
)
OpenResponsesRequestToolUnion = Annotated[
OpenResponsesRequestToolUnion = TypeAliasType(
"OpenResponsesRequestToolUnion",
Union[
Annotated[OpenResponsesRequestToolFunction, Tag("function")],
Annotated[OpenResponsesWebSearchPreviewTool, Tag("web_search_preview")],
Annotated[
OpenResponsesWebSearchPreview20250311Tool,
Tag("web_search_preview_2025_03_11"),
],
Annotated[OpenResponsesWebSearchTool, Tag("web_search")],
Annotated[OpenResponsesWebSearch20250826Tool, Tag("web_search_2025_08_26")],
OpenResponsesWebSearchPreviewTool,
OpenResponsesWebSearchPreview20250311Tool,
OpenResponsesWebSearchTool,
OpenResponsesWebSearch20250826Tool,
OpenResponsesRequestToolFunction,
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
)
ServiceTier = Union[
Literal[
"auto",
"default",
"flex",
"priority",
"scale",
],
UnrecognizedStr,
]
ServiceTier = Literal["auto",]
Truncation = Union[
Literal[
"auto",
@@ -348,17 +353,6 @@ class Provider(BaseModel):
return m
IDResponseHealing = Literal["response-healing",]
class PluginResponseHealingTypedDict(TypedDict):
id: IDResponseHealing
class PluginResponseHealing(BaseModel):
id: IDResponseHealing
IDFileParser = Literal["file-parser",]
@@ -440,24 +434,11 @@ class PluginModeration(BaseModel):
PluginTypedDict = TypeAliasType(
"PluginTypedDict",
Union[
PluginModerationTypedDict,
PluginResponseHealingTypedDict,
PluginFileParserTypedDict,
PluginWebTypedDict,
],
Union[PluginModerationTypedDict, PluginFileParserTypedDict, PluginWebTypedDict],
)
Plugin = Annotated[
Union[
Annotated[PluginModeration, Tag("moderation")],
Annotated[PluginWeb, Tag("web")],
Annotated[PluginFileParser, Tag("file-parser")],
Annotated[PluginResponseHealing, Tag("response-healing")],
],
Discriminator(lambda m: get_discriminator(m, "id", "id")),
]
Plugin = TypeAliasType("Plugin", Union[PluginModeration, PluginFileParser, PluginWeb])
class OpenResponsesRequestTypedDict(TypedDict):
@@ -487,8 +468,8 @@ class OpenResponsesRequestTypedDict(TypedDict):
include: NotRequired[Nullable[List[OpenAIResponsesIncludable]]]
background: NotRequired[Nullable[bool]]
safety_identifier: NotRequired[Nullable[str]]
store: Literal[False]
service_tier: NotRequired[ServiceTier]
store: NotRequired[Nullable[bool]]
service_tier: NotRequired[Nullable[ServiceTier]]
truncation: NotRequired[Nullable[Truncation]]
stream: NotRequired[bool]
provider: NotRequired[Nullable[ProviderTypedDict]]
@@ -552,12 +533,11 @@ class OpenResponsesRequest(BaseModel):
safety_identifier: OptionalNullable[str] = UNSET
STORE: Annotated[
Annotated[Optional[Literal[False]], AfterValidator(validate_const(False))],
pydantic.Field(alias="store"),
] = False
store: OptionalNullable[bool] = UNSET
service_tier: Optional[ServiceTier] = "auto"
service_tier: Annotated[
OptionalNullable[ServiceTier], PlainValidator(validate_open_enum(False))
] = UNSET
truncation: Annotated[
OptionalNullable[Truncation], PlainValidator(validate_open_enum(False))
@@ -619,6 +599,8 @@ class OpenResponsesRequest(BaseModel):
"include",
"background",
"safety_identifier",
"store",
"service_tier",
"truncation",
"provider",
]
@@ -59,10 +59,8 @@ from .reasoningtextcontent import ReasoningTextContent, ReasoningTextContentType
from .responseoutputtext import ResponseOutputText, ResponseOutputTextTypedDict
from .responsesoutputitem import ResponsesOutputItem, ResponsesOutputItemTypedDict
from openrouter.types import BaseModel
from openrouter.utils import get_discriminator
from pydantic import Discriminator, Tag
from typing import List, Literal, Union
from typing_extensions import Annotated, TypeAliasType, TypedDict
from typing_extensions import TypeAliasType, TypedDict
TypeResponseReasoningSummaryPartDone = Literal["response.reasoning_summary_part.done",]
@@ -330,14 +328,10 @@ Part2TypedDict = TypeAliasType(
)
Part2 = Annotated[
Union[
Annotated[ResponseOutputText, Tag("output_text")],
Annotated[ReasoningTextContent, Tag("reasoning_text")],
Annotated[OpenAIResponsesRefusalContent, Tag("refusal")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
Part2 = TypeAliasType(
"Part2",
Union[ReasoningTextContent, OpenAIResponsesRefusalContent, ResponseOutputText],
)
class OpenResponsesStreamEventResponseContentPartDoneTypedDict(TypedDict):
@@ -380,14 +374,10 @@ Part1TypedDict = TypeAliasType(
)
Part1 = Annotated[
Union[
Annotated[ResponseOutputText, Tag("output_text")],
Annotated[ReasoningTextContent, Tag("reasoning_text")],
Annotated[OpenAIResponsesRefusalContent, Tag("refusal")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
Part1 = TypeAliasType(
"Part1",
Union[ReasoningTextContent, OpenAIResponsesRefusalContent, ResponseOutputText],
)
class OpenResponsesStreamEventResponseContentPartAddedTypedDict(TypedDict):
@@ -619,97 +609,36 @@ OpenResponsesStreamEventTypedDict = TypeAliasType(
r"""Union of all possible event types emitted during response streaming"""
OpenResponsesStreamEvent = Annotated[
OpenResponsesStreamEvent = TypeAliasType(
"OpenResponsesStreamEvent",
Union[
Annotated[OpenResponsesStreamEventResponseCreated, Tag("response.created")],
Annotated[
OpenResponsesStreamEventResponseInProgress, Tag("response.in_progress")
],
Annotated[OpenResponsesStreamEventResponseCompleted, Tag("response.completed")],
Annotated[
OpenResponsesStreamEventResponseIncomplete, Tag("response.incomplete")
],
Annotated[OpenResponsesStreamEventResponseFailed, Tag("response.failed")],
Annotated[OpenResponsesErrorEvent, Tag("error")],
Annotated[
OpenResponsesStreamEventResponseOutputItemAdded,
Tag("response.output_item.added"),
],
Annotated[
OpenResponsesStreamEventResponseOutputItemDone,
Tag("response.output_item.done"),
],
Annotated[
OpenResponsesStreamEventResponseContentPartAdded,
Tag("response.content_part.added"),
],
Annotated[
OpenResponsesStreamEventResponseContentPartDone,
Tag("response.content_part.done"),
],
Annotated[
OpenResponsesStreamEventResponseOutputTextDelta,
Tag("response.output_text.delta"),
],
Annotated[
OpenResponsesStreamEventResponseOutputTextDone,
Tag("response.output_text.done"),
],
Annotated[
OpenResponsesStreamEventResponseRefusalDelta, Tag("response.refusal.delta")
],
Annotated[
OpenResponsesStreamEventResponseRefusalDone, Tag("response.refusal.done")
],
Annotated[
OpenResponsesStreamEventResponseOutputTextAnnotationAdded,
Tag("response.output_text.annotation.added"),
],
Annotated[
OpenResponsesStreamEventResponseFunctionCallArgumentsDelta,
Tag("response.function_call_arguments.delta"),
],
Annotated[
OpenResponsesStreamEventResponseFunctionCallArgumentsDone,
Tag("response.function_call_arguments.done"),
],
Annotated[
OpenResponsesReasoningDeltaEvent, Tag("response.reasoning_text.delta")
],
Annotated[OpenResponsesReasoningDoneEvent, Tag("response.reasoning_text.done")],
Annotated[
OpenResponsesReasoningSummaryPartAddedEvent,
Tag("response.reasoning_summary_part.added"),
],
Annotated[
OpenResponsesStreamEventResponseReasoningSummaryPartDone,
Tag("response.reasoning_summary_part.done"),
],
Annotated[
OpenResponsesReasoningSummaryTextDeltaEvent,
Tag("response.reasoning_summary_text.delta"),
],
Annotated[
OpenResponsesReasoningSummaryTextDoneEvent,
Tag("response.reasoning_summary_text.done"),
],
Annotated[
OpenResponsesImageGenCallInProgress,
Tag("response.image_generation_call.in_progress"),
],
Annotated[
OpenResponsesImageGenCallGenerating,
Tag("response.image_generation_call.generating"),
],
Annotated[
OpenResponsesImageGenCallPartialImage,
Tag("response.image_generation_call.partial_image"),
],
Annotated[
OpenResponsesImageGenCallCompleted,
Tag("response.image_generation_call.completed"),
],
OpenResponsesStreamEventResponseCreated,
OpenResponsesStreamEventResponseInProgress,
OpenResponsesStreamEventResponseCompleted,
OpenResponsesStreamEventResponseIncomplete,
OpenResponsesStreamEventResponseFailed,
OpenResponsesStreamEventResponseOutputItemAdded,
OpenResponsesStreamEventResponseOutputItemDone,
OpenResponsesImageGenCallCompleted,
OpenResponsesImageGenCallGenerating,
OpenResponsesImageGenCallInProgress,
OpenResponsesErrorEvent,
OpenResponsesStreamEventResponseFunctionCallArgumentsDelta,
OpenResponsesStreamEventResponseRefusalDelta,
OpenResponsesReasoningSummaryPartAddedEvent,
OpenResponsesStreamEventResponseContentPartAdded,
OpenResponsesImageGenCallPartialImage,
OpenResponsesStreamEventResponseFunctionCallArgumentsDone,
OpenResponsesReasoningDeltaEvent,
OpenResponsesReasoningDoneEvent,
OpenResponsesStreamEventResponseRefusalDone,
OpenResponsesStreamEventResponseReasoningSummaryPartDone,
OpenResponsesReasoningSummaryTextDeltaEvent,
OpenResponsesReasoningSummaryTextDoneEvent,
OpenResponsesStreamEventResponseContentPartDone,
OpenResponsesStreamEventResponseOutputTextDelta,
OpenResponsesStreamEventResponseOutputTextDone,
OpenResponsesStreamEventResponseOutputTextAnnotationAdded,
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
)
r"""Union of all possible event types emitted during response streaming"""
+4 -10
View File
@@ -7,10 +7,8 @@ from .openairesponsesrefusalcontent import (
)
from .responseoutputtext import ResponseOutputText, ResponseOutputTextTypedDict
from openrouter.types import BaseModel
from openrouter.utils import get_discriminator
from pydantic import Discriminator, Tag
from typing import List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
from typing_extensions import NotRequired, TypeAliasType, TypedDict
OutputMessageRole = Literal["assistant",]
@@ -54,13 +52,9 @@ OutputMessageContentTypedDict = TypeAliasType(
)
OutputMessageContent = Annotated[
Union[
Annotated[ResponseOutputText, Tag("output_text")],
Annotated[OpenAIResponsesRefusalContent, Tag("refusal")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
OutputMessageContent = TypeAliasType(
"OutputMessageContent", Union[OpenAIResponsesRefusalContent, ResponseOutputText]
)
class OutputMessageTypedDict(TypedDict):
+1 -5
View File
@@ -11,14 +11,12 @@ ProviderName = Union[
"AionLabs",
"Alibaba",
"Amazon Bedrock",
"Amazon Nova",
"Anthropic",
"Arcee AI",
"Arcee",
"AtlasCloud",
"Avian",
"Azure",
"BaseTen",
"BytePlus",
"Black Forest Labs",
"Cerebras",
"Chutes",
@@ -33,7 +31,6 @@ ProviderName = Union[
"Fireworks",
"Friendli",
"GMICloud",
"GoPomelo",
"Google",
"Google AI Studio",
"Groq",
@@ -64,7 +61,6 @@ ProviderName = Union[
"SambaNova",
"SiliconFlow",
"Stealth",
"StreamLake",
"Switchpoint",
"Targon",
"Together",
@@ -10,10 +10,8 @@ from .responsesformattextjsonschemaconfig import (
ResponsesFormatTextJSONSchemaConfig,
ResponsesFormatTextJSONSchemaConfigTypedDict,
)
from openrouter.utils import get_discriminator
from pydantic import Discriminator, Tag
from typing import Union
from typing_extensions import Annotated, TypeAliasType
from typing_extensions import TypeAliasType
ResponseFormatTextConfigTypedDict = TypeAliasType(
@@ -27,12 +25,12 @@ ResponseFormatTextConfigTypedDict = TypeAliasType(
r"""Text response format configuration"""
ResponseFormatTextConfig = Annotated[
ResponseFormatTextConfig = TypeAliasType(
"ResponseFormatTextConfig",
Union[
Annotated[ResponsesFormatText, Tag("text")],
Annotated[ResponsesFormatJSONObject, Tag("json_object")],
Annotated[ResponsesFormatTextJSONSchemaConfig, Tag("json_schema")],
ResponsesFormatText,
ResponsesFormatJSONObject,
ResponsesFormatTextJSONSchemaConfig,
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
)
r"""Text response format configuration"""
@@ -25,10 +25,8 @@ from .responseswebsearchcalloutput import (
ResponsesWebSearchCallOutput,
ResponsesWebSearchCallOutputTypedDict,
)
from openrouter.utils import get_discriminator
from pydantic import Discriminator, Tag
from typing import Union
from typing_extensions import Annotated, TypeAliasType
from typing_extensions import TypeAliasType
ResponsesOutputItemTypedDict = TypeAliasType(
@@ -45,15 +43,15 @@ ResponsesOutputItemTypedDict = TypeAliasType(
r"""An output item from the response"""
ResponsesOutputItem = Annotated[
ResponsesOutputItem = TypeAliasType(
"ResponsesOutputItem",
Union[
Annotated[ResponsesOutputMessage, Tag("message")],
Annotated[ResponsesOutputItemReasoning, Tag("reasoning")],
Annotated[ResponsesOutputItemFunctionCall, Tag("function_call")],
Annotated[ResponsesWebSearchCallOutput, Tag("web_search_call")],
Annotated[ResponsesOutputItemFileSearchCall, Tag("file_search_call")],
Annotated[ResponsesImageGenerationCall, Tag("image_generation_call")],
ResponsesWebSearchCallOutput,
ResponsesOutputItemFileSearchCall,
ResponsesImageGenerationCall,
ResponsesOutputMessage,
ResponsesOutputItemReasoning,
ResponsesOutputItemFunctionCall,
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
)
r"""An output item from the response"""
@@ -7,10 +7,8 @@ from .openairesponsesrefusalcontent import (
)
from .responseoutputtext import ResponseOutputText, ResponseOutputTextTypedDict
from openrouter.types import BaseModel
from openrouter.utils import get_discriminator
from pydantic import Discriminator, Tag
from typing import List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
from typing_extensions import NotRequired, TypeAliasType, TypedDict
ResponsesOutputMessageRole = Literal["assistant",]
@@ -54,13 +52,10 @@ ResponsesOutputMessageContentTypedDict = TypeAliasType(
)
ResponsesOutputMessageContent = Annotated[
Union[
Annotated[ResponseOutputText, Tag("output_text")],
Annotated[OpenAIResponsesRefusalContent, Tag("refusal")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
ResponsesOutputMessageContent = TypeAliasType(
"ResponsesOutputMessageContent",
Union[OpenAIResponsesRefusalContent, ResponseOutputText],
)
class ResponsesOutputMessageTypedDict(TypedDict):
+13
View File
@@ -0,0 +1,13 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from typing_extensions import TypedDict
class VideoURLTypedDict(TypedDict):
url: str
class VideoURL(BaseModel):
url: str
-4
View File
@@ -51,7 +51,6 @@ class Credits(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -148,7 +147,6 @@ class Credits(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -268,7 +266,6 @@ class Credits(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", components.CreateChargeRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -393,7 +390,6 @@ class Credits(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", components.CreateChargeRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
+22 -8
View File
@@ -1,6 +1,7 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from enum import Enum
from openrouter import components, errors, operations, utils
from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
@@ -9,6 +10,11 @@ from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Mapping, Optional, Union
class GenerateAcceptEnum(str, Enum):
APPLICATION_JSON = "application/json"
TEXT_EVENT_STREAM = "text/event-stream"
class Embeddings(BaseSDK):
r"""Text embedding endpoints"""
@@ -30,6 +36,7 @@ class Embeddings(BaseSDK):
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
accept_header_override: Optional[GenerateAcceptEnum] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.CreateEmbeddingsResponse:
r"""Submit an embedding request
@@ -46,6 +53,7 @@ class Embeddings(BaseSDK):
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
@@ -80,13 +88,14 @@ class Embeddings(BaseSDK):
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
accept_header_value=accept_header_override.value
if accept_header_override is not None
else "application/json;q=1, text/event-stream;q=0",
http_headers=http_headers,
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", operations.CreateEmbeddingsRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -129,8 +138,10 @@ class Embeddings(BaseSDK):
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
operations.CreateEmbeddingsResponse, http_res
operations.CreateEmbeddingsResponseBody, http_res
)
if utils.match_response(http_res, "200", "text/event-stream"):
return http_res.text
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
@@ -212,6 +223,7 @@ class Embeddings(BaseSDK):
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
accept_header_override: Optional[GenerateAcceptEnum] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.CreateEmbeddingsResponse:
r"""Submit an embedding request
@@ -228,6 +240,7 @@ class Embeddings(BaseSDK):
:param retries: Override the default retry configuration for this method
:param server_url: Override the default server URL for this method
:param timeout_ms: Override the default request timeout configuration for this method in milliseconds
:param accept_header_override: Override the default accept header for this method
:param http_headers: Additional headers to set or replace on requests.
"""
base_url = None
@@ -262,13 +275,14 @@ class Embeddings(BaseSDK):
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
accept_header_value=accept_header_override.value
if accept_header_override is not None
else "application/json;q=1, text/event-stream;q=0",
http_headers=http_headers,
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", operations.CreateEmbeddingsRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -311,8 +325,10 @@ class Embeddings(BaseSDK):
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
operations.CreateEmbeddingsResponse, http_res
operations.CreateEmbeddingsResponseBody, http_res
)
if utils.match_response(http_res, "200", "text/event-stream"):
return http_res.text
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
@@ -415,7 +431,6 @@ class Embeddings(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -507,7 +522,6 @@ class Embeddings(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
-4
View File
@@ -59,7 +59,6 @@ class Endpoints(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -159,7 +158,6 @@ class Endpoints(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -249,7 +247,6 @@ class Endpoints(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -336,7 +333,6 @@ class Endpoints(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
-2
View File
@@ -56,7 +56,6 @@ class Generations(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -194,7 +193,6 @@ class Generations(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
-3
View File
@@ -1,3 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
# package
@@ -1,54 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from typing import TYPE_CHECKING
from importlib import import_module
import builtins
import sys
if TYPE_CHECKING:
from .globals import Globals, GlobalsTypedDict
__all__ = ["Globals", "GlobalsTypedDict"]
_dynamic_imports: dict[str, str] = {
"Globals": ".globals",
"GlobalsTypedDict": ".globals",
}
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:
module_name = _dynamic_imports.get(attr_name)
if module_name is None:
raise AttributeError(
f"No {attr_name} found in _dynamic_imports for module name -> {__name__} "
)
try:
module = dynamic_import(module_name)
result = getattr(module, attr_name)
return result
except ImportError as e:
raise ImportError(
f"Failed to import {attr_name} from {module_name}: {e}"
) from e
except AttributeError as e:
raise AttributeError(
f"Failed to get {attr_name} from {module_name}: {e}"
) from e
def __dir__():
lazy_attrs = builtins.list(_dynamic_imports.keys())
return builtins.sorted(lazy_attrs)
-41
View File
@@ -1,41 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from openrouter.utils import FieldMetadata, HeaderMetadata
import pydantic
from typing import Optional
from typing_extensions import Annotated, NotRequired, TypedDict
class GlobalsTypedDict(TypedDict):
http_referer: NotRequired[str]
r"""The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
"""
x_title: NotRequired[str]
r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard.
"""
class Globals(BaseModel):
http_referer: Annotated[
Optional[str],
pydantic.Field(alias="HTTP-Referer"),
FieldMetadata(header=HeaderMetadata(style="simple", explode=False)),
] = None
r"""The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
"""
x_title: Annotated[
Optional[str],
pydantic.Field(alias="X-Title"),
FieldMetadata(header=HeaderMetadata(style="simple", explode=False)),
] = None
r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard.
"""
-6
View File
@@ -49,7 +49,6 @@ class Models(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -134,7 +133,6 @@ class Models(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -229,7 +227,6 @@ class Models(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -329,7 +326,6 @@ class Models(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -426,7 +422,6 @@ class Models(BaseSDK):
security=utils.get_pydantic_model(
security, operations.ListModelsUserSecurity
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -521,7 +516,6 @@ class Models(BaseSDK):
security=utils.get_pydantic_model(
security, operations.ListModelsUserSecurity
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
-4
View File
@@ -74,7 +74,6 @@ class OAuth(BaseSDK):
"json",
operations.ExchangeAuthCodeForAPIKeyRequest,
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -195,7 +194,6 @@ class OAuth(BaseSDK):
"json",
operations.ExchangeAuthCodeForAPIKeyRequest,
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -318,7 +316,6 @@ class OAuth(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", operations.CreateAuthKeysCodeRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -441,7 +438,6 @@ class OAuth(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", operations.CreateAuthKeysCodeRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
+7 -10
View File
@@ -45,6 +45,8 @@ if TYPE_CHECKING:
CreateEmbeddingsRequest,
CreateEmbeddingsRequestTypedDict,
CreateEmbeddingsResponse,
CreateEmbeddingsResponseBody,
CreateEmbeddingsResponseBodyTypedDict,
CreateEmbeddingsResponseTypedDict,
Embedding,
EmbeddingTypedDict,
@@ -98,12 +100,7 @@ if TYPE_CHECKING:
ExchangeAuthCodeForAPIKeyResponse,
ExchangeAuthCodeForAPIKeyResponseTypedDict,
)
from .getcredits import (
GetCreditsData,
GetCreditsDataTypedDict,
GetCreditsResponse,
GetCreditsResponseTypedDict,
)
from .getcredits import GetCreditsResponse, GetCreditsResponseTypedDict
from .getcurrentkey import (
GetCurrentKeyData,
GetCurrentKeyDataTypedDict,
@@ -219,6 +216,8 @@ __all__ = [
"CreateEmbeddingsRequest",
"CreateEmbeddingsRequestTypedDict",
"CreateEmbeddingsResponse",
"CreateEmbeddingsResponseBody",
"CreateEmbeddingsResponseBodyTypedDict",
"CreateEmbeddingsResponseTypedDict",
"CreateKeysData",
"CreateKeysDataTypedDict",
@@ -243,8 +242,6 @@ __all__ = [
"ExchangeAuthCodeForAPIKeyRequestTypedDict",
"ExchangeAuthCodeForAPIKeyResponse",
"ExchangeAuthCodeForAPIKeyResponseTypedDict",
"GetCreditsData",
"GetCreditsDataTypedDict",
"GetCreditsResponse",
"GetCreditsResponseTypedDict",
"GetCurrentKeyData",
@@ -373,6 +370,8 @@ _dynamic_imports: dict[str, str] = {
"CreateEmbeddingsRequest": ".createembeddings",
"CreateEmbeddingsRequestTypedDict": ".createembeddings",
"CreateEmbeddingsResponse": ".createembeddings",
"CreateEmbeddingsResponseBody": ".createembeddings",
"CreateEmbeddingsResponseBodyTypedDict": ".createembeddings",
"CreateEmbeddingsResponseTypedDict": ".createembeddings",
"Embedding": ".createembeddings",
"EmbeddingTypedDict": ".createembeddings",
@@ -417,8 +416,6 @@ _dynamic_imports: dict[str, str] = {
"ExchangeAuthCodeForAPIKeyRequestTypedDict": ".exchangeauthcodeforapikey",
"ExchangeAuthCodeForAPIKeyResponse": ".exchangeauthcodeforapikey",
"ExchangeAuthCodeForAPIKeyResponseTypedDict": ".exchangeauthcodeforapikey",
"GetCreditsData": ".getcredits",
"GetCreditsDataTypedDict": ".getcredits",
"GetCreditsResponse": ".getcredits",
"GetCreditsResponseTypedDict": ".getcredits",
"GetCurrentKeyData": ".getcurrentkey",
+16 -11
View File
@@ -15,8 +15,8 @@ from openrouter.types import (
UNSET_SENTINEL,
UnrecognizedStr,
)
from openrouter.utils import get_discriminator, validate_open_enum
from pydantic import Discriminator, Tag, model_serializer
from openrouter.utils import validate_open_enum
from pydantic import model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Any, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
@@ -63,13 +63,7 @@ ContentTypedDict = TypeAliasType(
)
Content = Annotated[
Union[
Annotated[ContentText, Tag("text")],
Annotated[ContentImageURL, Tag("image_url")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
Content = TypeAliasType("Content", Union[ContentText, ContentImageURL])
class InputTypedDict(TypedDict):
@@ -395,7 +389,7 @@ class Usage(BaseModel):
cost: Optional[float] = None
class CreateEmbeddingsResponseTypedDict(TypedDict):
class CreateEmbeddingsResponseBodyTypedDict(TypedDict):
r"""Embedding response"""
object: Object
@@ -405,7 +399,7 @@ class CreateEmbeddingsResponseTypedDict(TypedDict):
usage: NotRequired[UsageTypedDict]
class CreateEmbeddingsResponse(BaseModel):
class CreateEmbeddingsResponseBody(BaseModel):
r"""Embedding response"""
object: Object
@@ -417,3 +411,14 @@ class CreateEmbeddingsResponse(BaseModel):
id: Optional[str] = None
usage: Optional[Usage] = None
CreateEmbeddingsResponseTypedDict = TypeAliasType(
"CreateEmbeddingsResponseTypedDict",
Union[CreateEmbeddingsResponseBodyTypedDict, str],
)
CreateEmbeddingsResponse = TypeAliasType(
"CreateEmbeddingsResponse", Union[CreateEmbeddingsResponseBody, str]
)
-19
View File
@@ -5,28 +5,9 @@ from openrouter.types import BaseModel
from typing_extensions import TypedDict
class GetCreditsDataTypedDict(TypedDict):
total_credits: float
r"""Total credits purchased"""
total_usage: float
r"""Total credits used"""
class GetCreditsData(BaseModel):
total_credits: float
r"""Total credits purchased"""
total_usage: float
r"""Total credits used"""
class GetCreditsResponseTypedDict(TypedDict):
r"""Total credits purchased and used"""
data: GetCreditsDataTypedDict
class GetCreditsResponse(BaseModel):
r"""Total credits purchased and used"""
data: GetCreditsData
+1 -5
View File
@@ -38,14 +38,12 @@ GetParametersProvider = Union[
"AionLabs",
"Alibaba",
"Amazon Bedrock",
"Amazon Nova",
"Anthropic",
"Arcee AI",
"Arcee",
"AtlasCloud",
"Avian",
"Azure",
"BaseTen",
"BytePlus",
"Black Forest Labs",
"Cerebras",
"Chutes",
@@ -60,7 +58,6 @@ GetParametersProvider = Union[
"Fireworks",
"Friendli",
"GMICloud",
"GoPomelo",
"Google",
"Google AI Studio",
"Groq",
@@ -91,7 +88,6 @@ GetParametersProvider = Union[
"SambaNova",
"SiliconFlow",
"Stealth",
"StreamLake",
"Switchpoint",
"Targon",
"Together",
-2
View File
@@ -68,7 +68,6 @@ class Parameters(BaseSDK):
security=utils.get_pydantic_model(
security, operations.GetParametersSecurity
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -180,7 +179,6 @@ class Parameters(BaseSDK):
security=utils.get_pydantic_model(
security, operations.GetParametersSecurity
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
-2
View File
@@ -49,7 +49,6 @@ class Providers(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -134,7 +133,6 @@ class Providers(BaseSDK):
accept_header_value="application/json",
http_headers=http_headers,
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
+20 -8
View File
@@ -69,7 +69,8 @@ class Responses(BaseSDK):
include: OptionalNullable[List[components.OpenAIResponsesIncludable]] = UNSET,
background: OptionalNullable[bool] = UNSET,
safety_identifier: OptionalNullable[str] = UNSET,
service_tier: Optional[components.ServiceTier] = "auto",
store: OptionalNullable[bool] = UNSET,
service_tier: OptionalNullable[components.ServiceTier] = UNSET,
truncation: OptionalNullable[components.Truncation] = UNSET,
stream: Union[Literal[False], None] = None,
provider: OptionalNullable[
@@ -108,6 +109,7 @@ class Responses(BaseSDK):
:param include:
:param background:
:param safety_identifier:
:param store:
:param service_tier:
:param truncation:
:param stream:
@@ -172,7 +174,8 @@ class Responses(BaseSDK):
include: OptionalNullable[List[components.OpenAIResponsesIncludable]] = UNSET,
background: OptionalNullable[bool] = UNSET,
safety_identifier: OptionalNullable[str] = UNSET,
service_tier: Optional[components.ServiceTier] = "auto",
store: OptionalNullable[bool] = UNSET,
service_tier: OptionalNullable[components.ServiceTier] = UNSET,
truncation: OptionalNullable[components.Truncation] = UNSET,
stream: Literal[True],
provider: OptionalNullable[
@@ -211,6 +214,7 @@ class Responses(BaseSDK):
:param include:
:param background:
:param safety_identifier:
:param store:
:param service_tier:
:param truncation:
:param stream:
@@ -274,7 +278,8 @@ class Responses(BaseSDK):
include: OptionalNullable[List[components.OpenAIResponsesIncludable]] = UNSET,
background: OptionalNullable[bool] = UNSET,
safety_identifier: OptionalNullable[str] = UNSET,
service_tier: Optional[components.ServiceTier] = "auto",
store: OptionalNullable[bool] = UNSET,
service_tier: OptionalNullable[components.ServiceTier] = UNSET,
truncation: OptionalNullable[components.Truncation] = UNSET,
stream: Optional[bool] = False,
provider: OptionalNullable[
@@ -313,6 +318,7 @@ class Responses(BaseSDK):
:param include:
:param background:
:param safety_identifier:
:param store:
:param service_tier:
:param truncation:
:param stream:
@@ -368,6 +374,7 @@ class Responses(BaseSDK):
include=include,
background=background,
safety_identifier=safety_identifier,
store=store,
service_tier=service_tier,
truncation=truncation,
stream=stream,
@@ -396,7 +403,6 @@ class Responses(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", components.OpenResponsesRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
@@ -620,7 +626,8 @@ class Responses(BaseSDK):
include: OptionalNullable[List[components.OpenAIResponsesIncludable]] = UNSET,
background: OptionalNullable[bool] = UNSET,
safety_identifier: OptionalNullable[str] = UNSET,
service_tier: Optional[components.ServiceTier] = "auto",
store: OptionalNullable[bool] = UNSET,
service_tier: OptionalNullable[components.ServiceTier] = UNSET,
truncation: OptionalNullable[components.Truncation] = UNSET,
stream: Union[Literal[False], None] = None,
provider: OptionalNullable[
@@ -659,6 +666,7 @@ class Responses(BaseSDK):
:param include:
:param background:
:param safety_identifier:
:param store:
:param service_tier:
:param truncation:
:param stream:
@@ -723,7 +731,8 @@ class Responses(BaseSDK):
include: OptionalNullable[List[components.OpenAIResponsesIncludable]] = UNSET,
background: OptionalNullable[bool] = UNSET,
safety_identifier: OptionalNullable[str] = UNSET,
service_tier: Optional[components.ServiceTier] = "auto",
store: OptionalNullable[bool] = UNSET,
service_tier: OptionalNullable[components.ServiceTier] = UNSET,
truncation: OptionalNullable[components.Truncation] = UNSET,
stream: Literal[True],
provider: OptionalNullable[
@@ -762,6 +771,7 @@ class Responses(BaseSDK):
:param include:
:param background:
:param safety_identifier:
:param store:
:param service_tier:
:param truncation:
:param stream:
@@ -825,7 +835,8 @@ class Responses(BaseSDK):
include: OptionalNullable[List[components.OpenAIResponsesIncludable]] = UNSET,
background: OptionalNullable[bool] = UNSET,
safety_identifier: OptionalNullable[str] = UNSET,
service_tier: Optional[components.ServiceTier] = "auto",
store: OptionalNullable[bool] = UNSET,
service_tier: OptionalNullable[components.ServiceTier] = UNSET,
truncation: OptionalNullable[components.Truncation] = UNSET,
stream: Optional[bool] = False,
provider: OptionalNullable[
@@ -864,6 +875,7 @@ class Responses(BaseSDK):
:param include:
:param background:
:param safety_identifier:
:param store:
:param service_tier:
:param truncation:
:param stream:
@@ -919,6 +931,7 @@ class Responses(BaseSDK):
include=include,
background=background,
safety_identifier=safety_identifier,
store=store,
service_tier=service_tier,
truncation=truncation,
stream=stream,
@@ -947,7 +960,6 @@ class Responses(BaseSDK):
get_serialized_body=lambda: utils.serialize_request_body(
request, False, False, "json", components.OpenResponsesRequest
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
-13
View File
@@ -9,7 +9,6 @@ import httpx
import importlib
from openrouter import components, utils
from openrouter._hooks import SDKHooks
from openrouter.models import internal
from openrouter.types import OptionalNullable, UNSET
import sys
from typing import Any, Callable, Dict, Optional, TYPE_CHECKING, Union, cast
@@ -78,8 +77,6 @@ class OpenRouter(BaseSDK):
def __init__(
self,
api_key: Optional[Union[Optional[str], Callable[[], Optional[str]]]] = None,
http_referer: Optional[str] = None,
x_title: Optional[str] = None,
server: Optional[str] = None,
server_url: Optional[str] = None,
url_params: Optional[Dict[str, str]] = None,
@@ -92,8 +89,6 @@ class OpenRouter(BaseSDK):
r"""Instantiates the SDK configuring it with the provided parameters.
:param api_key: The api_key required for authentication
:param http_referer: Configures the http_referer parameter for all supported operations
:param x_title: Configures the x_title parameter for all supported operations
:param server: The server by name to use for all methods
:param server_url: The server URL to use for all methods
:param url_params: Parameters to optionally template the server URL with
@@ -134,13 +129,6 @@ class OpenRouter(BaseSDK):
if url_params is not None:
server_url = utils.template_url(server_url, url_params)
_globals = internal.Globals(
http_referer=utils.get_global_from_env(
http_referer, "OPENROUTER_HTTP_REFERER", str
),
x_title=utils.get_global_from_env(x_title, "OPENROUTER_X_TITLE", str),
)
BaseSDK.__init__(
self,
SDKConfiguration(
@@ -148,7 +136,6 @@ class OpenRouter(BaseSDK):
client_supplied=client_supplied,
async_client=async_client,
async_client_supplied=async_client_supplied,
globals=_globals,
security=security,
server_url=server_url,
server=server,
-2
View File
@@ -10,7 +10,6 @@ from .httpclient import AsyncHttpClient, HttpClient
from .utils import Logger, RetryConfig, remove_suffix
from dataclasses import dataclass
from openrouter import components
from openrouter.models import internal
from openrouter.types import OptionalNullable, UNSET
from pydantic import Field
from typing import Callable, Dict, Optional, Tuple, Union
@@ -31,7 +30,6 @@ class SDKConfiguration:
async_client: Union[AsyncHttpClient, None]
async_client_supplied: bool
debug_logger: Logger
globals: internal.Globals
security: Optional[
Union[components.Security, Callable[[], components.Security]]
] = None
+10 -21
View File
@@ -142,21 +142,16 @@ def serialize_multipart_form(
if field_metadata.file:
if isinstance(val, List):
# Handle array of files
array_field_name = f_name + "[]"
for file_obj in val:
if not _is_set(file_obj):
continue
file_name, content, content_type = _extract_file_properties(
file_obj
)
file_name, content, content_type = _extract_file_properties(file_obj)
if content_type is not None:
files.append(
(array_field_name, (file_name, content, content_type))
)
files.append((f_name + "[]", (file_name, content, content_type)))
else:
files.append((array_field_name, (file_name, content)))
files.append((f_name + "[]", (file_name, content)))
else:
# Handle single file
file_name, content, content_type = _extract_file_properties(val)
@@ -166,16 +161,11 @@ def serialize_multipart_form(
else:
files.append((f_name, (file_name, content)))
elif field_metadata.json:
files.append(
(
f_name,
(
None,
marshal_json(val, request_field_types[name]),
"application/json",
),
)
)
files.append((f_name, (
None,
marshal_json(val, request_field_types[name]),
"application/json",
)))
else:
if isinstance(val, List):
values = []
@@ -185,8 +175,7 @@ def serialize_multipart_form(
continue
values.append(_val_to_string(value))
array_field_name = f_name + "[]"
form[array_field_name] = values
form[f_name + "[]"] = values
else:
form[f_name] = _val_to_string(val)
return media_type, form, files
+2 -14
View File
@@ -27,13 +27,12 @@ from .forms import _populate_form
def get_query_params(
query_params: Any,
gbls: Optional[Any] = None,
allow_empty_value: Optional[List[str]] = None,
) -> Dict[str, List[str]]:
params: Dict[str, List[str]] = {}
globals_already_populated = _populate_query_params(query_params, gbls, params, [], allow_empty_value)
globals_already_populated = _populate_query_params(query_params, gbls, params, [])
if _is_set(gbls):
_populate_query_params(gbls, None, params, globals_already_populated, allow_empty_value)
_populate_query_params(gbls, None, params, globals_already_populated)
return params
@@ -43,7 +42,6 @@ def _populate_query_params(
gbls: Any,
query_param_values: Dict[str, List[str]],
skip_fields: List[str],
allow_empty_value: Optional[List[str]] = None,
) -> List[str]:
globals_already_populated: List[str] = []
@@ -71,16 +69,6 @@ def _populate_query_params(
globals_already_populated.append(name)
f_name = field.alias if field.alias is not None else name
allow_empty_set = set(allow_empty_value or [])
should_include_empty = f_name in allow_empty_set and (
value is None or value == [] or value == ""
)
if should_include_empty:
query_param_values[f_name] = [""]
continue
serialization = metadata.serialization
if serialization is not None:
serialized_parms = _get_serialized_params(
+5 -69
View File
@@ -3,9 +3,7 @@
import asyncio
import random
import time
from datetime import datetime
from email.utils import parsedate_to_datetime
from typing import List, Optional
from typing import List
import httpx
@@ -53,11 +51,9 @@ class Retries:
class TemporaryError(Exception):
response: httpx.Response
retry_after: Optional[int]
def __init__(self, response: httpx.Response):
self.response = response
self.retry_after = _parse_retry_after_header(response)
class PermanentError(Exception):
@@ -67,62 +63,6 @@ class PermanentError(Exception):
self.inner = inner
def _parse_retry_after_header(response: httpx.Response) -> Optional[int]:
"""Parse Retry-After header from response.
Returns:
Retry interval in milliseconds, or None if header is missing or invalid.
"""
retry_after_header = response.headers.get("retry-after")
if not retry_after_header:
return None
try:
seconds = float(retry_after_header)
return round(seconds * 1000)
except ValueError:
pass
try:
retry_date = parsedate_to_datetime(retry_after_header)
delta = (retry_date - datetime.now(retry_date.tzinfo)).total_seconds()
return round(max(0, delta) * 1000)
except (ValueError, TypeError):
pass
return None
def _get_sleep_interval(
exception: Exception,
initial_interval: int,
max_interval: int,
exponent: float,
retries: int,
) -> float:
"""Get sleep interval for retry with exponential backoff.
Args:
exception: The exception that triggered the retry.
initial_interval: Initial retry interval in milliseconds.
max_interval: Maximum retry interval in milliseconds.
exponent: Base for exponential backoff calculation.
retries: Current retry attempt count.
Returns:
Sleep interval in seconds.
"""
if (
isinstance(exception, TemporaryError)
and exception.retry_after is not None
and exception.retry_after > 0
):
return exception.retry_after / 1000
sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1)
return min(sleep, max_interval / 1000)
def retry(func, retries: Retries):
if retries.config.strategy == "backoff":
@@ -243,10 +183,8 @@ def retry_with_backoff(
return exception.response
raise
sleep = _get_sleep_interval(
exception, initial_interval, max_interval, exponent, retries
)
sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1)
sleep = min(sleep, max_interval / 1000)
time.sleep(sleep)
retries += 1
@@ -273,9 +211,7 @@ async def retry_with_backoff_async(
return exception.response
raise
sleep = _get_sleep_interval(
exception, initial_interval, max_interval, exponent, retries
)
sleep = (initial_interval / 1000) * exponent**retries + random.uniform(0, 1)
sleep = min(sleep, max_interval / 1000)
await asyncio.sleep(sleep)
retries += 1
Generated
+1 -1
View File
@@ -211,7 +211,7 @@ wheels = [
[[package]]
name = "openrouter"
version = "0.1.0"
version = "0.0.16"
source = { editable = "." }
dependencies = [
{ name = "httpcore" },