Compare commits

..
Author SHA1 Message Date
speakeasy-github[bot]andspeakeasy-bot c83dcf1f47 empty commit to trigger [run-tests] workflow 2026-04-14 00:40:55 +00:00
speakeasybot 0a9e60481a ## Python SDK Changes:
* `open_router.api_keys.list()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response.data.[]` **Changed** **Breaking** ⚠️
* `open_router.guardrails.get()`:  `response.data` **Changed** **Breaking** ⚠️
* `open_router.o_auth.create_auth_code()`:  `response.data.app_id` **Changed** **Breaking** ⚠️
* `open_router.guardrails.bulk_unassign_members()`:  `response.unassigned_count` **Changed** **Breaking** ⚠️
* `open_router.guardrails.bulk_unassign_keys()`:  `response.unassigned_count` **Changed** **Breaking** ⚠️
* `open_router.guardrails.bulk_assign_members()`:  `response.assigned_count` **Changed** **Breaking** ⚠️
* `open_router.guardrails.list_guardrail_member_assignments()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response.total_count` **Changed** **Breaking** ⚠️
* `open_router.beta.responses.send()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response` **Changed** **Breaking** ⚠️
* `open_router.analytics.get_user_activity()`: 
  *  `request` **Changed**
  *  `response.data.[]` **Changed** **Breaking** ⚠️
  *  `error.status[404]` **Added**
* `open_router.chat.send()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response` **Changed** **Breaking** ⚠️
* `open_router.embeddings.generate()`: 
  *  `request.provider` **Changed** **Breaking** ⚠️
  *  `response` **Changed** **Breaking** ⚠️
* `open_router.embeddings.list_models()`:  `response.data.[]` **Changed** **Breaking** ⚠️
* `open_router.generations.get_generation()`:  `response.data` **Changed** **Breaking** ⚠️
* `open_router.models.count()`:  `response.data.count` **Changed** **Breaking** ⚠️
* `open_router.models.list()`:  `response.data.[]` **Changed** **Breaking** ⚠️
* `open_router.models.list_for_user()`:  `response.data.[]` **Changed** **Breaking** ⚠️
* `open_router.endpoints.list_zdr_endpoints()`:  `response.data.[]` **Changed** **Breaking** ⚠️
* `open_router.guardrails.bulk_assign_keys()`:  `response.assigned_count` **Changed** **Breaking** ⚠️
* `open_router.guardrails.list_member_assignments()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response.total_count` **Changed** **Breaking** ⚠️
* `open_router.api_keys.create()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response.data` **Changed** **Breaking** ⚠️
* `open_router.api_keys.update()`: 
  *  `request.limit` **Changed** **Breaking** ⚠️
  *  `response.data` **Changed** **Breaking** ⚠️
* `open_router.api_keys.get()`:  `response.data` **Changed** **Breaking** ⚠️
* `open_router.api_keys.get_current_key_metadata()`:  `response.data` **Changed** **Breaking** ⚠️
* `open_router.guardrails.list()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response` **Changed** **Breaking** ⚠️
* `open_router.guardrails.create()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response.data` **Changed** **Breaking** ⚠️
* `open_router.endpoints.list()`:  `response.data` **Changed** **Breaking** ⚠️
* `open_router.guardrails.update()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response.data` **Changed** **Breaking** ⚠️
* `open_router.guardrails.list_key_assignments()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response.total_count` **Changed** **Breaking** ⚠️
* `open_router.guardrails.list_guardrail_key_assignments()`: 
  *  `request` **Changed** **Breaking** ⚠️
  *  `response.total_count` **Changed** **Breaking** ⚠️
* `open_router.organization.list_members()`: **Added**
* `open_router.rerank.rerank()`: **Added**
* `open_router.credits.create_coinbase_charge()`: **Deleted** **Breaking** ⚠️
* `open_router.video_generation.list_videos_models()`: **Added**
* `open_router.video_generation.get_video_content()`: **Added**
* `open_router.video_generation.get_generation()`: **Added**
* `open_router.video_generation.generate()`: **Added**
2026-04-14 00:40:46 +00:00
468 changed files with 3876 additions and 74611 deletions
@@ -1,86 +0,0 @@
name: Auto-merge Speakeasy PR
# Speakeasy mode:pr opens PRs (speakeasy-sdk-regen-*) and labels them
# patch/minor/major. Merge automatically so sdk_publish.yaml can run.
on:
pull_request:
types: [labeled]
permissions:
contents: write
pull-requests: write
concurrency:
group: auto-merge-speakeasy
cancel-in-progress: false
jobs:
auto-merge:
if: |
github.event.sender.login == 'github-actions[bot]' &&
github.event.pull_request.user.login == 'github-actions[bot]' &&
startsWith(github.event.pull_request.head.ref, 'speakeasy-sdk-regen-') &&
contains(github.event.pull_request.title, '🐝 Update SDK') &&
contains(fromJSON('["patch", "minor", "major"]'), github.event.label.name)
runs-on: ubuntu-latest
steps:
- name: Close superseded Speakeasy PRs
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
CURRENT_PR="${{ github.event.pull_request.number }}"
PRIOR_JSON=$(gh pr list \
--repo "${{ github.repository }}" \
--state open \
--search "head:speakeasy-sdk-regen-" \
--limit 500 \
--json number \
| jq -r --arg cur "$CURRENT_PR" \
'[.[].number | select(tostring != $cur)] | .[]')
if [ -z "$PRIOR_JSON" ]; then
echo "No superseded Speakeasy PRs to close"
exit 0
fi
mapfile -t PRIOR <<< "$PRIOR_JSON"
echo "Closing ${#PRIOR[@]} superseded Speakeasy PR(s)"
for N in "${PRIOR[@]}"; do
gh pr close "$N" --repo "${{ github.repository }}" --delete-branch \
--comment "Superseded by newer Speakeasy SDK generation PR #${CURRENT_PR}" \
|| echo "::warning::Failed to close PR #$N (continuing)"
sleep 1
done
- name: Auto-merge Speakeasy PR
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
PR_NUM="${{ github.event.pull_request.number }}"
REPO="${{ github.repository }}"
STATE=$(gh pr view "$PR_NUM" --repo "$REPO" --json state --jq .state)
if [ "$STATE" != "OPEN" ]; then
echo "PR #$PR_NUM is $STATE — skipping merge"
exit 0
fi
# Prefer GitHub auto-merge when required checks exist; otherwise
# squash-merge directly (same pattern as sdk-release-prs.yaml).
AUTO_MERGE_NOOP_PATTERN='is in clean status|protected branch rules|Branch does not have required protected branch rules'
if gh pr merge "$PR_NUM" --repo "$REPO" --squash --auto --delete-branch 2> /tmp/gh-merge.err; then
echo "Auto-merge enabled for Speakeasy PR #$PR_NUM"
elif grep -qiE "$AUTO_MERGE_NOOP_PATTERN" /tmp/gh-merge.err; then
echo "Auto-merge not applicable — merging PR #$PR_NUM directly"
cat /tmp/gh-merge.err >&2
gh pr merge "$PR_NUM" --repo "$REPO" --squash --delete-branch
else
echo "::error::Failed to enable auto-merge on Speakeasy PR #$PR_NUM"
cat /tmp/gh-merge.err >&2
exit 1
fi
@@ -1,36 +0,0 @@
name: Generate (spec change merged)
permissions:
checks: write
contents: write
pull-requests: write
statuses: write
id-token: write
"on":
workflow_dispatch:
inputs:
force:
description: Force generation of SDKs
type: boolean
default: false
set_version:
description: optionally set a specific SDK version
type: string
pull_request:
types: [closed]
branches:
- main
paths:
- .speakeasy/in.openapi.yaml
jobs:
generate:
if: github.event.pull_request.merged == true || github.event_name == 'workflow_dispatch'
uses: speakeasy-api/sdk-generation-action/.github/workflows/workflow-executor.yaml@v15
with:
force: ${{ github.event.inputs.force }}
mode: pr
set_version: ${{ github.event.inputs.set_version }}
secrets:
github_access_token: ${{ secrets.GITHUB_TOKEN }}
pypi_token: ${{ secrets.PYPI_TOKEN }}
speakeasy_api_key: ${{ secrets.SPEAKEASY_API_KEY }}
+595 -5106
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -32,7 +32,7 @@ generation:
skipResponseBodyAssertions: false
preApplyUnionDiscriminators: true
python:
version: 0.10.0
version: 0.9.0
additionalDependencies:
dev: {}
main: {}
+877 -14230
View File
File diff suppressed because it is too large Load Diff
+857 -14146
View File
File diff suppressed because it is too large Load Diff
@@ -1,10 +0,0 @@
overlay: 1.0.0
x-speakeasy-jsonpath: rfc9535
info:
title: Fix nullable pagination params
version: 0.0.0
actions:
- target: $..parameters[?@.name == "offset" && @.in == "query"].schema
description: Remove nullable from offset query params to fix mypy errors in pagination helpers
update:
nullable: false
+6 -7
View File
@@ -2,20 +2,20 @@ speakeasyVersion: 1.680.0
sources:
OpenRouter API:
sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:716ece4a1211eac2ee0e7e5836c7b484cff9bb002bd4e676d9ecad8317ee7941
sourceBlobDigest: sha256:12d3dc8e7150ab2c4c5e3d613b01cb5e4dcce52b329eea89ca1fdc656d6fe045
sourceRevisionDigest: sha256:17976e34475ee87867828c00c8e2d0c66ebb004832cf9c34b937c70b2887fafb
sourceBlobDigest: sha256:1e517208c3664b60ade61442469e33564727eb61906514aab26d32cac4cd8ebe
tags:
- latest
- speakeasy-sdk-regen-1781312282
- speakeasy-sdk-regen-1775954251
- 1.0.0
targets:
open-router:
source: OpenRouter API
sourceNamespace: open-router-chat-completions-api
sourceRevisionDigest: sha256:716ece4a1211eac2ee0e7e5836c7b484cff9bb002bd4e676d9ecad8317ee7941
sourceBlobDigest: sha256:12d3dc8e7150ab2c4c5e3d613b01cb5e4dcce52b329eea89ca1fdc656d6fe045
sourceRevisionDigest: sha256:17976e34475ee87867828c00c8e2d0c66ebb004832cf9c34b937c70b2887fafb
sourceBlobDigest: sha256:1e517208c3664b60ade61442469e33564727eb61906514aab26d32cac4cd8ebe
codeSamplesNamespace: open-router-python-code-samples
codeSamplesRevisionDigest: sha256:e7d6f4de48a7c63cf15f3a8378f952277cd4c59373c28c61909497853fa769e2
codeSamplesRevisionDigest: sha256:51de2c56d26b7522fc0e0774cfc6eb2e7d79a32d463ab345c7b5194e513e9060
workflow:
workflowVersion: 1.0.0
speakeasyVersion: 1.680.0
@@ -29,7 +29,6 @@ workflow:
- location: .speakeasy/overlays/add-headers.overlay.yaml
- location: .speakeasy/overlays/allof-simplify.overlay.yaml
- location: .speakeasy/overlays/boolean-query-params.overlay.yaml
- location: .speakeasy/overlays/fix-nullable-pagination.overlay.yaml
output: .speakeasy/out.openapi.yaml
registry:
location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api
-1
View File
@@ -10,7 +10,6 @@ sources:
- location: .speakeasy/overlays/add-headers.overlay.yaml
- location: .speakeasy/overlays/allof-simplify.overlay.yaml
- location: .speakeasy/overlays/boolean-query-params.overlay.yaml
- location: .speakeasy/overlays/fix-nullable-pagination.overlay.yaml
output: .speakeasy/out.openapi.yaml
registry:
location: registry.speakeasyapi.dev/openrouter/sdk/open-router-chat-completions-api
+1 -1
View File
@@ -1,6 +1,6 @@
# OpenRouter Python SDK
The OpenRouter Python SDK is a type-safe toolkit for building AI applications with access to 400+ language models through a unified API.
The OpenRouter Python SDK is a type-safe toolkit for building AI applications with access to 300+ language models through a unified API.
## Why use the OpenRouter SDK?
+10 -37
View File
@@ -1,6 +1,6 @@
# OpenRouter SDK
# OpenRouter SDK (Beta)
The [OpenRouter SDK](https://openrouter.ai/docs/sdks/python) is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to 400+ models across providers in an easy and type-safe way.
The [OpenRouter SDK](https://openrouter.ai/docs/sdks/python) is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to over 300 models across providers in an easy and type-safe way.
To learn more about how to use the OpenRouter SDK, check out our [API Reference](https://openrouter.ai/docs/sdks/python/reference) and [Documentation](https://openrouter.ai/docs/sdks/python).
@@ -189,7 +189,7 @@ with OpenRouter(
api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:
res = open_router.byok.list()
res = open_router.guardrails.list()
while res is not None:
# Handle items
@@ -199,39 +199,6 @@ with OpenRouter(
```
<!-- End Pagination [pagination] -->
<!-- Start File uploads [file-upload] -->
## File uploads
Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
> [!TIP]
>
> For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files.
>
```python
from openrouter import OpenRouter
import os
with OpenRouter(
http_referer="<value>",
x_open_router_title="<value>",
x_open_router_categories="<value>",
api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:
res = open_router.files.upload(file={
"file_name": "example.file",
"content": open("example.file", "rb"),
})
# Handle response
print(res)
```
<!-- End File uploads [file-upload] -->
<!-- Start Resource Management [resource-management] -->
## Resource Management
@@ -309,4 +276,10 @@ To run the test suite, you'll need to set up your environment with an OpenRouter
```bash
pytest
```
```
## Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage
to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally
looking for the latest version.
+10 -37
View File
@@ -1,6 +1,6 @@
# OpenRouter SDK
# OpenRouter SDK (Beta)
The [OpenRouter SDK](https://openrouter.ai/docs/sdks/python) is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to 400+ models across providers in an easy and type-safe way.
The [OpenRouter SDK](https://openrouter.ai/docs/sdks/python) is a Python toolkit designed to help you build AI-powered features and solutions. Giving you easy access to over 300 models across providers in an easy and type-safe way.
To learn more about how to use the OpenRouter SDK, check out our [API Reference](https://openrouter.ai/docs/sdks/python/reference) and [Documentation](https://openrouter.ai/docs/sdks/python).
@@ -189,7 +189,7 @@ with OpenRouter(
api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:
res = open_router.byok.list()
res = open_router.guardrails.list()
while res is not None:
# Handle items
@@ -199,39 +199,6 @@ with OpenRouter(
```
<!-- End Pagination [pagination] -->
<!-- Start File uploads [file-upload] -->
## File uploads
Certain SDK methods accept file objects as part of a request body or multi-part request. It is possible and typically recommended to upload files as a stream rather than reading the entire contents into memory. This avoids excessive memory consumption and potentially crashing with out-of-memory errors when working with very large files. The following example demonstrates how to attach a file stream to a request.
> [!TIP]
>
> For endpoints that handle file uploads bytes arrays can also be used. However, using streams is recommended for large files.
>
```python
from openrouter import OpenRouter
import os
with OpenRouter(
http_referer="<value>",
x_open_router_title="<value>",
x_open_router_categories="<value>",
api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:
res = open_router.files.upload(file={
"file_name": "example.file",
"content": open("example.file", "rb"),
})
# Handle response
print(res)
```
<!-- End File uploads [file-upload] -->
<!-- Start Resource Management [resource-management] -->
## Resource Management
@@ -309,4 +276,10 @@ To run the test suite, you'll need to set up your environment with an OpenRouter
```bash
pytest
```
```
## Maturity
This SDK is in beta, and there may be breaking changes between versions without a major version update. Therefore, we recommend pinning usage
to a specific package version. This way, you can install the same version each time without breaking changes unless you are intentionally
looking for the latest version.
+3 -13
View File
@@ -10,22 +10,12 @@ Based on:
### Releases
- [PyPI v0.0.16] https://pypi.org/project/openrouter/0.0.16 - .
## 2026-06-11 00:55:55
## 2026-04-14 00:39:13
### Changes
Based on:
- OpenAPI Doc
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
### Generated
- [python v0.9.2] .
- [python v0.9.0] .
### Releases
- [PyPI v0.9.2] https://pypi.org/project/openrouter/0.9.2 - .
## 2026-06-17 00:59:07
### Changes
Based on:
- OpenAPI Doc
- Speakeasy CLI 1.680.0 (2.788.4) https://github.com/speakeasy-api/speakeasy
### Generated
- [python v0.10.0] .
### Releases
- [PyPI v0.10.0] https://pypi.org/project/openrouter/0.10.0 - .
- [PyPI v0.9.0] https://pypi.org/project/openrouter/0.9.0 - .
+4 -4
View File
@@ -7,7 +7,7 @@ Detailed completion token usage
| Field | Type | Required | Description |
| ---------------------------- | ---------------------------- | ---------------------------- | ---------------------------- |
| `accepted_prediction_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Accepted prediction tokens |
| `audio_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Tokens used for audio output |
| `reasoning_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Tokens used for reasoning |
| `rejected_prediction_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Rejected prediction tokens |
| `accepted_prediction_tokens` | *Optional[int]* | :heavy_minus_sign: | Accepted prediction tokens |
| `audio_tokens` | *Optional[int]* | :heavy_minus_sign: | Tokens used for audio output |
| `reasoning_tokens` | *Optional[int]* | :heavy_minus_sign: | Tokens used for reasoning |
| `rejected_prediction_tokens` | *Optional[int]* | :heavy_minus_sign: | Rejected prediction tokens |
+5 -7
View File
@@ -1,12 +1,10 @@
# CostDetails
Breakdown of upstream inference costs
## Fields
| Field | Type | Required | Description |
| ------------------------------------- | ------------------------------------- | ------------------------------------- | ------------------------------------- |
| `upstream_inference_completions_cost` | *float* | :heavy_check_mark: | N/A |
| `upstream_inference_cost` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
| `upstream_inference_prompt_cost` | *float* | :heavy_check_mark: | N/A |
| Field | Type | Required | Description |
| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- |
| `upstream_inference_cost` | *Optional[float]* | :heavy_minus_sign: | N/A |
| `upstream_inference_input_cost` | *float* | :heavy_check_mark: | N/A |
| `upstream_inference_output_cost` | *float* | :heavy_check_mark: | N/A |
+10
View File
@@ -0,0 +1,10 @@
# Data
Model count data
## Fields
| Field | Type | Required | Description | Example |
| -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- | -------------------------------- |
| `count` | *int* | :heavy_check_mark: | Total number of available models | 150 |
+8 -8
View File
@@ -5,11 +5,11 @@ Default parameters for this model
## Fields
| Field | Type | Required | Description |
| ------------------------- | ------------------------- | ------------------------- | ------------------------- |
| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
| `repetition_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
| `top_k` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A |
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A |
| Field | Type | Required | Description |
| ----------------------- | ----------------------- | ----------------------- | ----------------------- |
| `frequency_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A |
| `presence_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A |
| `repetition_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A |
| `temperature` | *Optional[float]* | :heavy_minus_sign: | N/A |
| `top_k` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A |
| `top_p` | *Optional[float]* | :heavy_minus_sign: | N/A |
+15
View File
@@ -0,0 +1,15 @@
# Effort
Constrains effort on reasoning for reasoning models
## Values
| Name | Value |
| --------- | --------- |
| `XHIGH` | xhigh |
| `HIGH` | high |
| `MEDIUM` | medium |
| `LOW` | low |
| `MINIMAL` | minimal |
| `NONE` | none |
+18 -20
View File
@@ -5,23 +5,21 @@ Information about an AI model available on OpenRouter
## Fields
| Field | Type | Required | Description | Example |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `architecture` | [components.ModelArchitecture](../components/modelarchitecture.md) | :heavy_check_mark: | Model architecture information | {<br/>"input_modalities": [<br/>"text"<br/>],<br/>"instruct_type": "chatml",<br/>"modality": "text-\u003etext",<br/>"output_modalities": [<br/>"text"<br/>],<br/>"tokenizer": "GPT"<br/>} |
| `benchmarks` | [Optional[components.ModelBenchmarks]](../components/modelbenchmarks.md) | :heavy_minus_sign: | Third-party benchmark rankings for this model. Omitted when no benchmark data is available. | {<br/>"artificial_analysis": {<br/>"agentic_index": 55.8,<br/>"coding_index": 63.2,<br/>"intelligence_index": 71.4<br/>},<br/>"design_arena": [<br/>{<br/>"arena": "models",<br/>"category": "website",<br/>"elo": 1385.2,<br/>"rank": 5,<br/>"win_rate": 62.5<br/>}<br/>]<br/>} |
| `canonical_slug` | *str* | :heavy_check_mark: | Canonical slug for the model | openai/gpt-4 |
| `context_length` | *Nullable[int]* | :heavy_check_mark: | Maximum context length in tokens | 8192 |
| `created` | *int* | :heavy_check_mark: | Unix timestamp of when the model was created | 1692901234 |
| `default_parameters` | [Nullable[components.DefaultParameters]](../components/defaultparameters.md) | :heavy_check_mark: | Default parameters for this model | {<br/>"frequency_penalty": 0,<br/>"presence_penalty": 0,<br/>"repetition_penalty": 1,<br/>"temperature": 0.7,<br/>"top_k": 0,<br/>"top_p": 0.9<br/>} |
| `description` | *Optional[str]* | :heavy_minus_sign: | Description of the model | GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. |
| `expiration_date` | *OptionalNullable[str]* | :heavy_minus_sign: | The date after which the model may be removed. ISO 8601 date string (YYYY-MM-DD) or null if no expiration. | 2025-06-01 |
| `hugging_face_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Hugging Face model identifier, if applicable | microsoft/DialoGPT-medium |
| `id` | *str* | :heavy_check_mark: | Unique identifier for the model | openai/gpt-4 |
| `knowledge_cutoff` | *OptionalNullable[str]* | :heavy_minus_sign: | The date up to which the model was trained on data. ISO 8601 date string (YYYY-MM-DD) or null if unknown. | 2024-10-01 |
| `links` | [components.ModelLinks](../components/modellinks.md) | :heavy_check_mark: | Related API endpoints and resources for this model. | {<br/>"details": "/api/v1/models/openai/gpt-5.4/endpoints"<br/>} |
| `name` | *str* | :heavy_check_mark: | Display name of the model | GPT-4 |
| `per_request_limits` | [Nullable[components.PerRequestLimits]](../components/perrequestlimits.md) | :heavy_check_mark: | Per-request token limits | {<br/>"completion_tokens": 1000,<br/>"prompt_tokens": 1000<br/>} |
| `pricing` | [components.PublicPricing](../components/publicpricing.md) | :heavy_check_mark: | Pricing information for the model | {<br/>"completion": "0.00006",<br/>"image": "0",<br/>"prompt": "0.00003",<br/>"request": "0"<br/>} |
| `supported_parameters` | List[[components.Parameter](../components/parameter.md)] | :heavy_check_mark: | List of supported parameters for this model | |
| `supported_voices` | List[*str*] | :heavy_check_mark: | List of supported voice identifiers for TTS models. Null for non-TTS models. | <nil> |
| `top_provider` | [components.TopProviderInfo](../components/topproviderinfo.md) | :heavy_check_mark: | Information about the top provider for this model | {<br/>"context_length": 8192,<br/>"is_moderated": true,<br/>"max_completion_tokens": 4096<br/>} |
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `architecture` | [components.ModelArchitecture](../components/modelarchitecture.md) | :heavy_check_mark: | Model architecture information | {<br/>"input_modalities": [<br/>"text"<br/>],<br/>"instruct_type": "chatml",<br/>"modality": "text-\u003etext",<br/>"output_modalities": [<br/>"text"<br/>],<br/>"tokenizer": "GPT"<br/>} |
| `canonical_slug` | *str* | :heavy_check_mark: | Canonical slug for the model | openai/gpt-4 |
| `context_length` | *int* | :heavy_check_mark: | Maximum context length in tokens | 8192 |
| `created` | *int* | :heavy_check_mark: | Unix timestamp of when the model was created | 1692901234 |
| `default_parameters` | [Nullable[components.DefaultParameters]](../components/defaultparameters.md) | :heavy_check_mark: | Default parameters for this model | {<br/>"frequency_penalty": 0,<br/>"presence_penalty": 0,<br/>"repetition_penalty": 1,<br/>"temperature": 0.7,<br/>"top_k": 0,<br/>"top_p": 0.9<br/>} |
| `description` | *Optional[str]* | :heavy_minus_sign: | Description of the model | GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy. |
| `expiration_date` | *OptionalNullable[str]* | :heavy_minus_sign: | The date after which the model may be removed. ISO 8601 date string (YYYY-MM-DD) or null if no expiration. | 2025-06-01 |
| `hugging_face_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Hugging Face model identifier, if applicable | microsoft/DialoGPT-medium |
| `id` | *str* | :heavy_check_mark: | Unique identifier for the model | openai/gpt-4 |
| `knowledge_cutoff` | *OptionalNullable[str]* | :heavy_minus_sign: | The date up to which the model was trained on data. ISO 8601 date string (YYYY-MM-DD) or null if unknown. | 2024-10-01 |
| `links` | [components.ModelLinks](../components/modellinks.md) | :heavy_check_mark: | Related API endpoints and resources for this model. | {<br/>"details": "/api/v1/models/openai/gpt-5.4/endpoints"<br/>} |
| `name` | *str* | :heavy_check_mark: | Display name of the model | GPT-4 |
| `per_request_limits` | [Nullable[components.PerRequestLimits]](../components/perrequestlimits.md) | :heavy_check_mark: | Per-request token limits | {<br/>"completion_tokens": 1000,<br/>"prompt_tokens": 1000<br/>} |
| `pricing` | [components.PublicPricing](../components/publicpricing.md) | :heavy_check_mark: | Pricing information for the model | {<br/>"completion": "0.00006",<br/>"image": "0",<br/>"prompt": "0.00003",<br/>"request": "0"<br/>} |
| `supported_parameters` | List[[components.Parameter](../components/parameter.md)] | :heavy_check_mark: | List of supported parameters for this model | |
| `top_provider` | [components.TopProviderInfo](../components/topproviderinfo.md) | :heavy_check_mark: | Information about the top provider for this model | {<br/>"context_length": 8192,<br/>"is_moderated": true,<br/>"max_completion_tokens": 4096<br/>} |
+3 -3
View File
@@ -5,6 +5,6 @@ Model count data
## Fields
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ | ------------------------------------------------------------------------------ |
| `data` | [components.ModelsCountResponseData](../components/modelscountresponsedata.md) | :heavy_check_mark: | Model count data | {<br/>"count": 150<br/>} |
| Field | Type | Required | Description | Example |
| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- |
| `data` | [components.Data](../components/data.md) | :heavy_check_mark: | Model count data | {<br/>"count": 150<br/>} |
+3 -3
View File
@@ -5,6 +5,6 @@ List of available models
## Fields
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `data` | List[[components.Model](../components/model.md)] | :heavy_check_mark: | List of available models | [<br/>{<br/>"architecture": {<br/>"input_modalities": [<br/>"text"<br/>],<br/>"instruct_type": "chatml",<br/>"modality": "text-\u003etext",<br/>"output_modalities": [<br/>"text"<br/>],<br/>"tokenizer": "GPT"<br/>},<br/>"canonical_slug": "openai/gpt-4",<br/>"context_length": 8192,<br/>"created": 1692901234,<br/>"default_parameters": null,<br/>"description": "GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy.",<br/>"expiration_date": null,<br/>"id": "openai/gpt-4",<br/>"knowledge_cutoff": null,<br/>"links": {<br/>"details": "/api/v1/models/openai/gpt-5.4/endpoints"<br/>},<br/>"name": "GPT-4",<br/>"per_request_limits": null,<br/>"pricing": {<br/>"completion": "0.00006",<br/>"image": "0",<br/>"prompt": "0.00003",<br/>"request": "0"<br/>},<br/>"supported_parameters": [<br/>"temperature",<br/>"top_p",<br/>"max_tokens"<br/>],<br/>"supported_voices": null,<br/>"top_provider": {<br/>"context_length": 8192,<br/>"is_moderated": true,<br/>"max_completion_tokens": 4096<br/>}<br/>}<br/>] |
| Field | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data` | List[[components.Model](../components/model.md)] | :heavy_check_mark: | List of available models | [<br/>{<br/>"architecture": {<br/>"input_modalities": [<br/>"text"<br/>],<br/>"instruct_type": "chatml",<br/>"modality": "text-\u003etext",<br/>"output_modalities": [<br/>"text"<br/>],<br/>"tokenizer": "GPT"<br/>},<br/>"canonical_slug": "openai/gpt-4",<br/>"context_length": 8192,<br/>"created": 1692901234,<br/>"default_parameters": null,<br/>"description": "GPT-4 is a large multimodal model that can solve difficult problems with greater accuracy.",<br/>"expiration_date": null,<br/>"id": "openai/gpt-4",<br/>"knowledge_cutoff": null,<br/>"links": {<br/>"details": "/api/v1/models/openai/gpt-5.4/endpoints"<br/>},<br/>"name": "GPT-4",<br/>"per_request_limits": null,<br/>"pricing": {<br/>"completion": "0.00006",<br/>"image": "0",<br/>"prompt": "0.00003",<br/>"request": "0"<br/>},<br/>"supported_parameters": [<br/>"temperature",<br/>"top_p",<br/>"max_tokens"<br/>],<br/>"top_provider": {<br/>"context_length": 8192,<br/>"is_moderated": true,<br/>"max_completion_tokens": 4096<br/>}<br/>}<br/>] |
@@ -39,15 +39,3 @@ value: components.OpenAIResponsesToolChoice = /* values here */
value: components.ToolChoiceAllowed = /* values here */
```
### `components.OpenAIResponsesToolChoiceApplyPatch`
```python
value: components.OpenAIResponsesToolChoiceApplyPatch = /* values here */
```
### `components.OpenAIResponsesToolChoiceShell`
```python
value: components.OpenAIResponsesToolChoiceShell = /* values here */
```
+8 -10
View File
@@ -3,13 +3,11 @@
## Values
| Name | Value |
| --------------- | --------------- |
| `TEXT` | text |
| `IMAGE` | image |
| `EMBEDDINGS` | embeddings |
| `AUDIO` | audio |
| `VIDEO` | video |
| `RERANK` | rerank |
| `SPEECH` | speech |
| `TRANSCRIPTION` | transcription |
| Name | Value |
| ------------ | ------------ |
| `TEXT` | text |
| `IMAGE` | image |
| `EMBEDDINGS` | embeddings |
| `AUDIO` | audio |
| `VIDEO` | video |
| `RERANK` | rerank |
+4 -4
View File
@@ -7,7 +7,7 @@ Percentile-based latency cutoffs. All specified cutoffs must be met for an endpo
| Field | Type | Required | Description |
| ----------------------------- | ----------------------------- | ----------------------------- | ----------------------------- |
| `p50` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum p50 latency (seconds) |
| `p75` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum p75 latency (seconds) |
| `p90` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum p90 latency (seconds) |
| `p99` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum p99 latency (seconds) |
| `p50` | *Optional[float]* | :heavy_minus_sign: | Maximum p50 latency (seconds) |
| `p75` | *Optional[float]* | :heavy_minus_sign: | Maximum p75 latency (seconds) |
| `p90` | *Optional[float]* | :heavy_minus_sign: | Maximum p90 latency (seconds) |
| `p99` | *Optional[float]* | :heavy_minus_sign: | Maximum p99 latency (seconds) |
@@ -7,7 +7,7 @@ Percentile-based throughput cutoffs. All specified cutoffs must be met for an en
| Field | Type | Required | Description |
| ----------------------------------- | ----------------------------------- | ----------------------------------- | ----------------------------------- |
| `p50` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum p50 throughput (tokens/sec) |
| `p75` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum p75 throughput (tokens/sec) |
| `p90` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum p90 throughput (tokens/sec) |
| `p99` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum p99 throughput (tokens/sec) |
| `p50` | *Optional[float]* | :heavy_minus_sign: | Minimum p50 throughput (tokens/sec) |
| `p75` | *Optional[float]* | :heavy_minus_sign: | Minimum p75 throughput (tokens/sec) |
| `p90` | *Optional[float]* | :heavy_minus_sign: | Minimum p90 throughput (tokens/sec) |
| `p99` | *Optional[float]* | :heavy_minus_sign: | Minimum p99 throughput (tokens/sec) |
+1 -9
View File
@@ -10,7 +10,6 @@
| `AION_LABS` | AionLabs |
| `ALIBABA` | Alibaba |
| `AMBIENT` | Ambient |
| `BAIDU` | Baidu |
| `AMAZON_BEDROCK` | Amazon Bedrock |
| `AMAZON_NOVA` | Amazon Nova |
| `ANTHROPIC` | Anthropic |
@@ -27,14 +26,10 @@
| `CLARIFAI` | Clarifai |
| `CLOUDFLARE` | Cloudflare |
| `COHERE` | Cohere |
| `CRUCIBLE` | Crucible |
| `CRUSOE` | Crusoe |
| `DARKBLOOM` | Darkbloom |
| `DECART` | Decart |
| `DEEP_INFRA` | DeepInfra |
| `DEEP_SEEK` | DeepSeek |
| `DEKA_LLM` | DekaLLM |
| `DIGITAL_OCEAN` | DigitalOcean |
| `FEATHERLESS` | Featherless |
| `FIREWORKS` | Fireworks |
| `FRIENDLI` | Friendli |
@@ -42,6 +37,7 @@
| `GOOGLE` | Google |
| `GOOGLE_AI_STUDIO` | Google AI Studio |
| `GROQ` | Groq |
| `HYPERBOLIC` | Hyperbolic |
| `INCEPTION` | Inception |
| `INCEPTRON` | Inceptron |
| `INFERENCE_NET` | InferenceNet |
@@ -60,15 +56,12 @@
| `MORPH` | Morph |
| `N_COMPASS` | NCompass |
| `NEBIUS` | Nebius |
| `NEX_AGI` | Nex AGI |
| `NEXT_BIT` | NextBit |
| `NOVITA` | Novita |
| `NVIDIA` | Nvidia |
| `OPEN_AI` | OpenAI |
| `OPEN_INFERENCE` | OpenInference |
| `PARASAIL` | Parasail |
| `POOLSIDE` | Poolside |
| `PERCEPTRON` | Perceptron |
| `PERPLEXITY` | Perplexity |
| `PHALA` | Phala |
| `RECRAFT` | Recraft |
@@ -85,7 +78,6 @@
| `TOGETHER` | Together |
| `UPSTAGE` | Upstage |
| `VENICE` | Venice |
| `WAFER` | Wafer |
| `WAND_B` | WandB |
| `XIAOMI` | Xiaomi |
| `X_AI` | xAI |
+5 -5
View File
@@ -9,8 +9,8 @@ Information about a specific model endpoint
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `context_length` | *int* | :heavy_check_mark: | N/A | |
| `latency_last_30m` | [Nullable[components.PercentileStats]](../components/percentilestats.md) | :heavy_check_mark: | Latency percentiles in milliseconds over the last 30 minutes. Latency measures time to first token. Only visible when authenticated with an API key or cookie; returns null for unauthenticated requests. | {<br/>"p50": 25.5,<br/>"p75": 35.2,<br/>"p90": 48.7,<br/>"p99": 85.3<br/>} |
| `max_completion_tokens` | *Nullable[int]* | :heavy_check_mark: | N/A | |
| `max_prompt_tokens` | *Nullable[int]* | :heavy_check_mark: | N/A | |
| `max_completion_tokens` | *int* | :heavy_check_mark: | N/A | |
| `max_prompt_tokens` | *int* | :heavy_check_mark: | N/A | |
| `model_id` | *str* | :heavy_check_mark: | The unique identifier for the model (permaslug) | openai/gpt-4 |
| `model_name` | *str* | :heavy_check_mark: | N/A | |
| `name` | *str* | :heavy_check_mark: | N/A | |
@@ -22,6 +22,6 @@ Information about a specific model endpoint
| `supports_implicit_caching` | *bool* | :heavy_check_mark: | N/A | |
| `tag` | *str* | :heavy_check_mark: | N/A | |
| `throughput_last_30m` | [Nullable[components.PercentileStats]](../components/percentilestats.md) | :heavy_check_mark: | N/A | {<br/>"p50": 25.5,<br/>"p75": 35.2,<br/>"p90": 48.7,<br/>"p99": 85.3<br/>} |
| `uptime_last_1d` | *Nullable[float]* | :heavy_check_mark: | Uptime percentage over the last 1 day, calculated as successful requests / (successful + error requests) * 100. Rate-limited requests are excluded. Returns null if insufficient data. | |
| `uptime_last_30m` | *Nullable[float]* | :heavy_check_mark: | N/A | |
| `uptime_last_5m` | *Nullable[float]* | :heavy_check_mark: | Uptime percentage over the last 5 minutes, calculated as successful requests / (successful + error requests) * 100. Rate-limited requests are excluded. Returns null if insufficient data. | |
| `uptime_last_1d` | *float* | :heavy_check_mark: | Uptime percentage over the last 1 day, calculated as successful requests / (successful + error requests) * 100. Rate-limited requests are excluded. Returns null if insufficient data. | |
| `uptime_last_30m` | *float* | :heavy_check_mark: | N/A | |
| `uptime_last_5m` | *float* | :heavy_check_mark: | Uptime percentage over the last 5 minutes, calculated as successful requests / (successful + error requests) * 100. Rate-limited requests are excluded. Returns null if insufficient data. | |
+11
View File
@@ -0,0 +1,11 @@
# Reasoning
Configuration options for reasoning models
## Fields
| Field | Type | Required | Description | Example |
| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `effort` | [OptionalNullable[components.Effort]](../components/effort.md) | :heavy_minus_sign: | Constrains effort on reasoning for reasoning models | medium |
| `summary` | [OptionalNullable[components.ChatReasoningSummaryVerbosityEnum]](../components/chatreasoningsummaryverbosityenum.md) | :heavy_minus_sign: | N/A | concise |
+2 -2
View File
@@ -7,6 +7,6 @@ Information about the top provider for this model
| Field | Type | Required | Description | Example |
| ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- | ----------------------------------------------- |
| `context_length` | *OptionalNullable[int]* | :heavy_minus_sign: | Context length from the top provider | 8192 |
| `context_length` | *Optional[int]* | :heavy_minus_sign: | Context length from the top provider | 8192 |
| `is_moderated` | *bool* | :heavy_check_mark: | Whether the top provider moderates content | true |
| `max_completion_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Maximum completion tokens from the top provider | 4096 |
| `max_completion_tokens` | *Optional[int]* | :heavy_minus_sign: | Maximum completion tokens from the top provider | 4096 |
-1
View File
@@ -5,7 +5,6 @@
| Field | Type | Required | Description |
| -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- | -------------------------------------------------------------- |
| `content` | *Optional[str]* | :heavy_minus_sign: | N/A |
| `end_index` | *int* | :heavy_check_mark: | N/A |
| `start_index` | *int* | :heavy_check_mark: | N/A |
| `title` | *str* | :heavy_check_mark: | N/A |
+6 -7
View File
@@ -5,10 +5,9 @@ The search engine to use for web search.
## Values
| Name | Value |
| ------------ | ------------ |
| `NATIVE` | native |
| `EXA` | exa |
| `FIRECRAWL` | firecrawl |
| `PARALLEL` | parallel |
| `PERPLEXITY` | perplexity |
| Name | Value |
| ----------- | ----------- |
| `NATIVE` | native |
| `EXA` | exa |
| `FIRECRAWL` | firecrawl |
| `PARALLEL` | parallel |
-1
View File
@@ -8,5 +8,4 @@ Bad Gateway - Provider/upstream API failure
| Field | Type | Required | Description | Example |
| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `error` | [components.BadGatewayResponseErrorData](../components/badgatewayresponseerrordata.md) | :heavy_check_mark: | Error data for BadGatewayResponse | {<br/>"code": 502,<br/>"message": "Provider returned error"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
-1
View File
@@ -8,5 +8,4 @@ Bad Request - Invalid request parameters or malformed input
| Field | Type | Required | Description | Example |
| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------- |
| `error` | [components.BadRequestResponseErrorData](../components/badrequestresponseerrordata.md) | :heavy_check_mark: | Error data for BadRequestResponse | {<br/>"code": 400,<br/>"message": "Invalid request parameters"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
@@ -8,5 +8,4 @@ Infrastructure Timeout - Provider request timed out at edge network
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `error` | [components.EdgeNetworkTimeoutResponseErrorData](../components/edgenetworktimeoutresponseerrordata.md) | :heavy_check_mark: | Error data for EdgeNetworkTimeoutResponse | {<br/>"code": 524,<br/>"message": "Request timed out. Please try again later."<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
-1
View File
@@ -8,5 +8,4 @@ Forbidden - Authentication successful but insufficient permissions
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ |
| `error` | [components.ForbiddenResponseErrorData](../components/forbiddenresponseerrordata.md) | :heavy_check_mark: | Error data for ForbiddenResponse | {<br/>"code": 403,<br/>"message": "Only management keys can perform this operation"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
@@ -8,5 +8,4 @@ Internal Server Error - Unexpected server error
| Field | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `error` | [components.InternalServerResponseErrorData](../components/internalserverresponseerrordata.md) | :heavy_check_mark: | Error data for InternalServerResponse | {<br/>"code": 500,<br/>"message": "Internal Server Error"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
-1
View File
@@ -8,5 +8,4 @@ Not Found - Resource does not exist
| Field | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| `error` | [components.NotFoundResponseErrorData](../components/notfoundresponseerrordata.md) | :heavy_check_mark: | Error data for NotFoundResponse | {<br/>"code": 404,<br/>"message": "Resource not found"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
@@ -8,5 +8,4 @@ Payload Too Large - Request payload exceeds size limits
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| `error` | [components.PayloadTooLargeResponseErrorData](../components/payloadtoolargeresponseerrordata.md) | :heavy_check_mark: | Error data for PayloadTooLargeResponse | {<br/>"code": 413,<br/>"message": "Request payload too large"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
@@ -8,5 +8,4 @@ Payment Required - Insufficient credits or quota to complete request
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| `error` | [components.PaymentRequiredResponseErrorData](../components/paymentrequiredresponseerrordata.md) | :heavy_check_mark: | Error data for PaymentRequiredResponse | {<br/>"code": 402,<br/>"message": "Insufficient credits. Add more using https://openrouter.ai/credits"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
@@ -8,5 +8,4 @@ Provider Overloaded - Provider is temporarily overloaded
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `error` | [components.ProviderOverloadedResponseErrorData](../components/provideroverloadedresponseerrordata.md) | :heavy_check_mark: | Error data for ProviderOverloadedResponse | {<br/>"code": 529,<br/>"message": "Provider returned error"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
@@ -8,5 +8,4 @@ Request Timeout - Operation exceeded time limit
| Field | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------- |
| `error` | [components.RequestTimeoutResponseErrorData](../components/requesttimeoutresponseerrordata.md) | :heavy_check_mark: | Error data for RequestTimeoutResponse | {<br/>"code": 408,<br/>"message": "Operation timed out. Please try again later."<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
@@ -8,5 +8,4 @@ Service Unavailable - Service temporarily unavailable
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `error` | [components.ServiceUnavailableResponseErrorData](../components/serviceunavailableresponseerrordata.md) | :heavy_check_mark: | Error data for ServiceUnavailableResponse | {<br/>"code": 503,<br/>"message": "Service temporarily unavailable"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
@@ -8,5 +8,4 @@ Too Many Requests - Rate limit exceeded
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ |
| `error` | [components.TooManyRequestsResponseErrorData](../components/toomanyrequestsresponseerrordata.md) | :heavy_check_mark: | Error data for TooManyRequestsResponse | {<br/>"code": 429,<br/>"message": "Rate limit exceeded"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
-1
View File
@@ -8,5 +8,4 @@ Unauthorized - Authentication required or invalid credentials
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ |
| `error` | [components.UnauthorizedResponseErrorData](../components/unauthorizedresponseerrordata.md) | :heavy_check_mark: | Error data for UnauthorizedResponse | {<br/>"code": 401,<br/>"message": "Missing Authentication header"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
@@ -8,5 +8,4 @@ Unprocessable Entity - Semantic validation failure
| Field | Type | Required | Description | Example |
| -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `error` | [components.UnprocessableEntityResponseErrorData](../components/unprocessableentityresponseerrordata.md) | :heavy_check_mark: | Error data for UnprocessableEntityResponse | {<br/>"code": 422,<br/>"message": "Invalid argument"<br/>} |
| `openrouter_metadata` | Dict[str, *Nullable[Any]*] | :heavy_minus_sign: | N/A | |
| `user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
+13
View File
@@ -0,0 +1,13 @@
# APIType
Type of API used for the generation
## Values
| Name | Value |
| ------------- | ------------- |
| `COMPLETIONS` | completions |
| `EMBEDDINGS` | embeddings |
| `RERANK` | rerank |
| `VIDEO` | video |
+21
View File
@@ -0,0 +1,21 @@
# Category
Filter models by use case category
## Values
| Name | Value |
| --------------- | --------------- |
| `PROGRAMMING` | programming |
| `ROLEPLAY` | roleplay |
| `MARKETING` | marketing |
| `MARKETING_SEO` | marketing/seo |
| `TECHNOLOGY` | technology |
| `SCIENCE` | science |
| `TRANSLATION` | translation |
| `LEGAL` | legal |
| `FINANCE` | finance |
| `HEALTH` | health |
| `TRIVIA` | trivia |
| `ACADEMIA` | academia |
-18
View File
@@ -15,21 +15,3 @@ value: operations.ContentText = /* values here */
value: operations.ContentImageURL = /* values here */
```
### `components.ContentPartInputAudio`
```python
value: components.ContentPartInputAudio = /* values here */
```
### `components.ContentPartInputVideo`
```python
value: components.ContentPartInputVideo = /* values here */
```
### `components.ContentPartInputFile`
```python
value: components.ContentPartInputFile = /* values here */
```
@@ -3,13 +3,12 @@
## Fields
| Field | Type | Required | Description | Example |
| -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Supports https URLs and localhost/127.0.0.1 URLs on any port for local CLI tools. | https://myapp.com/auth/callback |
| `code_challenge` | *Optional[str]* | :heavy_minus_sign: | PKCE code challenge for enhanced security | E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM |
| `code_challenge_method` | [Optional[operations.CreateAuthKeysCodeCodeChallengeMethod]](../operations/createauthkeyscodecodechallengemethod.md) | :heavy_minus_sign: | The method used to generate the code challenge | S256 |
| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional expiration time for the API key to be created | 2027-12-31T23:59:59Z |
| `key_label` | *Optional[str]* | :heavy_minus_sign: | Optional custom label for the API key. Defaults to the app name if not provided. | My Custom Key |
| `limit` | *Optional[float]* | :heavy_minus_sign: | Credit limit for the API key to be created | 100 |
| `usage_limit_type` | [Optional[operations.UsageLimitType]](../operations/usagelimittype.md) | :heavy_minus_sign: | Optional credit limit reset interval. When set, the credit limit resets on this interval. | monthly |
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Optional workspace ID to associate the API key with | |
| Field | Type | Required | Description | Example |
| -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed. | https://myapp.com/auth/callback |
| `code_challenge` | *Optional[str]* | :heavy_minus_sign: | PKCE code challenge for enhanced security | E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM |
| `code_challenge_method` | [Optional[operations.CreateAuthKeysCodeCodeChallengeMethod]](../operations/createauthkeyscodecodechallengemethod.md) | :heavy_minus_sign: | The method used to generate the code challenge | S256 |
| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional expiration time for the API key to be created | 2027-12-31T23:59:59Z |
| `key_label` | *Optional[str]* | :heavy_minus_sign: | Optional custom label for the API key. Defaults to the app name if not provided. | My Custom Key |
| `limit` | *Optional[float]* | :heavy_minus_sign: | Credit limit for the API key to be created | 100 |
| `usage_limit_type` | [Optional[operations.UsageLimitType]](../operations/usagelimittype.md) | :heavy_minus_sign: | Optional credit limit reset interval. When set, the credit limit resets on this interval. | monthly |
+6 -6
View File
@@ -3,9 +3,9 @@
## Fields
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `create_guardrail_request` | [components.CreateGuardrailRequest](../components/createguardrailrequest.md) | :heavy_check_mark: | N/A | {<br/>"allowed_models": null,<br/>"allowed_providers": [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>],<br/>"content_filter_builtins": [<br/>{<br/>"action": "block",<br/>"slug": "regex-prompt-injection"<br/>}<br/>],<br/>"content_filters": null,<br/>"description": "A guardrail for limiting API usage",<br/>"enforce_zdr_anthropic": true,<br/>"enforce_zdr_google": false,<br/>"enforce_zdr_openai": true,<br/>"enforce_zdr_other": false,<br/>"ignored_models": null,<br/>"ignored_providers": null,<br/>"limit_usd": 50,<br/>"name": "My New Guardrail",<br/>"reset_interval": "monthly"<br/>} |
| Field | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `create_guardrail_request` | [components.CreateGuardrailRequest](../components/createguardrailrequest.md) | :heavy_check_mark: | N/A | {<br/>"allowed_models": null,<br/>"allowed_providers": [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>],<br/>"description": "A guardrail for limiting API usage",<br/>"enforce_zdr": false,<br/>"ignored_models": null,<br/>"ignored_providers": null,<br/>"limit_usd": 50,<br/>"name": "My New Guardrail",<br/>"reset_interval": "monthly"<br/>} |
+3 -4
View File
@@ -18,13 +18,12 @@ The created API key information
| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943 |
| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false |
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key |
| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z |
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 |
| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 |
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
| `workspace_id` | *str* | :heavy_check_mark: | The workspace ID this API key belongs to. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
+2 -3
View File
@@ -8,7 +8,6 @@
| `creator_user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Optional user ID of the key creator. Only meaningful for organization-owned keys where a specific member is creating the key. | user_2dHFtVWx2n56w6HkM0000000000 |
| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected | 2027-12-31T23:59:59Z |
| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true |
| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 |
| `limit` | *Optional[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 |
| `limit_reset` | [OptionalNullable[operations.CreateKeysLimitReset]](../operations/createkeyslimitreset.md) | :heavy_minus_sign: | Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | monthly |
| `name` | *str* | :heavy_check_mark: | Name for the new API key | My New API Key |
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | The workspace to create the API key in. Defaults to the default workspace if not provided. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `name` | *str* | :heavy_check_mark: | Name for the new API key | My New API Key |
+4 -4
View File
@@ -5,7 +5,7 @@ API key created successfully
## Fields
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `data` | [operations.CreateKeysData](../operations/createkeysdata.md) | :heavy_check_mark: | The created API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5,<br/>"workspace_id": "0df9e665-d932-5740-b2c7-b52af166bc11"<br/>} |
| `key` | *str* | :heavy_check_mark: | The actual API key string (only shown once) | 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 |
| Field | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data` | [operations.CreateKeysData](../operations/createkeysdata.md) | :heavy_check_mark: | The created API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5<br/>} |
| `key` | *str* | :heavy_check_mark: | The actual API key string (only shown once) | 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 |
@@ -8,5 +8,4 @@
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `x_open_router_metadata` | [Optional[components.MetadataLevel]](../components/metadatalevel.md) | :heavy_minus_sign: | Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility. | enabled |
| `responses_request` | [components.ResponsesRequest](../components/responsesrequest.md) | :heavy_check_mark: | N/A | {<br/>"input": [<br/>{<br/>"content": "Hello, how are you?",<br/>"role": "user",<br/>"type": "message"<br/>}<br/>],<br/>"model": "anthropic/claude-4.5-sonnet-20250929",<br/>"temperature": 0.7,<br/>"tools": [<br/>{<br/>"description": "Get the current weather in a given location",<br/>"name": "get_current_weather",<br/>"parameters": {<br/>"properties": {<br/>"location": {<br/>"type": "string"<br/>}<br/>},<br/>"type": "object"<br/>},<br/>"type": "function"<br/>}<br/>],<br/>"top_p": 0.9<br/>} |
@@ -0,0 +1,10 @@
# CreateResponsesResponseBody
Successful response
## Fields
| Field | Type | Required | Description | Example |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data` | [components.StreamEvents](../components/streamevents.md) | :heavy_check_mark: | Union of all possible event types emitted during response streaming | {<br/>"response": {<br/>"created_at": 1704067200,<br/>"error": null,<br/>"id": "resp-abc123",<br/>"incomplete_details": null,<br/>"instructions": null,<br/>"max_output_tokens": null,<br/>"metadata": null,<br/>"model": "gpt-4",<br/>"object": "response",<br/>"output": [],<br/>"parallel_tool_calls": true,<br/>"status": "in_progress",<br/>"temperature": null,<br/>"tool_choice": "auto",<br/>"tools": [],<br/>"top_p": null<br/>},<br/>"sequence_number": 0,<br/>"type": "response.created"<br/>} |
+2 -2
View File
@@ -18,8 +18,8 @@ Current API key information
| `is_management_key` | *bool* | :heavy_check_mark: | Whether this is a management key | false |
| ~~`is_provisioning_key`~~ | *bool* | :heavy_check_mark: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.<br/><br/>Whether this is a management key | false |
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
| ~~`rate_limit`~~ | [operations.RateLimit](../operations/ratelimit.md) | :heavy_check_mark: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.<br/><br/>Legacy rate limit information about a key. Will always return -1. | {<br/>"interval": "1h",<br/>"note": "This field is deprecated and safe to ignore.",<br/>"requests": 1000<br/>} |
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
+47
View File
@@ -0,0 +1,47 @@
# GetGenerationData
Generation data
## Fields
| Field | Type | Required | Description | Example |
| --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------------------------------------------------------------------- |
| `api_type` | [Nullable[operations.APIType]](../operations/apitype.md) | :heavy_check_mark: | Type of API used for the generation | |
| `app_id` | *int* | :heavy_check_mark: | ID of the app that made the request | 12345 |
| `cache_discount` | *float* | :heavy_check_mark: | Discount applied due to caching | 0.0002 |
| `cancelled` | *Nullable[bool]* | :heavy_check_mark: | Whether the generation was cancelled | false |
| `created_at` | *str* | :heavy_check_mark: | ISO 8601 timestamp of when the generation was created | 2024-07-15T23:33:19.433273+00:00 |
| `external_user` | *Nullable[str]* | :heavy_check_mark: | External user identifier | user-123 |
| `finish_reason` | *Nullable[str]* | :heavy_check_mark: | Reason the generation finished | stop |
| `generation_time` | *float* | :heavy_check_mark: | Time taken for generation in milliseconds | 1200 |
| `http_referer` | *Nullable[str]* | :heavy_check_mark: | Referer header from the request | |
| `id` | *str* | :heavy_check_mark: | Unique identifier for the generation | gen-3bhGkxlo4XFrqiabUM7NDtwDzWwG |
| `is_byok` | *bool* | :heavy_check_mark: | Whether this used bring-your-own-key | false |
| `latency` | *float* | :heavy_check_mark: | Total latency in milliseconds | 1250 |
| `model` | *str* | :heavy_check_mark: | Model used for the generation | sao10k/l3-stheno-8b |
| `moderation_latency` | *float* | :heavy_check_mark: | Moderation latency in milliseconds | 50 |
| `native_finish_reason` | *Nullable[str]* | :heavy_check_mark: | Native finish reason as reported by provider | stop |
| `native_tokens_cached` | *int* | :heavy_check_mark: | Native cached tokens as reported by provider | 3 |
| `native_tokens_completion` | *int* | :heavy_check_mark: | Native completion tokens as reported by provider | 25 |
| `native_tokens_completion_images` | *int* | :heavy_check_mark: | Native completion image tokens as reported by provider | 0 |
| `native_tokens_prompt` | *int* | :heavy_check_mark: | Native prompt tokens as reported by provider | 10 |
| `native_tokens_reasoning` | *int* | :heavy_check_mark: | Native reasoning tokens as reported by provider | 5 |
| `num_input_audio_prompt` | *int* | :heavy_check_mark: | Number of audio inputs in the prompt | 0 |
| `num_media_completion` | *int* | :heavy_check_mark: | Number of media items in the completion | 0 |
| `num_media_prompt` | *int* | :heavy_check_mark: | Number of media items in the prompt | 1 |
| `num_search_results` | *int* | :heavy_check_mark: | Number of search results included | 5 |
| `origin` | *str* | :heavy_check_mark: | Origin URL of the request | https://openrouter.ai/ |
| `provider_name` | *Nullable[str]* | :heavy_check_mark: | Name of the provider that served the request | Infermatic |
| `provider_responses` | List[[components.ProviderResponse](../components/providerresponse.md)] | :heavy_check_mark: | List of provider responses for this generation, including fallback attempts | |
| `request_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Unique identifier grouping all generations from a single API request | req-1727282430-aBcDeFgHiJkLmNoPqRsT |
| `router` | *Nullable[str]* | :heavy_check_mark: | Router used for the request (e.g., openrouter/auto) | openrouter/auto |
| `session_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Session identifier grouping multiple generations in the same session | |
| `streamed` | *Nullable[bool]* | :heavy_check_mark: | Whether the response was streamed | true |
| `tokens_completion` | *int* | :heavy_check_mark: | Number of tokens in the completion | 25 |
| `tokens_prompt` | *int* | :heavy_check_mark: | Number of tokens in the prompt | 10 |
| `total_cost` | *float* | :heavy_check_mark: | Total cost of the generation in USD | 0.0015 |
| `upstream_id` | *Nullable[str]* | :heavy_check_mark: | Upstream provider's identifier for this generation | chatcmpl-791bcf62-080e-4568-87d0-94c72e3b4946 |
| `upstream_inference_cost` | *float* | :heavy_check_mark: | Cost charged by the upstream provider | 0.0012 |
| `usage` | *float* | :heavy_check_mark: | Usage amount in USD | 0.0015 |
| `user_agent` | *Nullable[str]* | :heavy_check_mark: | User-Agent header from the request | |
+10
View File
@@ -0,0 +1,10 @@
# GetGenerationResponse
Generation response
## Fields
| Field | Type | Required | Description |
| ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ | ------------------------------------------------------------------ |
| `data` | [operations.GetGenerationData](../operations/getgenerationdata.md) | :heavy_check_mark: | Generation data |
+3 -4
View File
@@ -18,13 +18,12 @@ The API key information
| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943 |
| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false |
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key |
| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z |
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 |
| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 |
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
| `workspace_id` | *str* | :heavy_check_mark: | The workspace ID this API key belongs to. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
+3 -3
View File
@@ -5,6 +5,6 @@ API key details
## Fields
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `data` | [operations.GetKeyData](../operations/getkeydata.md) | :heavy_check_mark: | The API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5,<br/>"workspace_id": "0df9e665-d932-5740-b2c7-b52af166bc11"<br/>} |
| Field | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data` | [operations.GetKeyData](../operations/getkeydata.md) | :heavy_check_mark: | The API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5<br/>} |
+8 -20
View File
@@ -3,23 +3,11 @@
## Fields
| Field | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `category` | [Optional[operations.GetModelsCategory]](../operations/getmodelscategory.md) | :heavy_minus_sign: | Filter models by use case category | programming |
| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | Filter models by supported parameter (comma-separated) | temperature |
| `output_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by output modality. Accepts a comma-separated list of modalities (text, image, audio, embeddings) or "all" to include all models. Defaults to "text". | text |
| `sort` | [Optional[operations.GetModelsSort]](../operations/getmodelssort.md) | :heavy_minus_sign: | Sort the returned models server-side. Prefer this over fetching the full list and sorting client-side. Options: pricing-low-to-high, pricing-high-to-low (average prompt/completion price), context-high-to-low (context length), throughput-high-to-low, latency-low-to-high (recent median performance), most-popular, top-weekly (tokens processed in the last week), newest (creation date). When omitted, the existing default ordering is preserved. | newest |
| `q` | *Optional[str]* | :heavy_minus_sign: | Free-text search by model name or slug. | gpt-4 |
| `input_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by input modality. Comma-separated list of: text, image, audio, file. | text,image |
| `context` | *Optional[int]* | :heavy_minus_sign: | Minimum context length (tokens). Models with smaller context are excluded. | 128000 |
| `min_price` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum prompt price in $/M tokens. | 0 |
| `max_price` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum prompt price in $/M tokens. | 10 |
| `arch` | *Optional[str]* | :heavy_minus_sign: | Filter models by architecture/model family (e.g. GPT, Claude, Gemini, Llama). | GPT |
| `model_authors` | *Optional[str]* | :heavy_minus_sign: | Filter models by the organization that created the model. Comma-separated list of author slugs. | openai,anthropic |
| `providers` | *Optional[str]* | :heavy_minus_sign: | Filter models by hosting provider. Comma-separated list of provider names. | OpenAI,Anthropic |
| `distillable` | [Optional[operations.Distillable]](../operations/distillable.md) | :heavy_minus_sign: | Filter by distillation capability. "true" returns only distillable models, "false" excludes them. | true |
| `zdr` | [Optional[operations.Zdr]](../operations/zdr.md) | :heavy_minus_sign: | When set to "true", return only models with zero data retention endpoints. | true |
| `region` | [Optional[operations.Region]](../operations/region.md) | :heavy_minus_sign: | Filter to models with endpoints in the given data region. Currently only "eu" is supported. | eu |
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `category` | [Optional[operations.Category]](../operations/category.md) | :heavy_minus_sign: | Filter models by use case category | programming |
| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | Filter models by supported parameter (comma-separated) | temperature |
| `output_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by output modality. Accepts a comma-separated list of modalities (text, image, audio, embeddings) or "all" to include all models. Defaults to "text". | text |
+3 -4
View File
@@ -16,13 +16,12 @@
| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943 |
| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false |
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key |
| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z |
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 |
| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 |
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
| `workspace_id` | *str* | :heavy_check_mark: | The workspace ID this API key belongs to. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
+1 -2
View File
@@ -9,5 +9,4 @@
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of records to skip for pagination | 0 |
| `limit` | *Optional[int]* | :heavy_minus_sign: | Maximum number of records to return (max 100) | 50 |
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Filter guardrails by workspace ID. By default, guardrails in the default workspace are returned. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `limit` | *Optional[int]* | :heavy_minus_sign: | Maximum number of records to return (max 100) | 50 |
+3 -3
View File
@@ -3,6 +3,6 @@
## Fields
| Field | Type | Required | Description | Example |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `result` | [components.ListGuardrailsResponse](../components/listguardrailsresponse.md) | :heavy_check_mark: | N/A | {<br/>"data": [<br/>{<br/>"allowed_models": null,<br/>"allowed_providers": [<br/>"openai",<br/>"anthropic",<br/>"google"<br/>],<br/>"content_filter_builtins": [<br/>{<br/>"action": "redact",<br/>"label": "[EMAIL]",<br/>"slug": "email"<br/>}<br/>],<br/>"content_filters": null,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"description": "Guardrail for production environment",<br/>"enforce_zdr": null,<br/>"enforce_zdr_anthropic": true,<br/>"enforce_zdr_google": false,<br/>"enforce_zdr_openai": true,<br/>"enforce_zdr_other": false,<br/>"id": "550e8400-e29b-41d4-a716-446655440000",<br/>"ignored_models": null,<br/>"ignored_providers": null,<br/>"limit_usd": 100,<br/>"name": "Production Guardrail",<br/>"reset_interval": "monthly",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"workspace_id": "0df9e665-d932-5740-b2c7-b52af166bc11"<br/>}<br/>],<br/>"total_count": 1<br/>} |
| Field | Type | Required | Description | Example |
| --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `result` | [components.ListGuardrailsResponse](../components/listguardrailsresponse.md) | :heavy_check_mark: | N/A | {<br/>"data": [<br/>{<br/>"allowed_models": null,<br/>"allowed_providers": [<br/>"openai",<br/>"anthropic",<br/>"google"<br/>],<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"description": "Guardrail for production environment",<br/>"enforce_zdr": false,<br/>"id": "550e8400-e29b-41d4-a716-446655440000",<br/>"ignored_models": null,<br/>"ignored_providers": null,<br/>"limit_usd": 100,<br/>"name": "Production Guardrail",<br/>"reset_interval": "monthly",<br/>"updated_at": "2025-08-24T15:45:00Z"<br/>}<br/>],<br/>"total_count": 1<br/>} |
+1 -2
View File
@@ -9,5 +9,4 @@
| `x_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `include_disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to include disabled API keys in the response | false |
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of API keys to skip for pagination | 0 |
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Filter API keys by workspace ID. By default, keys in the default workspace are returned. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of API keys to skip for pagination | 0 |
@@ -8,5 +8,4 @@
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `x_open_router_metadata` | [Optional[components.MetadataLevel]](../components/metadatalevel.md) | :heavy_minus_sign: | Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility. | enabled |
| `chat_request` | [components.ChatRequest](../components/chatrequest.md) | :heavy_check_mark: | N/A | {<br/>"max_tokens": 150,<br/>"messages": [<br/>{<br/>"content": "You are a helpful assistant.",<br/>"role": "system"<br/>},<br/>{<br/>"content": "What is the capital of France?",<br/>"role": "user"<br/>}<br/>],<br/>"model": "openai/gpt-4",<br/>"temperature": 0.7<br/>} |
@@ -0,0 +1,10 @@
# SendChatCompletionRequestResponseBody
Successful chat completion response
## Fields
| Field | Type | Required | Description | Example |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data` | [components.ChatStreamChunk](../components/chatstreamchunk.md) | :heavy_check_mark: | Streaming chat completion chunk | {<br/>"choices": [<br/>{<br/>"delta": {<br/>"content": "Hello",<br/>"role": "assistant"<br/>},<br/>"finish_reason": null,<br/>"index": 0<br/>}<br/>],<br/>"created": 1677652288,<br/>"id": "chatcmpl-123",<br/>"model": "openai/gpt-4",<br/>"object": "chat.completion.chunk"<br/>} |
+3 -4
View File
@@ -18,13 +18,12 @@ The updated API key information
| `hash` | *str* | :heavy_check_mark: | Unique hash identifier for the API key | f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943 |
| `include_byok_in_limit` | *bool* | :heavy_check_mark: | Whether to include external BYOK usage in the credit limit | false |
| `label` | *str* | :heavy_check_mark: | Human-readable label for the API key | sk-or-v1-0e6...1c96 |
| `limit` | *Nullable[float]* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *Nullable[float]* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit` | *float* | :heavy_check_mark: | Spending limit for the API key in USD | 100 |
| `limit_remaining` | *float* | :heavy_check_mark: | Remaining spending limit in USD | 74.5 |
| `limit_reset` | *Nullable[str]* | :heavy_check_mark: | Type of limit reset for the API key | monthly |
| `name` | *str* | :heavy_check_mark: | Name of the API key | My Production Key |
| `updated_at` | *Nullable[str]* | :heavy_check_mark: | ISO 8601 timestamp of when the API key was last updated | 2025-08-24T15:45:00Z |
| `usage` | *float* | :heavy_check_mark: | Total OpenRouter credit usage (in USD) for the API key | 25.5 |
| `usage_daily` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC day | 25.5 |
| `usage_monthly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC month | 25.5 |
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
| `workspace_id` | *str* | :heavy_check_mark: | The workspace ID this API key belongs to. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `usage_weekly` | *float* | :heavy_check_mark: | OpenRouter credit usage (in USD) for the current UTC week (Monday-Sunday) | 25.5 |
+1 -1
View File
@@ -7,6 +7,6 @@
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to disable the API key | false |
| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true |
| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 |
| `limit` | *Optional[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 |
| `limit_reset` | [OptionalNullable[operations.UpdateKeysLimitReset]](../operations/updatekeyslimitreset.md) | :heavy_minus_sign: | New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | daily |
| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the API key | Updated API Key Name |
+3 -3
View File
@@ -5,6 +5,6 @@ API key updated successfully
## Fields
| Field | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `data` | [operations.UpdateKeysData](../operations/updatekeysdata.md) | :heavy_check_mark: | The updated API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5,<br/>"workspace_id": "0df9e665-d932-5740-b2c7-b52af166bc11"<br/>} |
| Field | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `data` | [operations.UpdateKeysData](../operations/updatekeysdata.md) | :heavy_check_mark: | The updated API key information | {<br/>"byok_usage": 17.38,<br/>"byok_usage_daily": 17.38,<br/>"byok_usage_monthly": 17.38,<br/>"byok_usage_weekly": 17.38,<br/>"created_at": "2025-08-24T10:30:00Z",<br/>"creator_user_id": "user_2dHFtVWx2n56w6HkM0000000000",<br/>"disabled": false,<br/>"expires_at": "2027-12-31T23:59:59Z",<br/>"hash": "f01d52606dc8f0a8303a7b5cc3fa07109c2e346cec7c0a16b40de462992ce943",<br/>"include_byok_in_limit": false,<br/>"label": "sk-or-v1-0e6...1c96",<br/>"limit": 100,<br/>"limit_remaining": 74.5,<br/>"limit_reset": "monthly",<br/>"name": "My Production Key",<br/>"updated_at": "2025-08-24T15:45:00Z",<br/>"usage": 25.5,<br/>"usage_daily": 25.5,<br/>"usage_monthly": 25.5,<br/>"usage_weekly": 25.5<br/>} |
+2 -5
View File
@@ -95,7 +95,6 @@ with OpenRouter(
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `include_disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to include disabled API keys in the response | false |
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of API keys to skip for pagination | 0 |
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Filter API keys by workspace ID. By default, keys in the default workspace are returned. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
@@ -149,9 +148,8 @@ with OpenRouter(
| `creator_user_id` | *OptionalNullable[str]* | :heavy_minus_sign: | Optional user ID of the key creator. Only meaningful for organization-owned keys where a specific member is creating the key. | user_2dHFtVWx2n56w6HkM0000000000 |
| `expires_at` | [date](https://docs.python.org/3/library/datetime.html#date-objects) | :heavy_minus_sign: | Optional ISO 8601 UTC timestamp when the API key should expire. Must be UTC, other timezones will be rejected | 2027-12-31T23:59:59Z |
| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true |
| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 |
| `limit` | *Optional[float]* | :heavy_minus_sign: | Optional spending limit for the API key in USD | 50 |
| `limit_reset` | [OptionalNullable[operations.CreateKeysLimitReset]](../../operations/createkeyslimitreset.md) | :heavy_minus_sign: | Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | monthly |
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | The workspace to create the API key in. Defaults to the default workspace if not provided. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
@@ -164,7 +162,6 @@ with OpenRouter(
| ----------------------------------- | ----------------------------------- | ----------------------------------- |
| errors.BadRequestResponseError | 400 | application/json |
| errors.UnauthorizedResponseError | 401 | application/json |
| errors.ForbiddenResponseError | 403 | application/json |
| errors.TooManyRequestsResponseError | 429 | application/json |
| errors.InternalServerResponseError | 500 | application/json |
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
@@ -305,7 +302,7 @@ with OpenRouter(
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `disabled` | *Optional[bool]* | :heavy_minus_sign: | Whether to disable the API key | false |
| `include_byok_in_limit` | *Optional[bool]* | :heavy_minus_sign: | Whether to include BYOK usage in the limit | true |
| `limit` | *OptionalNullable[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 |
| `limit` | *Optional[float]* | :heavy_minus_sign: | New spending limit for the API key in USD | 75 |
| `limit_reset` | [OptionalNullable[operations.UpdateKeysLimitReset]](../../operations/updatekeyslimitreset.md) | :heavy_minus_sign: | New limit reset type for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday. | daily |
| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the API key | Updated API Key Name |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
+39 -47
View File
@@ -34,7 +34,7 @@ with OpenRouter(
"content": "What is the capital of France?",
"role": "user",
},
], x_open_router_metadata="enabled", max_tokens=150, model="openai/gpt-4", stream=False, temperature=0.7)
], max_tokens=150, model="openai/gpt-4", stream=False, temperature=0.7)
with res as event_stream:
for event in event_stream:
@@ -45,51 +45,44 @@ with OpenRouter(
### Parameters
| Parameter | Type | Required | Description | Example |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `messages` | List[[components.ChatMessages](../../components/chatmessages.md)] | :heavy_check_mark: | List of messages for the conversation | [<br/>{<br/>"content": "Hello!",<br/>"role": "user"<br/>}<br/>] |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `x_open_router_metadata` | [Optional[components.MetadataLevel]](../../components/metadatalevel.md) | :heavy_minus_sign: | Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility. | enabled |
| `cache_control` | [Optional[components.AnthropicCacheControlDirective]](../../components/anthropiccachecontroldirective.md) | :heavy_minus_sign: | Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models. | {<br/>"type": "ephemeral"<br/>} |
| `debug` | [Optional[components.ChatDebugOptions]](../../components/chatdebugoptions.md) | :heavy_minus_sign: | Debug options for inspecting request transformations (streaming only) | {<br/>"echo_upstream_body": true<br/>} |
| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | Frequency penalty (-2.0 to 2.0) | 0 |
| `image_config` | Dict[str, [components.ImageConfig](../../components/imageconfig.md)] | :heavy_minus_sign: | Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details. | {<br/>"aspect_ratio": "16:9",<br/>"quality": "high"<br/>} |
| `logit_bias` | Dict[str, *float*] | :heavy_minus_sign: | Token logit bias adjustments | {<br/>"50256": -100<br/>} |
| `logprobs` | *OptionalNullable[bool]* | :heavy_minus_sign: | Return log probabilities | false |
| `max_completion_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Maximum tokens in completion | 100 |
| `max_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16. | 100 |
| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values) | {<br/>"session_id": "session-456",<br/>"user_id": "user-123"<br/>} |
| `min_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter. | 0.1 |
| `modalities` | List[[components.Modality](../../components/modality.md)] | :heavy_minus_sign: | Output modalities for the response. Supported values are "text", "image", and "audio". | [<br/>"text",<br/>"image"<br/>] |
| `model` | *Optional[str]* | :heavy_minus_sign: | Model to use for completion | openai/gpt-4 |
| `models` | List[*str*] | :heavy_minus_sign: | Models to use for completion | [<br/>"openai/gpt-4",<br/>"openai/gpt-4o"<br/>] |
| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enable parallel function calling during tool use. When true, the model may generate multiple tool calls in a single response. | true |
| `plugins` | List[[components.ChatRequestPlugin](../../components/chatrequestplugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | Presence penalty (-2.0 to 2.0) | 0 |
| `provider` | [OptionalNullable[components.ProviderPreferences]](../../components/providerpreferences.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | {<br/>"allow_fallbacks": true<br/>} |
| `reasoning` | [Optional[components.ChatRequestReasoning]](../../components/chatrequestreasoning.md) | :heavy_minus_sign: | Configuration options for reasoning models | {<br/>"effort": "medium",<br/>"summary": "concise"<br/>} |
| `reasoning_effort` | [OptionalNullable[components.ChatRequestReasoningEffort]](../../components/chatrequestreasoningeffort.md) | :heavy_minus_sign: | Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ. | medium |
| `repetition_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter. | 1 |
| `response_format` | [Optional[components.ResponseFormat]](../../components/responseformat.md) | :heavy_minus_sign: | Response format configuration | {<br/>"type": "json_object"<br/>} |
| `seed` | *OptionalNullable[int]* | :heavy_minus_sign: | Random seed for deterministic outputs | 42 |
| `service_tier` | [OptionalNullable[components.ChatRequestServiceTier]](../../components/chatrequestservicetier.md) | :heavy_minus_sign: | The service tier to use for processing this request. | auto |
| `session_id` | *Optional[str]* | :heavy_minus_sign: | A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. | |
| `stop` | [OptionalNullable[components.Stop]](../../components/stop.md) | :heavy_minus_sign: | Stop sequences (up to 4) | [<br/>""<br/>] |
| `stop_server_tools_when` | List[[components.StopServerToolsWhenCondition](../../components/stopservertoolswhencondition.md)] | :heavy_minus_sign: | Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`. | [<br/>{<br/>"step_count": 5,<br/>"type": "step_count_is"<br/>},<br/>{<br/>"max_cost_in_dollars": 0.5,<br/>"type": "max_cost"<br/>}<br/>] |
| `stream` | *Optional[bool]* | :heavy_minus_sign: | Enable streaming response | false |
| `stream_options` | [OptionalNullable[components.ChatStreamOptions]](../../components/chatstreamoptions.md) | :heavy_minus_sign: | Streaming configuration options | {<br/>"include_usage": true<br/>} |
| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | Sampling temperature (0-2) | 0.7 |
| `tool_choice` | [Optional[components.ChatToolChoice]](../../components/chattoolchoice.md) | :heavy_minus_sign: | Tool choice configuration | auto |
| `tools` | List[[components.ChatFunctionTool](../../components/chatfunctiontool.md)] | :heavy_minus_sign: | Available tools for function calling | [<br/>{<br/>"function": {<br/>"description": "Get weather",<br/>"name": "get_weather"<br/>},<br/>"type": "function"<br/>}<br/>] |
| `top_a` | *OptionalNullable[float]* | :heavy_minus_sign: | Consider only tokens with "sufficiently high" probabilities based on the probability of the most likely token. Not all providers support this parameter. | 0 |
| `top_k` | *OptionalNullable[int]* | :heavy_minus_sign: | Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter. | 40 |
| `top_logprobs` | *OptionalNullable[int]* | :heavy_minus_sign: | Number of top log probabilities to return (0-20) | 5 |
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | 1 |
| `trace` | [Optional[components.TraceConfig]](../../components/traceconfig.md) | :heavy_minus_sign: | Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations. | {<br/>"trace_id": "trace-abc123",<br/>"trace_name": "my-app-trace"<br/>} |
| `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | user-123 |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
| Parameter | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `messages` | List[[components.ChatMessages](../../components/chatmessages.md)] | :heavy_check_mark: | List of messages for the conversation | [<br/>{<br/>"content": "Hello!",<br/>"role": "user"<br/>}<br/>] |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `cache_control` | [Optional[components.AnthropicCacheControlDirective]](../../components/anthropiccachecontroldirective.md) | :heavy_minus_sign: | N/A | {<br/>"type": "ephemeral"<br/>} |
| `debug` | [Optional[components.ChatDebugOptions]](../../components/chatdebugoptions.md) | :heavy_minus_sign: | Debug options for inspecting request transformations (streaming only) | {<br/>"echo_upstream_body": true<br/>} |
| `frequency_penalty` | *Optional[float]* | :heavy_minus_sign: | Frequency penalty (-2.0 to 2.0) | 0 |
| `image_config` | Dict[str, [components.ChatRequestImageConfig](../../components/chatrequestimageconfig.md)] | :heavy_minus_sign: | Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details. | {<br/>"aspect_ratio": "16:9"<br/>} |
| `logit_bias` | Dict[str, *float*] | :heavy_minus_sign: | Token logit bias adjustments | {<br/>"50256": -100<br/>} |
| `logprobs` | *OptionalNullable[bool]* | :heavy_minus_sign: | Return log probabilities | false |
| `max_completion_tokens` | *Optional[int]* | :heavy_minus_sign: | Maximum tokens in completion | 100 |
| `max_tokens` | *Optional[int]* | :heavy_minus_sign: | Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16. | 100 |
| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values) | {<br/>"session_id": "session-456",<br/>"user_id": "user-123"<br/>} |
| `modalities` | List[[components.Modality](../../components/modality.md)] | :heavy_minus_sign: | Output modalities for the response. Supported values are "text", "image", and "audio". | [<br/>"text",<br/>"image"<br/>] |
| `model` | *Optional[str]* | :heavy_minus_sign: | Model to use for completion | openai/gpt-4 |
| `models` | List[*str*] | :heavy_minus_sign: | Models to use for completion | [<br/>"openai/gpt-4",<br/>"openai/gpt-4o"<br/>] |
| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enable parallel function calling during tool use. When true, the model may generate multiple tool calls in a single response. | true |
| `plugins` | List[[components.ChatRequestPlugin](../../components/chatrequestplugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
| `presence_penalty` | *Optional[float]* | :heavy_minus_sign: | Presence penalty (-2.0 to 2.0) | 0 |
| `provider` | [OptionalNullable[components.ProviderPreferences]](../../components/providerpreferences.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | {<br/>"allow_fallbacks": true<br/>} |
| `reasoning` | [Optional[components.Reasoning]](../../components/reasoning.md) | :heavy_minus_sign: | Configuration options for reasoning models | {<br/>"effort": "medium",<br/>"summary": "concise"<br/>} |
| `response_format` | [Optional[components.ResponseFormat]](../../components/responseformat.md) | :heavy_minus_sign: | Response format configuration | {<br/>"type": "json_object"<br/>} |
| `seed` | *Optional[int]* | :heavy_minus_sign: | Random seed for deterministic outputs | 42 |
| `service_tier` | [OptionalNullable[components.ChatRequestServiceTier]](../../components/chatrequestservicetier.md) | :heavy_minus_sign: | The service tier to use for processing this request. | auto |
| `session_id` | *Optional[str]* | :heavy_minus_sign: | A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. | |
| `stop` | [OptionalNullable[components.Stop]](../../components/stop.md) | :heavy_minus_sign: | Stop sequences (up to 4) | [<br/>""<br/>] |
| `stream` | *Optional[bool]* | :heavy_minus_sign: | Enable streaming response | false |
| `stream_options` | [OptionalNullable[components.ChatStreamOptions]](../../components/chatstreamoptions.md) | :heavy_minus_sign: | Streaming configuration options | {<br/>"include_usage": true<br/>} |
| `temperature` | *Optional[float]* | :heavy_minus_sign: | Sampling temperature (0-2) | 0.7 |
| `tool_choice` | [Optional[components.ChatToolChoice]](../../components/chattoolchoice.md) | :heavy_minus_sign: | Tool choice configuration | auto |
| `tools` | List[[components.ChatFunctionTool](../../components/chatfunctiontool.md)] | :heavy_minus_sign: | Available tools for function calling | [<br/>{<br/>"function": {<br/>"description": "Get weather",<br/>"name": "get_weather"<br/>},<br/>"type": "function"<br/>}<br/>] |
| `top_logprobs` | *Optional[int]* | :heavy_minus_sign: | Number of top log probabilities to return (0-20) | 5 |
| `top_p` | *Optional[float]* | :heavy_minus_sign: | Nucleus sampling parameter (0-1) | 1 |
| `trace` | [Optional[components.TraceConfig]](../../components/traceconfig.md) | :heavy_minus_sign: | Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations. | {<br/>"trace_id": "trace-abc123",<br/>"trace_name": "my-app-trace"<br/>} |
| `user` | *Optional[str]* | :heavy_minus_sign: | Unique user identifier | user-123 |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
@@ -102,7 +95,6 @@ with OpenRouter(
| errors.BadRequestResponseError | 400 | application/json |
| errors.UnauthorizedResponseError | 401 | application/json |
| errors.PaymentRequiredResponseError | 402 | application/json |
| errors.ForbiddenResponseError | 403 | application/json |
| errors.NotFoundResponseError | 404 | application/json |
| errors.RequestTimeoutResponseError | 408 | application/json |
| errors.PayloadTooLargeResponseError | 413 | application/json |
+1 -56
View File
@@ -7,7 +7,6 @@ Generation history endpoints
### Available Operations
* [get_generation](#get_generation) - Get request & usage metadata for a generation
* [list_generation_content](#list_generation_content) - Get stored prompt and completion content for a generation
## get_generation
@@ -47,7 +46,7 @@ with OpenRouter(
### Response
**[components.GenerationResponse](../../components/generationresponse.md)**
**[operations.GetGenerationResponse](../../operations/getgenerationresponse.md)**
### Errors
@@ -61,58 +60,4 @@ with OpenRouter(
| errors.BadGatewayResponseError | 502 | application/json |
| errors.EdgeNetworkTimeoutResponseError | 524 | application/json |
| errors.ProviderOverloadedResponseError | 529 | application/json |
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
## list_generation_content
Get stored prompt and completion content for a generation
### Example Usage
<!-- UsageSnippet language="python" operationID="listGenerationContent" method="get" path="/generation/content" -->
```python
from openrouter import OpenRouter
import os
with OpenRouter(
http_referer="<value>",
x_open_router_title="<value>",
x_open_router_categories="<value>",
api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:
res = open_router.generations.list_generation_content(id="gen-1234567890")
# Handle response
print(res)
```
### Parameters
| Parameter | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | *str* | :heavy_check_mark: | The generation ID | gen-1234567890 |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
**[components.GenerationContentResponse](../../components/generationcontentresponse.md)**
### Errors
| Error Type | Status Code | Content Type |
| -------------------------------------- | -------------------------------------- | -------------------------------------- |
| errors.UnauthorizedResponseError | 401 | application/json |
| errors.ForbiddenResponseError | 403 | application/json |
| errors.NotFoundResponseError | 404 | application/json |
| errors.TooManyRequestsResponseError | 429 | application/json |
| errors.InternalServerResponseError | 500 | application/json |
| errors.BadGatewayResponseError | 502 | application/json |
| errors.EdgeNetworkTimeoutResponseError | 524 | application/json |
| errors.ProviderOverloadedResponseError | 529 | application/json |
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
+32 -47
View File
@@ -57,7 +57,6 @@ with OpenRouter(
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `offset` | *Optional[int]* | :heavy_minus_sign: | Number of records to skip for pagination | 0 |
| `limit` | *Optional[int]* | :heavy_minus_sign: | Maximum number of records to return (max 100) | 50 |
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Filter guardrails by workspace ID. By default, guardrails in the default workspace are returned. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
@@ -95,7 +94,7 @@ with OpenRouter(
"openai",
"anthropic",
"deepseek",
], description="A guardrail for limiting API usage", enforce_zdr_anthropic=True, enforce_zdr_google=False, enforce_zdr_openai=True, enforce_zdr_other=False, ignored_models=None, ignored_providers=None, limit_usd=50, reset_interval="monthly")
], description="A guardrail for limiting API usage", enforce_zdr=False, ignored_models=None, ignored_providers=None, limit_usd=50, reset_interval="monthly")
# Handle response
print(res)
@@ -104,28 +103,21 @@ with OpenRouter(
### Parameters
| Parameter | Type | Required | Description | Example |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | *str* | :heavy_check_mark: | Name for the new guardrail | My New Guardrail |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `allowed_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers (slug or canonical_slug accepted) | [<br/>"openai/gpt-5.2",<br/>"anthropic/claude-4.5-opus-20251124",<br/>"deepseek/deepseek-r1-0528:free"<br/>] |
| `allowed_providers` | List[*str*] | :heavy_minus_sign: | List of allowed provider IDs | [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>] |
| `content_filter_builtins` | List[[components.ContentFilterBuiltinEntryInput](../../components/contentfilterbuiltinentryinput.md)] | :heavy_minus_sign: | Builtin content filters to apply. The "flag" action is only supported for "regex-prompt-injection"; PII slugs (email, phone, ssn, credit-card, ip-address, person-name, address) accept "block" or "redact" only. | [<br/>{<br/>"action": "block",<br/>"slug": "regex-prompt-injection"<br/>}<br/>] |
| `content_filters` | List[[components.ContentFilterEntry](../../components/contentfilterentry.md)] | :heavy_minus_sign: | Custom regex content filters to apply to request messages | [<br/>{<br/>"action": "redact",<br/>"label": "[API_KEY]",<br/>"pattern": "\\b(sk-[a-zA-Z0-9]{48})\\b"<br/>}<br/>] |
| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | Description of the guardrail | A guardrail for limiting API usage |
| `enforce_zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.<br/><br/>Deprecated. Use enforce_zdr_anthropic, enforce_zdr_openai, enforce_zdr_google, and enforce_zdr_other instead. When provided, its value is copied into any of those per-provider fields that are not explicitly specified on the request. | false |
| `enforce_zdr_anthropic` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for Anthropic models. Falls back to enforce_zdr when not provided. | false |
| `enforce_zdr_google` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for Google models. Falls back to enforce_zdr when not provided. | false |
| `enforce_zdr_openai` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for OpenAI models. Falls back to enforce_zdr when not provided. | false |
| `enforce_zdr_other` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for models that are not from Anthropic, OpenAI, or Google. Falls back to enforce_zdr when not provided. | false |
| `ignored_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers to exclude from routing (slug or canonical_slug accepted) | [<br/>"openai/gpt-4o-mini"<br/>] |
| `ignored_providers` | List[*str*] | :heavy_minus_sign: | List of provider IDs to exclude from routing | [<br/>"azure"<br/>] |
| `limit_usd` | *OptionalNullable[float]* | :heavy_minus_sign: | Spending limit in USD | 50 |
| `reset_interval` | [OptionalNullable[components.GuardrailInterval]](../../components/guardrailinterval.md) | :heavy_minus_sign: | Interval at which the limit resets (daily, weekly, monthly) | monthly |
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | The workspace to create the guardrail in. Defaults to the default workspace if not provided. | 0df9e665-d932-5740-b2c7-b52af166bc11 |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
| Parameter | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `name` | *str* | :heavy_check_mark: | Name for the new guardrail | My New Guardrail |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `allowed_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers (slug or canonical_slug accepted) | [<br/>"openai/gpt-5.2",<br/>"anthropic/claude-4.5-opus-20251124",<br/>"deepseek/deepseek-r1-0528:free"<br/>] |
| `allowed_providers` | List[*str*] | :heavy_minus_sign: | List of allowed provider IDs | [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>] |
| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | Description of the guardrail | A guardrail for limiting API usage |
| `enforce_zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention | false |
| `ignored_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers to exclude from routing (slug or canonical_slug accepted) | [<br/>"openai/gpt-4o-mini"<br/>] |
| `ignored_providers` | List[*str*] | :heavy_minus_sign: | List of provider IDs to exclude from routing | [<br/>"azure"<br/>] |
| `limit_usd` | *Optional[float]* | :heavy_minus_sign: | Spending limit in USD | 50 |
| `reset_interval` | [OptionalNullable[components.GuardrailInterval]](../../components/guardrailinterval.md) | :heavy_minus_sign: | Interval at which the limit resets (daily, weekly, monthly) | monthly |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
@@ -137,7 +129,6 @@ with OpenRouter(
| ---------------------------------- | ---------------------------------- | ---------------------------------- |
| errors.BadRequestResponseError | 400 | application/json |
| errors.UnauthorizedResponseError | 401 | application/json |
| errors.ForbiddenResponseError | 403 | application/json |
| errors.InternalServerResponseError | 500 | application/json |
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
@@ -267,28 +258,22 @@ with OpenRouter(
### Parameters
| Parameter | Type | Required | Description | Example |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | *str* | :heavy_check_mark: | The unique identifier of the guardrail to update | 550e8400-e29b-41d4-a716-446655440000 |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `allowed_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers (slug or canonical_slug accepted) | [<br/>"openai/gpt-5.2"<br/>] |
| `allowed_providers` | List[*str*] | :heavy_minus_sign: | New list of allowed provider IDs | [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>] |
| `content_filter_builtins` | List[[components.ContentFilterBuiltinEntryInput](../../components/contentfilterbuiltinentryinput.md)] | :heavy_minus_sign: | Builtin content filters to apply. Set to null to remove. The "flag" action is only supported for "regex-prompt-injection"; PII slugs (email, phone, ssn, credit-card, ip-address, person-name, address) accept "block" or "redact" only. | [<br/>{<br/>"action": "block",<br/>"slug": "regex-prompt-injection"<br/>}<br/>] |
| `content_filters` | List[[components.ContentFilterEntry](../../components/contentfilterentry.md)] | :heavy_minus_sign: | Custom regex content filters to apply. Set to null to remove. | <nil> |
| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | New description for the guardrail | Updated description |
| `enforce_zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | : warning: ** DEPRECATED **: This will be removed in a future release, please migrate away from it as soon as possible.<br/><br/>Deprecated. Use enforce_zdr_anthropic, enforce_zdr_openai, enforce_zdr_google, and enforce_zdr_other instead. When provided, its value is copied into any of those per-provider fields that are not explicitly specified on the request. | true |
| `enforce_zdr_anthropic` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for Anthropic models. Falls back to enforce_zdr when not provided. | true |
| `enforce_zdr_google` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for Google models. Falls back to enforce_zdr when not provided. | true |
| `enforce_zdr_openai` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for OpenAI models. Falls back to enforce_zdr when not provided. | true |
| `enforce_zdr_other` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention for models that are not from Anthropic, OpenAI, or Google. Falls back to enforce_zdr when not provided. | true |
| `ignored_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers to exclude from routing (slug or canonical_slug accepted) | [<br/>"openai/gpt-4o-mini"<br/>] |
| `ignored_providers` | List[*str*] | :heavy_minus_sign: | List of provider IDs to exclude from routing | [<br/>"azure"<br/>] |
| `limit_usd` | *OptionalNullable[float]* | :heavy_minus_sign: | New spending limit in USD | 75 |
| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the guardrail | Updated Guardrail Name |
| `reset_interval` | [OptionalNullable[components.GuardrailInterval]](../../components/guardrailinterval.md) | :heavy_minus_sign: | Interval at which the limit resets (daily, weekly, monthly) | monthly |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
| Parameter | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id` | *str* | :heavy_check_mark: | The unique identifier of the guardrail to update | 550e8400-e29b-41d4-a716-446655440000 |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `allowed_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers (slug or canonical_slug accepted) | [<br/>"openai/gpt-5.2"<br/>] |
| `allowed_providers` | List[*str*] | :heavy_minus_sign: | New list of allowed provider IDs | [<br/>"openai",<br/>"anthropic",<br/>"deepseek"<br/>] |
| `description` | *OptionalNullable[str]* | :heavy_minus_sign: | New description for the guardrail | Updated description |
| `enforce_zdr` | *OptionalNullable[bool]* | :heavy_minus_sign: | Whether to enforce zero data retention | true |
| `ignored_models` | List[*str*] | :heavy_minus_sign: | Array of model identifiers to exclude from routing (slug or canonical_slug accepted) | [<br/>"openai/gpt-4o-mini"<br/>] |
| `ignored_providers` | List[*str*] | :heavy_minus_sign: | List of provider IDs to exclude from routing | [<br/>"azure"<br/>] |
| `limit_usd` | *Optional[float]* | :heavy_minus_sign: | New spending limit in USD | 75 |
| `name` | *Optional[str]* | :heavy_minus_sign: | New name for the guardrail | Updated Guardrail Name |
| `reset_interval` | [OptionalNullable[components.GuardrailInterval]](../../components/guardrailinterval.md) | :heavy_minus_sign: | Interval at which the limit resets (daily, weekly, monthly) | monthly |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
+9 -71
View File
@@ -6,60 +6,10 @@ Model information endpoints
### Available Operations
* [get](#get) - Get a model by its slug
* [list](#list) - List all models and their properties
* [count](#count) - Get total count of available models
* [list_for_user](#list_for_user) - List models filtered by user provider preferences, privacy settings, and guardrails
## get
Returns full details for a single model identified by its author and slug (e.g. openai/gpt-4). Supports variant suffixes (e.g. openai/gpt-4:free) and resolves known slug aliases.
### Example Usage
<!-- UsageSnippet language="python" operationID="getModel" method="get" path="/model/{author}/{slug}" -->
```python
from openrouter import OpenRouter
import os
with OpenRouter(
http_referer="<value>",
x_open_router_title="<value>",
x_open_router_categories="<value>",
api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:
res = open_router.models.get(author="openai", slug="gpt-4")
# Handle response
print(res)
```
### Parameters
| Parameter | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `author` | *str* | :heavy_check_mark: | The author/organization of the model | openai |
| `slug` | *str* | :heavy_check_mark: | The model slug, optionally including a variant suffix (e.g. gpt-4 or gpt-4:free) | gpt-4 |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
**[components.ModelResponse](../../components/modelresponse.md)**
### Errors
| Error Type | Status Code | Content Type |
| ---------------------------------- | ---------------------------------- | ---------------------------------- |
| errors.NotFoundResponseError | 404 | application/json |
| errors.InternalServerResponseError | 500 | application/json |
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
## list
List all models and their properties
@@ -88,27 +38,15 @@ with OpenRouter(
### Parameters
| Parameter | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `category` | [Optional[operations.GetModelsCategory]](../../operations/getmodelscategory.md) | :heavy_minus_sign: | Filter models by use case category | programming |
| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | Filter models by supported parameter (comma-separated) | temperature |
| `output_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by output modality. Accepts a comma-separated list of modalities (text, image, audio, embeddings) or "all" to include all models. Defaults to "text". | text |
| `sort` | [Optional[operations.GetModelsSort]](../../operations/getmodelssort.md) | :heavy_minus_sign: | Sort the returned models server-side. Prefer this over fetching the full list and sorting client-side. Options: pricing-low-to-high, pricing-high-to-low (average prompt/completion price), context-high-to-low (context length), throughput-high-to-low, latency-low-to-high (recent median performance), most-popular, top-weekly (tokens processed in the last week), newest (creation date). When omitted, the existing default ordering is preserved. | newest |
| `q` | *Optional[str]* | :heavy_minus_sign: | Free-text search by model name or slug. | gpt-4 |
| `input_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by input modality. Comma-separated list of: text, image, audio, file. | text,image |
| `context` | *Optional[int]* | :heavy_minus_sign: | Minimum context length (tokens). Models with smaller context are excluded. | 128000 |
| `min_price` | *OptionalNullable[float]* | :heavy_minus_sign: | Minimum prompt price in $/M tokens. | 0 |
| `max_price` | *OptionalNullable[float]* | :heavy_minus_sign: | Maximum prompt price in $/M tokens. | 10 |
| `arch` | *Optional[str]* | :heavy_minus_sign: | Filter models by architecture/model family (e.g. GPT, Claude, Gemini, Llama). | GPT |
| `model_authors` | *Optional[str]* | :heavy_minus_sign: | Filter models by the organization that created the model. Comma-separated list of author slugs. | openai,anthropic |
| `providers` | *Optional[str]* | :heavy_minus_sign: | Filter models by hosting provider. Comma-separated list of provider names. | OpenAI,Anthropic |
| `distillable` | [Optional[operations.Distillable]](../../operations/distillable.md) | :heavy_minus_sign: | Filter by distillation capability. "true" returns only distillable models, "false" excludes them. | true |
| `zdr` | [Optional[operations.Zdr]](../../operations/zdr.md) | :heavy_minus_sign: | When set to "true", return only models with zero data retention endpoints. | true |
| `region` | [Optional[operations.Region]](../../operations/region.md) | :heavy_minus_sign: | Filter to models with endpoints in the given data region. Currently only "eu" is supported. | eu |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
| Parameter | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `category` | [Optional[operations.Category]](../../operations/category.md) | :heavy_minus_sign: | Filter models by use case category | programming |
| `supported_parameters` | *Optional[str]* | :heavy_minus_sign: | Filter models by supported parameter (comma-separated) | temperature |
| `output_modalities` | *Optional[str]* | :heavy_minus_sign: | Filter models by output modality. Accepts a comma-separated list of modalities (text, image, audio, embeddings) or "all" to include all models. Defaults to "text". | text |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
+1 -3
View File
@@ -90,7 +90,7 @@ with OpenRouter(
| Parameter | Type | Required | Description | Example |
| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- |
| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Supports https URLs and localhost/127.0.0.1 URLs on any port for local CLI tools. | https://myapp.com/auth/callback |
| `callback_url` | *str* | :heavy_check_mark: | The callback URL to redirect to after authorization. Note, only https URLs on ports 443 and 3000 are allowed. | https://myapp.com/auth/callback |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
@@ -100,7 +100,6 @@ with OpenRouter(
| `key_label` | *Optional[str]* | :heavy_minus_sign: | Optional custom label for the API key. Defaults to the app name if not provided. | My Custom Key |
| `limit` | *Optional[float]* | :heavy_minus_sign: | Credit limit for the API key to be created | 100 |
| `usage_limit_type` | [Optional[operations.UsageLimitType]](../../operations/usagelimittype.md) | :heavy_minus_sign: | Optional credit limit reset interval. When set, the credit limit resets on this interval. | monthly |
| `workspace_id` | *Optional[str]* | :heavy_minus_sign: | Optional workspace ID to associate the API key with | |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
@@ -113,7 +112,6 @@ with OpenRouter(
| ---------------------------------- | ---------------------------------- | ---------------------------------- |
| errors.BadRequestResponseError | 400 | application/json |
| errors.UnauthorizedResponseError | 401 | application/json |
| errors.ForbiddenResponseError | 403 | application/json |
| errors.ConflictResponseError | 409 | application/json |
| errors.InternalServerResponseError | 500 | application/json |
| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* |
+41 -45
View File
@@ -27,7 +27,7 @@ with OpenRouter(
api_key=os.getenv("OPENROUTER_API_KEY", ""),
) as open_router:
res = open_router.beta.responses.send(x_open_router_metadata="enabled", input="Tell me a joke", model="openai/gpt-4o", service_tier="auto", stream=False)
res = open_router.beta.responses.send(input="Tell me a joke", model="openai/gpt-4o", service_tier="auto", stream=False)
with res as event_stream:
for event in event_stream:
@@ -38,49 +38,46 @@ with OpenRouter(
### Parameters
| Parameter | Type | Required | Description | Example |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `x_open_router_metadata` | [Optional[components.MetadataLevel]](../../components/metadatalevel.md) | :heavy_minus_sign: | Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility. | enabled |
| `background` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
| `cache_control` | [Optional[components.AnthropicCacheControlDirective]](../../components/anthropiccachecontroldirective.md) | :heavy_minus_sign: | Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models. | {<br/>"type": "ephemeral"<br/>} |
| `frequency_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | |
| `image_config` | Dict[str, [components.ImageConfig](../../components/imageconfig.md)] | :heavy_minus_sign: | Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details. | {<br/>"aspect_ratio": "16:9",<br/>"quality": "high"<br/>} |
| `include` | List[[components.ResponseIncludesEnum](../../components/responseincludesenum.md)] | :heavy_minus_sign: | N/A | |
| `input` | [Optional[components.InputsUnion]](../../components/inputsunion.md) | :heavy_minus_sign: | Input for a response request - can be a string or array of items | [<br/>{<br/>"content": "What is the weather today?",<br/>"role": "user"<br/>}<br/>] |
| `instructions` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `max_output_tokens` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | |
| `max_tool_calls` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | |
| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. | {<br/>"session_id": "abc-def-ghi",<br/>"user_id": "123"<br/>} |
| `modalities` | List[[components.OutputModalityEnum](../../components/outputmodalityenum.md)] | :heavy_minus_sign: | Output modalities for the response. Supported values are "text" and "image". | [<br/>"text",<br/>"image"<br/>] |
| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | |
| `models` | List[*str*] | :heavy_minus_sign: | N/A | |
| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
| `plugins` | List[[components.ResponsesRequestPlugin](../../components/responsesrequestplugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
| `presence_penalty` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | |
| `previous_response_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `prompt` | [OptionalNullable[components.StoredPromptTemplate]](../../components/storedprompttemplate.md) | :heavy_minus_sign: | N/A | {<br/>"id": "prompt-abc123",<br/>"variables": {<br/>"name": "John"<br/>}<br/>} |
| `prompt_cache_key` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `provider` | [OptionalNullable[components.ProviderPreferences]](../../components/providerpreferences.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | {<br/>"allow_fallbacks": true<br/>} |
| `reasoning` | [OptionalNullable[components.ReasoningConfig]](../../components/reasoningconfig.md) | :heavy_minus_sign: | Configuration for reasoning mode in the response | {<br/>"effort": "medium",<br/>"summary": "auto"<br/>} |
| `safety_identifier` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `service_tier` | [OptionalNullable[components.ResponsesRequestServiceTier]](../../components/responsesrequestservicetier.md) | :heavy_minus_sign: | N/A | |
| `session_id` | *Optional[str]* | :heavy_minus_sign: | A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. | |
| `stop_server_tools_when` | List[[components.StopServerToolsWhenCondition](../../components/stopservertoolswhencondition.md)] | :heavy_minus_sign: | Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`. | [<br/>{<br/>"step_count": 5,<br/>"type": "step_count_is"<br/>},<br/>{<br/>"max_cost_in_dollars": 0.5,<br/>"type": "max_cost"<br/>}<br/>] |
| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | |
| `temperature` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | |
| `text` | [Optional[components.TextExtendedConfig]](../../components/textextendedconfig.md) | :heavy_minus_sign: | Text output configuration including format and verbosity | {<br/>"format": {<br/>"type": "text"<br/>},<br/>"verbosity": "medium"<br/>} |
| `tool_choice` | [Optional[components.OpenAIResponsesToolChoiceUnion]](../../components/openairesponsestoolchoiceunion.md) | :heavy_minus_sign: | N/A | auto |
| `tools` | List[[components.ResponsesRequestToolUnion](../../components/responsesrequesttoolunion.md)] | :heavy_minus_sign: | N/A | |
| `top_k` | *Optional[int]* | :heavy_minus_sign: | N/A | |
| `top_logprobs` | *OptionalNullable[int]* | :heavy_minus_sign: | N/A | |
| `top_p` | *OptionalNullable[float]* | :heavy_minus_sign: | N/A | |
| `trace` | [Optional[components.TraceConfig]](../../components/traceconfig.md) | :heavy_minus_sign: | Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations. | {<br/>"trace_id": "trace-abc123",<br/>"trace_name": "my-app-trace"<br/>} |
| `truncation` | [OptionalNullable[components.OpenAIResponsesTruncation]](../../components/openairesponsestruncation.md) | :heavy_minus_sign: | N/A | auto |
| `user` | *Optional[str]* | :heavy_minus_sign: | A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 256 characters. | |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
| Parameter | Type | Required | Description | Example |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `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_open_router_title` | *Optional[str]* | :heavy_minus_sign: | The app display name allows you to customize how your app appears in OpenRouter's dashboard.<br/> | |
| `x_open_router_categories` | *Optional[str]* | :heavy_minus_sign: | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.<br/> | |
| `background` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
| `frequency_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A | |
| `image_config` | Dict[str, [components.ResponsesRequestImageConfig](../../components/responsesrequestimageconfig.md)] | :heavy_minus_sign: | Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/features/multimodal/image-generation for more details. | {<br/>"aspect_ratio": "16:9"<br/>} |
| `include` | List[[components.ResponseIncludesEnum](../../components/responseincludesenum.md)] | :heavy_minus_sign: | N/A | |
| `input` | [Optional[components.InputsUnion]](../../components/inputsunion.md) | :heavy_minus_sign: | Input for a response request - can be a string or array of items | [<br/>{<br/>"content": "What is the weather today?",<br/>"role": "user"<br/>}<br/>] |
| `instructions` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `max_output_tokens` | *Optional[int]* | :heavy_minus_sign: | N/A | |
| `max_tool_calls` | *Optional[int]* | :heavy_minus_sign: | N/A | |
| `metadata` | Dict[str, *str*] | :heavy_minus_sign: | Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed. | {<br/>"session_id": "abc-def-ghi",<br/>"user_id": "123"<br/>} |
| `modalities` | List[[components.OutputModalityEnum](../../components/outputmodalityenum.md)] | :heavy_minus_sign: | Output modalities for the response. Supported values are "text" and "image". | [<br/>"text",<br/>"image"<br/>] |
| `model` | *Optional[str]* | :heavy_minus_sign: | N/A | |
| `models` | List[*str*] | :heavy_minus_sign: | N/A | |
| `parallel_tool_calls` | *OptionalNullable[bool]* | :heavy_minus_sign: | N/A | |
| `plugins` | List[[components.ResponsesRequestPlugin](../../components/responsesrequestplugin.md)] | :heavy_minus_sign: | Plugins you want to enable for this request, including their settings. | |
| `presence_penalty` | *Optional[float]* | :heavy_minus_sign: | N/A | |
| `previous_response_id` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `prompt` | [OptionalNullable[components.StoredPromptTemplate]](../../components/storedprompttemplate.md) | :heavy_minus_sign: | N/A | {<br/>"id": "prompt-abc123",<br/>"variables": {<br/>"name": "John"<br/>}<br/>} |
| `prompt_cache_key` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `provider` | [OptionalNullable[components.ProviderPreferences]](../../components/providerpreferences.md) | :heavy_minus_sign: | When multiple model providers are available, optionally indicate your routing preference. | {<br/>"allow_fallbacks": true<br/>} |
| `reasoning` | [OptionalNullable[components.ReasoningConfig]](../../components/reasoningconfig.md) | :heavy_minus_sign: | Configuration for reasoning mode in the response | {<br/>"effort": "medium",<br/>"summary": "auto"<br/>} |
| `safety_identifier` | *OptionalNullable[str]* | :heavy_minus_sign: | N/A | |
| `service_tier` | [OptionalNullable[components.ResponsesRequestServiceTier]](../../components/responsesrequestservicetier.md) | :heavy_minus_sign: | N/A | |
| `session_id` | *Optional[str]* | :heavy_minus_sign: | A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters. | |
| `stream` | *Optional[bool]* | :heavy_minus_sign: | N/A | |
| `temperature` | *Optional[float]* | :heavy_minus_sign: | N/A | |
| `text` | [Optional[components.TextExtendedConfig]](../../components/textextendedconfig.md) | :heavy_minus_sign: | Text output configuration including format and verbosity | {<br/>"format": {<br/>"type": "text"<br/>},<br/>"verbosity": "medium"<br/>} |
| `tool_choice` | [Optional[components.OpenAIResponsesToolChoiceUnion]](../../components/openairesponsestoolchoiceunion.md) | :heavy_minus_sign: | N/A | auto |
| `tools` | List[[components.ResponsesRequestToolUnion](../../components/responsesrequesttoolunion.md)] | :heavy_minus_sign: | N/A | |
| `top_k` | *Optional[int]* | :heavy_minus_sign: | N/A | |
| `top_logprobs` | *Optional[int]* | :heavy_minus_sign: | N/A | |
| `top_p` | *Optional[float]* | :heavy_minus_sign: | N/A | |
| `trace` | [Optional[components.TraceConfig]](../../components/traceconfig.md) | :heavy_minus_sign: | Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations. | {<br/>"trace_id": "trace-abc123",<br/>"trace_name": "my-app-trace"<br/>} |
| `truncation` | [OptionalNullable[components.OpenAIResponsesTruncation]](../../components/openairesponsestruncation.md) | :heavy_minus_sign: | N/A | auto |
| `user` | *Optional[str]* | :heavy_minus_sign: | A unique identifier representing your end-user, which helps distinguish between different users of your app. This allows your app to identify specific users in case of abuse reports, preventing your entire app from being affected by the actions of individual users. Maximum of 256 characters. | |
| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.md) | :heavy_minus_sign: | Configuration to override the default retry behavior of the client. | |
### Response
@@ -93,7 +90,6 @@ with OpenRouter(
| errors.BadRequestResponseError | 400 | application/json |
| errors.UnauthorizedResponseError | 401 | application/json |
| errors.PaymentRequiredResponseError | 402 | application/json |
| errors.ForbiddenResponseError | 403 | application/json |
| errors.NotFoundResponseError | 404 | application/json |
| errors.RequestTimeoutResponseError | 408 | application/json |
| errors.PayloadTooLargeResponseError | 413 | application/json |
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "openrouter"
version = "0.10.0"
version = "0.9.0"
description = "Official Python Client SDK for OpenRouter."
authors = [{ name = "OpenRouter" },]
readme = "README-PYPI.md"
+2 -2
View File
@@ -3,10 +3,10 @@
import importlib.metadata
__title__: str = "openrouter"
__version__: str = "0.10.0"
__version__: str = "0.9.0"
__openapi_doc_version__: str = "1.0.0"
__gen_version__: str = "2.788.4"
__user_agent__: str = "speakeasy-sdk/python 0.10.0 2.788.4 1.0.0 openrouter"
__user_agent__: str = "speakeasy-sdk/python 0.9.0 2.788.4 1.0.0 openrouter"
try:
if __package__ is not None:
+6 -28
View File
@@ -257,7 +257,6 @@ class APIKeys(BaseSDK):
x_open_router_categories: Optional[str] = None,
include_disabled: Optional[bool] = None,
offset: Optional[int] = None,
workspace_id: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -276,7 +275,6 @@ class APIKeys(BaseSDK):
:param include_disabled: Whether to include disabled API keys in the response
:param offset: Number of API keys to skip for pagination
:param workspace_id: Filter API keys by workspace ID. By default, keys in the default workspace are returned.
: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
@@ -298,7 +296,6 @@ class APIKeys(BaseSDK):
x_open_router_categories=x_open_router_categories,
include_disabled=include_disabled,
offset=offset,
workspace_id=workspace_id,
)
req = self._build_request(
@@ -389,7 +386,6 @@ class APIKeys(BaseSDK):
x_open_router_categories: Optional[str] = None,
include_disabled: Optional[bool] = None,
offset: Optional[int] = None,
workspace_id: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -408,7 +404,6 @@ class APIKeys(BaseSDK):
:param include_disabled: Whether to include disabled API keys in the response
:param offset: Number of API keys to skip for pagination
:param workspace_id: Filter API keys by workspace ID. By default, keys in the default workspace are returned.
: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
@@ -430,7 +425,6 @@ class APIKeys(BaseSDK):
x_open_router_categories=x_open_router_categories,
include_disabled=include_disabled,
offset=offset,
workspace_id=workspace_id,
)
req = self._build_request_async(
@@ -523,9 +517,8 @@ class APIKeys(BaseSDK):
creator_user_id: OptionalNullable[str] = UNSET,
expires_at: OptionalNullable[datetime] = UNSET,
include_byok_in_limit: Optional[bool] = None,
limit: OptionalNullable[float] = UNSET,
limit: Optional[float] = None,
limit_reset: OptionalNullable[operations.CreateKeysLimitReset] = UNSET,
workspace_id: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -548,7 +541,6 @@ class APIKeys(BaseSDK):
:param include_byok_in_limit: Whether to include BYOK usage in the limit
:param limit: Optional spending limit for the API key in USD
:param limit_reset: Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.
:param workspace_id: The workspace to create the API key in. Defaults to the default workspace if not provided.
: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
@@ -575,7 +567,6 @@ class APIKeys(BaseSDK):
limit=limit,
limit_reset=limit_reset,
name=name,
workspace_id=workspace_id,
),
)
@@ -631,7 +622,7 @@ class APIKeys(BaseSDK):
),
),
request=req,
error_status_codes=["400", "401", "403", "429", "4XX", "500", "5XX"],
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
retry_config=retry_config,
)
@@ -648,11 +639,6 @@ class APIKeys(BaseSDK):
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "429", "application/json"):
response_data = unmarshal_json_response(
errors.TooManyRequestsResponseErrorData, http_res
@@ -686,9 +672,8 @@ class APIKeys(BaseSDK):
creator_user_id: OptionalNullable[str] = UNSET,
expires_at: OptionalNullable[datetime] = UNSET,
include_byok_in_limit: Optional[bool] = None,
limit: OptionalNullable[float] = UNSET,
limit: Optional[float] = None,
limit_reset: OptionalNullable[operations.CreateKeysLimitReset] = UNSET,
workspace_id: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
@@ -711,7 +696,6 @@ class APIKeys(BaseSDK):
:param include_byok_in_limit: Whether to include BYOK usage in the limit
:param limit: Optional spending limit for the API key in USD
:param limit_reset: Type of limit reset for the API key (daily, weekly, monthly, or null for no reset). Resets happen automatically at midnight UTC, and weeks are Monday through Sunday.
:param workspace_id: The workspace to create the API key in. Defaults to the default workspace if not provided.
: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
@@ -738,7 +722,6 @@ class APIKeys(BaseSDK):
limit=limit,
limit_reset=limit_reset,
name=name,
workspace_id=workspace_id,
),
)
@@ -794,7 +777,7 @@ class APIKeys(BaseSDK):
),
),
request=req,
error_status_codes=["400", "401", "403", "429", "4XX", "500", "5XX"],
error_status_codes=["400", "401", "429", "4XX", "500", "5XX"],
retry_config=retry_config,
)
@@ -811,11 +794,6 @@ class APIKeys(BaseSDK):
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "429", "application/json"):
response_data = unmarshal_json_response(
errors.TooManyRequestsResponseErrorData, http_res
@@ -1372,7 +1350,7 @@ class APIKeys(BaseSDK):
x_open_router_categories: Optional[str] = None,
disabled: Optional[bool] = None,
include_byok_in_limit: Optional[bool] = None,
limit: OptionalNullable[float] = UNSET,
limit: Optional[float] = None,
limit_reset: OptionalNullable[operations.UpdateKeysLimitReset] = UNSET,
name: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
@@ -1532,7 +1510,7 @@ class APIKeys(BaseSDK):
x_open_router_categories: Optional[str] = None,
disabled: Optional[bool] = None,
include_byok_in_limit: Optional[bool] = None,
limit: OptionalNullable[float] = UNSET,
limit: Optional[float] = None,
limit_reset: OptionalNullable[operations.UpdateKeysLimitReset] = UNSET,
name: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
-6
View File
@@ -2,14 +2,11 @@
from .basesdk import BaseSDK
from .sdkconfiguration import SDKConfiguration
from openrouter.beta_analytics import BetaAnalytics
from openrouter.responses import Responses
from typing import Optional
class Beta(BaseSDK):
analytics: BetaAnalytics
r"""beta.Analytics endpoints"""
responses: Responses
r"""beta.responses endpoints"""
@@ -21,7 +18,4 @@ class Beta(BaseSDK):
self._init_sdks()
def _init_sdks(self):
self.analytics = BetaAnalytics(
self.sdk_configuration, parent_ref=self.parent_ref
)
self.responses = Responses(self.sdk_configuration, parent_ref=self.parent_ref)
-619
View File
@@ -1,619 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from .basesdk import BaseSDK
from openrouter import components, errors, operations, utils
from openrouter._hooks import HookContext
from openrouter.types import OptionalNullable, UNSET
from openrouter.utils import get_security_from_env
from openrouter.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, List, Mapping, Optional, Union
class BetaAnalytics(BaseSDK):
r"""beta.Analytics endpoints"""
def get_analytics_meta(
self,
*,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetAnalyticsMetaResponse:
r"""Get available analytics metrics and dimensions
Returns the available metrics, dimensions, filter operators, and granularities for the analytics query endpoint. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param http_referer: 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.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = operations.GetAnalyticsMetaRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
)
req = self._build_request(
method="GET",
path="/analytics/meta",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.GetAnalyticsMetaGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getAnalyticsMeta",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "403", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
operations.GetAnalyticsMetaResponse, http_res
)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def get_analytics_meta_async(
self,
*,
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.GetAnalyticsMetaResponse:
r"""Get available analytics metrics and dimensions
Returns the available metrics, dimensions, filter operators, and granularities for the analytics query endpoint. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param http_referer: 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.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
: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 http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = operations.GetAnalyticsMetaRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
)
req = self._build_request_async(
method="GET",
path="/analytics/meta",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=False,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.GetAnalyticsMetaGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
allow_empty_value=None,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="getAnalyticsMeta",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["401", "403", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(
operations.GetAnalyticsMetaResponse, http_res
)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
def query_analytics(
self,
*,
metrics: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
dimensions: Optional[List[str]] = None,
filters: Optional[
Union[List[operations.Filter], List[operations.FilterTypedDict]]
] = None,
granularity: Optional[str] = None,
group_limit: Optional[int] = None,
limit: Optional[int] = None,
order_by: Optional[
Union[operations.OrderBy, operations.OrderByTypedDict]
] = None,
time_range: Optional[
Union[operations.TimeRange, operations.TimeRangeTypedDict]
] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.QueryAnalyticsResponse:
r"""Query analytics data
Execute an analytics query with specified metrics, dimensions, filters, and time range. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param metrics:
:param http_referer: 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.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param dimensions:
:param filters:
:param granularity: Time granularity
:param group_limit: Maximum rows per distinct combination of dimensions. When omitted on time-series queries (granularity + dimensions), auto-computed to avoid truncating time windows. Explicit values override the default and may truncate time buckets if set lower than the number of buckets in the range. Ignored when no dimensions are specified.
:param limit: Maximum total rows returned. Defaults to 1000. On time-series queries with dimensions and no explicit group_limit, the server may raise this to accommodate the expected number of unique time-bucket/dimension combinations.
:param order_by:
:param time_range:
: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 http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = operations.QueryAnalyticsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
request_body=operations.QueryAnalyticsRequestBody(
dimensions=dimensions,
filters=utils.get_pydantic_model(
filters, Optional[List[operations.Filter]]
),
granularity=granularity,
group_limit=group_limit,
limit=limit,
metrics=metrics,
order_by=utils.get_pydantic_model(
order_by, Optional[operations.OrderBy]
),
time_range=utils.get_pydantic_model(
time_range, Optional[operations.TimeRange]
),
),
)
req = self._build_request(
method="POST",
path="/analytics/query",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.QueryAnalyticsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.request_body,
False,
False,
"json",
operations.QueryAnalyticsRequestBody,
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = self.do_request(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="queryAnalytics",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "403", "408", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(operations.QueryAnalyticsResponse, http_res)
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "408", "application/json"):
response_data = unmarshal_json_response(
errors.RequestTimeoutResponseErrorData, http_res
)
raise errors.RequestTimeoutResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = utils.stream_to_text(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
async def query_analytics_async(
self,
*,
metrics: List[str],
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
dimensions: Optional[List[str]] = None,
filters: Optional[
Union[List[operations.Filter], List[operations.FilterTypedDict]]
] = None,
granularity: Optional[str] = None,
group_limit: Optional[int] = None,
limit: Optional[int] = None,
order_by: Optional[
Union[operations.OrderBy, operations.OrderByTypedDict]
] = None,
time_range: Optional[
Union[operations.TimeRange, operations.TimeRangeTypedDict]
] = None,
retries: OptionalNullable[utils.RetryConfig] = UNSET,
server_url: Optional[str] = None,
timeout_ms: Optional[int] = None,
http_headers: Optional[Mapping[str, str]] = None,
) -> operations.QueryAnalyticsResponse:
r"""Query analytics data
Execute an analytics query with specified metrics, dimensions, filters, and time range. [Management key](/docs/guides/overview/auth/management-api-keys) required.
:param metrics:
:param http_referer: 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.
:param x_open_router_title: The app display name allows you to customize how your app appears in OpenRouter's dashboard.
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param dimensions:
:param filters:
:param granularity: Time granularity
:param group_limit: Maximum rows per distinct combination of dimensions. When omitted on time-series queries (granularity + dimensions), auto-computed to avoid truncating time windows. Explicit values override the default and may truncate time buckets if set lower than the number of buckets in the range. Ignored when no dimensions are specified.
:param limit: Maximum total rows returned. Defaults to 1000. On time-series queries with dimensions and no explicit group_limit, the server may raise this to accommodate the expected number of unique time-bucket/dimension combinations.
:param order_by:
:param time_range:
: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 http_headers: Additional headers to set or replace on requests.
"""
base_url = None
url_variables = None
if timeout_ms is None:
timeout_ms = self.sdk_configuration.timeout_ms
if server_url is not None:
base_url = server_url
else:
base_url = self._get_url(base_url, url_variables)
request = operations.QueryAnalyticsRequest(
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
request_body=operations.QueryAnalyticsRequestBody(
dimensions=dimensions,
filters=utils.get_pydantic_model(
filters, Optional[List[operations.Filter]]
),
granularity=granularity,
group_limit=group_limit,
limit=limit,
metrics=metrics,
order_by=utils.get_pydantic_model(
order_by, Optional[operations.OrderBy]
),
time_range=utils.get_pydantic_model(
time_range, Optional[operations.TimeRange]
),
),
)
req = self._build_request_async(
method="POST",
path="/analytics/query",
base_url=base_url,
url_variables=url_variables,
request=request,
request_body_required=True,
request_has_path_params=False,
request_has_query_params=True,
user_agent_header="user-agent",
accept_header_value="application/json",
http_headers=http_headers,
_globals=operations.QueryAnalyticsGlobals(
http_referer=self.sdk_configuration.globals.http_referer,
x_open_router_title=self.sdk_configuration.globals.x_open_router_title,
x_open_router_categories=self.sdk_configuration.globals.x_open_router_categories,
),
security=self.sdk_configuration.security,
get_serialized_body=lambda: utils.serialize_request_body(
request.request_body,
False,
False,
"json",
operations.QueryAnalyticsRequestBody,
),
allow_empty_value=None,
timeout_ms=timeout_ms,
)
if retries == UNSET:
if self.sdk_configuration.retry_config is not UNSET:
retries = self.sdk_configuration.retry_config
else:
retries = utils.RetryConfig(
"backoff", utils.BackoffStrategy(500, 60000, 1.5, 3600000), True
)
retry_config = None
if isinstance(retries, utils.RetryConfig):
retry_config = (retries, ["5XX"])
http_res = await self.do_request_async(
hook_ctx=HookContext(
config=self.sdk_configuration,
base_url=base_url or "",
operation_id="queryAnalytics",
oauth2_scopes=None,
security_source=get_security_from_env(
self.sdk_configuration.security, components.Security
),
),
request=req,
error_status_codes=["400", "401", "403", "408", "4XX", "500", "5XX"],
retry_config=retry_config,
)
response_data: Any = None
if utils.match_response(http_res, "200", "application/json"):
return unmarshal_json_response(operations.QueryAnalyticsResponse, http_res)
if utils.match_response(http_res, "400", "application/json"):
response_data = unmarshal_json_response(
errors.BadRequestResponseErrorData, http_res
)
raise errors.BadRequestResponseError(response_data, http_res)
if utils.match_response(http_res, "401", "application/json"):
response_data = unmarshal_json_response(
errors.UnauthorizedResponseErrorData, http_res
)
raise errors.UnauthorizedResponseError(response_data, http_res)
if utils.match_response(http_res, "403", "application/json"):
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res
)
raise errors.ForbiddenResponseError(response_data, http_res)
if utils.match_response(http_res, "408", "application/json"):
response_data = unmarshal_json_response(
errors.RequestTimeoutResponseErrorData, http_res
)
raise errors.RequestTimeoutResponseError(response_data, http_res)
if utils.match_response(http_res, "500", "application/json"):
response_data = unmarshal_json_response(
errors.InternalServerResponseErrorData, http_res
)
raise errors.InternalServerResponseError(response_data, http_res)
if utils.match_response(http_res, "4XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
if utils.match_response(http_res, "5XX", "*"):
http_res_text = await utils.stream_to_text_async(http_res)
raise errors.OpenRouterDefaultError(
"API error occurred", http_res, http_res_text
)
raise errors.OpenRouterDefaultError("Unexpected response received", http_res)
File diff suppressed because it is too large Load Diff
+82 -260
View File
@@ -26,7 +26,6 @@ class Chat(BaseSDK):
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
x_open_router_metadata: Optional[components.MetadataLevel] = None,
cache_control: Optional[
Union[
components.AnthropicCacheControlDirective,
@@ -36,19 +35,18 @@ class Chat(BaseSDK):
debug: Optional[
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
frequency_penalty: Optional[float] = None,
image_config: Optional[
Union[
Dict[str, components.ImageConfig],
Dict[str, components.ImageConfigTypedDict],
Dict[str, components.ChatRequestImageConfig],
Dict[str, components.ChatRequestImageConfigTypedDict],
]
] = None,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
max_completion_tokens: OptionalNullable[int] = UNSET,
max_tokens: OptionalNullable[int] = UNSET,
max_completion_tokens: Optional[int] = None,
max_tokens: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
min_p: OptionalNullable[float] = UNSET,
modalities: Optional[List[components.Modality]] = None,
model: Optional[str] = None,
models: Optional[List[str]] = None,
@@ -59,42 +57,29 @@ class Chat(BaseSDK):
List[components.ChatRequestPluginTypedDict],
]
] = None,
presence_penalty: OptionalNullable[float] = UNSET,
presence_penalty: Optional[float] = None,
provider: OptionalNullable[
Union[
components.ProviderPreferences, components.ProviderPreferencesTypedDict
]
] = UNSET,
reasoning: Optional[
Union[
components.ChatRequestReasoning,
components.ChatRequestReasoningTypedDict,
]
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
reasoning_effort: OptionalNullable[
components.ChatRequestReasoningEffort
] = UNSET,
repetition_penalty: OptionalNullable[float] = UNSET,
response_format: Optional[
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
seed: Optional[int] = None,
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
session_id: Optional[str] = None,
stop: OptionalNullable[
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stop_server_tools_when: Optional[
Union[
List[components.StopServerToolsWhenCondition],
List[components.StopServerToolsWhenConditionTypedDict],
]
] = None,
stream: Union[Literal[False], None] = None,
stream_options: OptionalNullable[
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
temperature: Optional[float] = None,
tool_choice: Optional[
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
] = None,
@@ -104,10 +89,8 @@ class Chat(BaseSDK):
List[components.ChatFunctionToolTypedDict],
]
] = None,
top_a: OptionalNullable[float] = UNSET,
top_k: OptionalNullable[int] = UNSET,
top_logprobs: OptionalNullable[int] = UNSET,
top_p: OptionalNullable[float] = UNSET,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
trace: Optional[
Union[components.TraceConfig, components.TraceConfigTypedDict]
] = None,
@@ -129,8 +112,7 @@ class Chat(BaseSDK):
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
:param cache_control:
:param debug: Debug options for inspecting request transformations (streaming only)
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
@@ -139,7 +121,6 @@ class Chat(BaseSDK):
:param max_completion_tokens: Maximum tokens in completion
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
:param model: Model to use for completion
:param models: Models to use for completion
@@ -148,21 +129,16 @@ class Chat(BaseSDK):
:param presence_penalty: Presence penalty (-2.0 to 2.0)
:param provider: When multiple model providers are available, optionally indicate your routing preference.
:param reasoning: Configuration options for reasoning models
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
:param response_format: Response format configuration
:param seed: Random seed for deterministic outputs
:param service_tier: The service tier to use for processing this request.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param stop: Stop sequences (up to 4)
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
:param stream: Enable streaming response
:param stream_options: Streaming configuration options
:param temperature: Sampling temperature (0-2)
:param tool_choice: Tool choice configuration
:param tools: Available tools for function calling
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
:param top_logprobs: Number of top log probabilities to return (0-20)
:param top_p: Nucleus sampling parameter (0-1)
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
@@ -184,7 +160,6 @@ class Chat(BaseSDK):
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
x_open_router_metadata: Optional[components.MetadataLevel] = None,
cache_control: Optional[
Union[
components.AnthropicCacheControlDirective,
@@ -194,19 +169,18 @@ class Chat(BaseSDK):
debug: Optional[
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
frequency_penalty: Optional[float] = None,
image_config: Optional[
Union[
Dict[str, components.ImageConfig],
Dict[str, components.ImageConfigTypedDict],
Dict[str, components.ChatRequestImageConfig],
Dict[str, components.ChatRequestImageConfigTypedDict],
]
] = None,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
max_completion_tokens: OptionalNullable[int] = UNSET,
max_tokens: OptionalNullable[int] = UNSET,
max_completion_tokens: Optional[int] = None,
max_tokens: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
min_p: OptionalNullable[float] = UNSET,
modalities: Optional[List[components.Modality]] = None,
model: Optional[str] = None,
models: Optional[List[str]] = None,
@@ -217,42 +191,29 @@ class Chat(BaseSDK):
List[components.ChatRequestPluginTypedDict],
]
] = None,
presence_penalty: OptionalNullable[float] = UNSET,
presence_penalty: Optional[float] = None,
provider: OptionalNullable[
Union[
components.ProviderPreferences, components.ProviderPreferencesTypedDict
]
] = UNSET,
reasoning: Optional[
Union[
components.ChatRequestReasoning,
components.ChatRequestReasoningTypedDict,
]
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
reasoning_effort: OptionalNullable[
components.ChatRequestReasoningEffort
] = UNSET,
repetition_penalty: OptionalNullable[float] = UNSET,
response_format: Optional[
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
seed: Optional[int] = None,
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
session_id: Optional[str] = None,
stop: OptionalNullable[
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stop_server_tools_when: Optional[
Union[
List[components.StopServerToolsWhenCondition],
List[components.StopServerToolsWhenConditionTypedDict],
]
] = None,
stream: Literal[True],
stream_options: OptionalNullable[
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
temperature: Optional[float] = None,
tool_choice: Optional[
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
] = None,
@@ -262,10 +223,8 @@ class Chat(BaseSDK):
List[components.ChatFunctionToolTypedDict],
]
] = None,
top_a: OptionalNullable[float] = UNSET,
top_k: OptionalNullable[int] = UNSET,
top_logprobs: OptionalNullable[int] = UNSET,
top_p: OptionalNullable[float] = UNSET,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
trace: Optional[
Union[components.TraceConfig, components.TraceConfigTypedDict]
] = None,
@@ -287,8 +246,7 @@ class Chat(BaseSDK):
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
:param cache_control:
:param debug: Debug options for inspecting request transformations (streaming only)
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
@@ -297,7 +255,6 @@ class Chat(BaseSDK):
:param max_completion_tokens: Maximum tokens in completion
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
:param model: Model to use for completion
:param models: Models to use for completion
@@ -306,21 +263,16 @@ class Chat(BaseSDK):
:param presence_penalty: Presence penalty (-2.0 to 2.0)
:param provider: When multiple model providers are available, optionally indicate your routing preference.
:param reasoning: Configuration options for reasoning models
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
:param response_format: Response format configuration
:param seed: Random seed for deterministic outputs
:param service_tier: The service tier to use for processing this request.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param stop: Stop sequences (up to 4)
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
:param stream: Enable streaming response
:param stream_options: Streaming configuration options
:param temperature: Sampling temperature (0-2)
:param tool_choice: Tool choice configuration
:param tools: Available tools for function calling
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
:param top_logprobs: Number of top log probabilities to return (0-20)
:param top_p: Nucleus sampling parameter (0-1)
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
@@ -341,7 +293,6 @@ class Chat(BaseSDK):
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
x_open_router_metadata: Optional[components.MetadataLevel] = None,
cache_control: Optional[
Union[
components.AnthropicCacheControlDirective,
@@ -351,19 +302,18 @@ class Chat(BaseSDK):
debug: Optional[
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
frequency_penalty: Optional[float] = None,
image_config: Optional[
Union[
Dict[str, components.ImageConfig],
Dict[str, components.ImageConfigTypedDict],
Dict[str, components.ChatRequestImageConfig],
Dict[str, components.ChatRequestImageConfigTypedDict],
]
] = None,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
max_completion_tokens: OptionalNullable[int] = UNSET,
max_tokens: OptionalNullable[int] = UNSET,
max_completion_tokens: Optional[int] = None,
max_tokens: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
min_p: OptionalNullable[float] = UNSET,
modalities: Optional[List[components.Modality]] = None,
model: Optional[str] = None,
models: Optional[List[str]] = None,
@@ -374,42 +324,29 @@ class Chat(BaseSDK):
List[components.ChatRequestPluginTypedDict],
]
] = None,
presence_penalty: OptionalNullable[float] = UNSET,
presence_penalty: Optional[float] = None,
provider: OptionalNullable[
Union[
components.ProviderPreferences, components.ProviderPreferencesTypedDict
]
] = UNSET,
reasoning: Optional[
Union[
components.ChatRequestReasoning,
components.ChatRequestReasoningTypedDict,
]
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
reasoning_effort: OptionalNullable[
components.ChatRequestReasoningEffort
] = UNSET,
repetition_penalty: OptionalNullable[float] = UNSET,
response_format: Optional[
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
seed: Optional[int] = None,
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
session_id: Optional[str] = None,
stop: OptionalNullable[
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stop_server_tools_when: Optional[
Union[
List[components.StopServerToolsWhenCondition],
List[components.StopServerToolsWhenConditionTypedDict],
]
] = None,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
temperature: Optional[float] = None,
tool_choice: Optional[
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
] = None,
@@ -419,10 +356,8 @@ class Chat(BaseSDK):
List[components.ChatFunctionToolTypedDict],
]
] = None,
top_a: OptionalNullable[float] = UNSET,
top_k: OptionalNullable[int] = UNSET,
top_logprobs: OptionalNullable[int] = UNSET,
top_p: OptionalNullable[float] = UNSET,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
trace: Optional[
Union[components.TraceConfig, components.TraceConfigTypedDict]
] = None,
@@ -444,8 +379,7 @@ class Chat(BaseSDK):
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
:param cache_control:
:param debug: Debug options for inspecting request transformations (streaming only)
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
@@ -454,7 +388,6 @@ class Chat(BaseSDK):
:param max_completion_tokens: Maximum tokens in completion
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
:param model: Model to use for completion
:param models: Models to use for completion
@@ -463,21 +396,16 @@ class Chat(BaseSDK):
:param presence_penalty: Presence penalty (-2.0 to 2.0)
:param provider: When multiple model providers are available, optionally indicate your routing preference.
:param reasoning: Configuration options for reasoning models
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
:param response_format: Response format configuration
:param seed: Random seed for deterministic outputs
:param service_tier: The service tier to use for processing this request.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param stop: Stop sequences (up to 4)
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
:param stream: Enable streaming response
:param stream_options: Streaming configuration options
:param temperature: Sampling temperature (0-2)
:param tool_choice: Tool choice configuration
:param tools: Available tools for function calling
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
:param top_logprobs: Number of top log probabilities to return (0-20)
:param top_p: Nucleus sampling parameter (0-1)
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
@@ -502,7 +430,6 @@ class Chat(BaseSDK):
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
x_open_router_metadata=x_open_router_metadata,
chat_request=components.ChatRequest(
cache_control=utils.get_pydantic_model(
cache_control, Optional[components.AnthropicCacheControlDirective]
@@ -520,7 +447,6 @@ class Chat(BaseSDK):
messages, List[components.ChatMessages]
),
metadata=metadata,
min_p=min_p,
modalities=modalities,
model=model,
models=models,
@@ -533,10 +459,8 @@ class Chat(BaseSDK):
provider, OptionalNullable[components.ProviderPreferences]
),
reasoning=utils.get_pydantic_model(
reasoning, Optional[components.ChatRequestReasoning]
reasoning, Optional[components.Reasoning]
),
reasoning_effort=reasoning_effort,
repetition_penalty=repetition_penalty,
response_format=utils.get_pydantic_model(
response_format, Optional[components.ResponseFormat]
),
@@ -544,10 +468,6 @@ class Chat(BaseSDK):
service_tier=service_tier,
session_id=session_id,
stop=stop,
stop_server_tools_when=utils.get_pydantic_model(
stop_server_tools_when,
Optional[List[components.StopServerToolsWhenCondition]],
),
stream=stream,
stream_options=utils.get_pydantic_model(
stream_options, OptionalNullable[components.ChatStreamOptions]
@@ -559,8 +479,6 @@ class Chat(BaseSDK):
tools=utils.get_pydantic_model(
tools, Optional[List[components.ChatFunctionTool]]
),
top_a=top_a,
top_k=top_k,
top_logprobs=top_logprobs,
top_p=top_p,
trace=utils.get_pydantic_model(trace, Optional[components.TraceConfig]),
@@ -620,7 +538,6 @@ class Chat(BaseSDK):
"400",
"401",
"402",
"403",
"404",
"408",
"413",
@@ -648,7 +565,7 @@ class Chat(BaseSDK):
return eventstreaming.EventStream(
http_res,
lambda raw: utils.unmarshal_json(
raw, components.ChatStreamingResponse
raw, operations.SendChatCompletionRequestResponseBody
).data,
sentinel="[DONE]",
client_ref=self,
@@ -675,12 +592,6 @@ class Chat(BaseSDK):
raise errors.PaymentRequiredResponseError(
response_data, http_res, http_res_text
)
if utils.match_response(http_res, "403", "application/json"):
http_res_text = utils.stream_to_text(http_res)
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res, http_res_text
)
raise errors.ForbiddenResponseError(response_data, http_res, http_res_text)
if utils.match_response(http_res, "404", "application/json"):
http_res_text = utils.stream_to_text(http_res)
response_data = unmarshal_json_response(
@@ -783,7 +694,6 @@ class Chat(BaseSDK):
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
x_open_router_metadata: Optional[components.MetadataLevel] = None,
cache_control: Optional[
Union[
components.AnthropicCacheControlDirective,
@@ -793,19 +703,18 @@ class Chat(BaseSDK):
debug: Optional[
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
frequency_penalty: Optional[float] = None,
image_config: Optional[
Union[
Dict[str, components.ImageConfig],
Dict[str, components.ImageConfigTypedDict],
Dict[str, components.ChatRequestImageConfig],
Dict[str, components.ChatRequestImageConfigTypedDict],
]
] = None,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
max_completion_tokens: OptionalNullable[int] = UNSET,
max_tokens: OptionalNullable[int] = UNSET,
max_completion_tokens: Optional[int] = None,
max_tokens: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
min_p: OptionalNullable[float] = UNSET,
modalities: Optional[List[components.Modality]] = None,
model: Optional[str] = None,
models: Optional[List[str]] = None,
@@ -816,42 +725,29 @@ class Chat(BaseSDK):
List[components.ChatRequestPluginTypedDict],
]
] = None,
presence_penalty: OptionalNullable[float] = UNSET,
presence_penalty: Optional[float] = None,
provider: OptionalNullable[
Union[
components.ProviderPreferences, components.ProviderPreferencesTypedDict
]
] = UNSET,
reasoning: Optional[
Union[
components.ChatRequestReasoning,
components.ChatRequestReasoningTypedDict,
]
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
reasoning_effort: OptionalNullable[
components.ChatRequestReasoningEffort
] = UNSET,
repetition_penalty: OptionalNullable[float] = UNSET,
response_format: Optional[
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
seed: Optional[int] = None,
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
session_id: Optional[str] = None,
stop: OptionalNullable[
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stop_server_tools_when: Optional[
Union[
List[components.StopServerToolsWhenCondition],
List[components.StopServerToolsWhenConditionTypedDict],
]
] = None,
stream: Union[Literal[False], None] = None,
stream_options: OptionalNullable[
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
temperature: Optional[float] = None,
tool_choice: Optional[
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
] = None,
@@ -861,10 +757,8 @@ class Chat(BaseSDK):
List[components.ChatFunctionToolTypedDict],
]
] = None,
top_a: OptionalNullable[float] = UNSET,
top_k: OptionalNullable[int] = UNSET,
top_logprobs: OptionalNullable[int] = UNSET,
top_p: OptionalNullable[float] = UNSET,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
trace: Optional[
Union[components.TraceConfig, components.TraceConfigTypedDict]
] = None,
@@ -886,8 +780,7 @@ class Chat(BaseSDK):
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
:param cache_control:
:param debug: Debug options for inspecting request transformations (streaming only)
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
@@ -896,7 +789,6 @@ class Chat(BaseSDK):
:param max_completion_tokens: Maximum tokens in completion
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
:param model: Model to use for completion
:param models: Models to use for completion
@@ -905,21 +797,16 @@ class Chat(BaseSDK):
:param presence_penalty: Presence penalty (-2.0 to 2.0)
:param provider: When multiple model providers are available, optionally indicate your routing preference.
:param reasoning: Configuration options for reasoning models
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
:param response_format: Response format configuration
:param seed: Random seed for deterministic outputs
:param service_tier: The service tier to use for processing this request.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param stop: Stop sequences (up to 4)
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
:param stream: Enable streaming response
:param stream_options: Streaming configuration options
:param temperature: Sampling temperature (0-2)
:param tool_choice: Tool choice configuration
:param tools: Available tools for function calling
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
:param top_logprobs: Number of top log probabilities to return (0-20)
:param top_p: Nucleus sampling parameter (0-1)
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
@@ -941,7 +828,6 @@ class Chat(BaseSDK):
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
x_open_router_metadata: Optional[components.MetadataLevel] = None,
cache_control: Optional[
Union[
components.AnthropicCacheControlDirective,
@@ -951,19 +837,18 @@ class Chat(BaseSDK):
debug: Optional[
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
frequency_penalty: Optional[float] = None,
image_config: Optional[
Union[
Dict[str, components.ImageConfig],
Dict[str, components.ImageConfigTypedDict],
Dict[str, components.ChatRequestImageConfig],
Dict[str, components.ChatRequestImageConfigTypedDict],
]
] = None,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
max_completion_tokens: OptionalNullable[int] = UNSET,
max_tokens: OptionalNullable[int] = UNSET,
max_completion_tokens: Optional[int] = None,
max_tokens: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
min_p: OptionalNullable[float] = UNSET,
modalities: Optional[List[components.Modality]] = None,
model: Optional[str] = None,
models: Optional[List[str]] = None,
@@ -974,42 +859,29 @@ class Chat(BaseSDK):
List[components.ChatRequestPluginTypedDict],
]
] = None,
presence_penalty: OptionalNullable[float] = UNSET,
presence_penalty: Optional[float] = None,
provider: OptionalNullable[
Union[
components.ProviderPreferences, components.ProviderPreferencesTypedDict
]
] = UNSET,
reasoning: Optional[
Union[
components.ChatRequestReasoning,
components.ChatRequestReasoningTypedDict,
]
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
reasoning_effort: OptionalNullable[
components.ChatRequestReasoningEffort
] = UNSET,
repetition_penalty: OptionalNullable[float] = UNSET,
response_format: Optional[
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
seed: Optional[int] = None,
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
session_id: Optional[str] = None,
stop: OptionalNullable[
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stop_server_tools_when: Optional[
Union[
List[components.StopServerToolsWhenCondition],
List[components.StopServerToolsWhenConditionTypedDict],
]
] = None,
stream: Literal[True],
stream_options: OptionalNullable[
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
temperature: Optional[float] = None,
tool_choice: Optional[
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
] = None,
@@ -1019,10 +891,8 @@ class Chat(BaseSDK):
List[components.ChatFunctionToolTypedDict],
]
] = None,
top_a: OptionalNullable[float] = UNSET,
top_k: OptionalNullable[int] = UNSET,
top_logprobs: OptionalNullable[int] = UNSET,
top_p: OptionalNullable[float] = UNSET,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
trace: Optional[
Union[components.TraceConfig, components.TraceConfigTypedDict]
] = None,
@@ -1044,8 +914,7 @@ class Chat(BaseSDK):
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
:param cache_control:
:param debug: Debug options for inspecting request transformations (streaming only)
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
@@ -1054,7 +923,6 @@ class Chat(BaseSDK):
:param max_completion_tokens: Maximum tokens in completion
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
:param model: Model to use for completion
:param models: Models to use for completion
@@ -1063,21 +931,16 @@ class Chat(BaseSDK):
:param presence_penalty: Presence penalty (-2.0 to 2.0)
:param provider: When multiple model providers are available, optionally indicate your routing preference.
:param reasoning: Configuration options for reasoning models
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
:param response_format: Response format configuration
:param seed: Random seed for deterministic outputs
:param service_tier: The service tier to use for processing this request.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param stop: Stop sequences (up to 4)
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
:param stream: Enable streaming response
:param stream_options: Streaming configuration options
:param temperature: Sampling temperature (0-2)
:param tool_choice: Tool choice configuration
:param tools: Available tools for function calling
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
:param top_logprobs: Number of top log probabilities to return (0-20)
:param top_p: Nucleus sampling parameter (0-1)
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
@@ -1098,7 +961,6 @@ class Chat(BaseSDK):
http_referer: Optional[str] = None,
x_open_router_title: Optional[str] = None,
x_open_router_categories: Optional[str] = None,
x_open_router_metadata: Optional[components.MetadataLevel] = None,
cache_control: Optional[
Union[
components.AnthropicCacheControlDirective,
@@ -1108,19 +970,18 @@ class Chat(BaseSDK):
debug: Optional[
Union[components.ChatDebugOptions, components.ChatDebugOptionsTypedDict]
] = None,
frequency_penalty: OptionalNullable[float] = UNSET,
frequency_penalty: Optional[float] = None,
image_config: Optional[
Union[
Dict[str, components.ImageConfig],
Dict[str, components.ImageConfigTypedDict],
Dict[str, components.ChatRequestImageConfig],
Dict[str, components.ChatRequestImageConfigTypedDict],
]
] = None,
logit_bias: OptionalNullable[Dict[str, float]] = UNSET,
logprobs: OptionalNullable[bool] = UNSET,
max_completion_tokens: OptionalNullable[int] = UNSET,
max_tokens: OptionalNullable[int] = UNSET,
max_completion_tokens: Optional[int] = None,
max_tokens: Optional[int] = None,
metadata: Optional[Dict[str, str]] = None,
min_p: OptionalNullable[float] = UNSET,
modalities: Optional[List[components.Modality]] = None,
model: Optional[str] = None,
models: Optional[List[str]] = None,
@@ -1131,42 +992,29 @@ class Chat(BaseSDK):
List[components.ChatRequestPluginTypedDict],
]
] = None,
presence_penalty: OptionalNullable[float] = UNSET,
presence_penalty: Optional[float] = None,
provider: OptionalNullable[
Union[
components.ProviderPreferences, components.ProviderPreferencesTypedDict
]
] = UNSET,
reasoning: Optional[
Union[
components.ChatRequestReasoning,
components.ChatRequestReasoningTypedDict,
]
Union[components.Reasoning, components.ReasoningTypedDict]
] = None,
reasoning_effort: OptionalNullable[
components.ChatRequestReasoningEffort
] = UNSET,
repetition_penalty: OptionalNullable[float] = UNSET,
response_format: Optional[
Union[components.ResponseFormat, components.ResponseFormatTypedDict]
] = None,
seed: OptionalNullable[int] = UNSET,
seed: Optional[int] = None,
service_tier: OptionalNullable[components.ChatRequestServiceTier] = UNSET,
session_id: Optional[str] = None,
stop: OptionalNullable[
Union[components.Stop, components.StopTypedDict]
] = UNSET,
stop_server_tools_when: Optional[
Union[
List[components.StopServerToolsWhenCondition],
List[components.StopServerToolsWhenConditionTypedDict],
]
] = None,
stream: Optional[bool] = False,
stream_options: OptionalNullable[
Union[components.ChatStreamOptions, components.ChatStreamOptionsTypedDict]
] = UNSET,
temperature: OptionalNullable[float] = UNSET,
temperature: Optional[float] = None,
tool_choice: Optional[
Union[components.ChatToolChoice, components.ChatToolChoiceTypedDict]
] = None,
@@ -1176,10 +1024,8 @@ class Chat(BaseSDK):
List[components.ChatFunctionToolTypedDict],
]
] = None,
top_a: OptionalNullable[float] = UNSET,
top_k: OptionalNullable[int] = UNSET,
top_logprobs: OptionalNullable[int] = UNSET,
top_p: OptionalNullable[float] = UNSET,
top_logprobs: Optional[int] = None,
top_p: Optional[float] = None,
trace: Optional[
Union[components.TraceConfig, components.TraceConfigTypedDict]
] = None,
@@ -1201,8 +1047,7 @@ class Chat(BaseSDK):
:param x_open_router_categories: Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings.
:param x_open_router_metadata: Opt-in to surface routing metadata on the response under `openrouter_metadata`. Defaults to `disabled`. The legacy header `X-OpenRouter-Experimental-Metadata` is also accepted for backward compatibility.
:param cache_control: Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models.
:param cache_control:
:param debug: Debug options for inspecting request transformations (streaming only)
:param frequency_penalty: Frequency penalty (-2.0 to 2.0)
:param image_config: Provider-specific image configuration options. Keys and values vary by model/provider. See https://openrouter.ai/docs/guides/overview/multimodal/image-generation for more details.
@@ -1211,7 +1056,6 @@ class Chat(BaseSDK):
:param max_completion_tokens: Maximum tokens in completion
:param max_tokens: Maximum tokens (deprecated, use max_completion_tokens). Note: some providers enforce a minimum of 16.
:param metadata: Key-value pairs for additional object information (max 16 pairs, 64 char keys, 512 char values)
:param min_p: Minimum probability threshold relative to the most likely token. Tokens with probability below min_p * (probability of top token) are filtered out. Not all providers support this parameter.
:param modalities: Output modalities for the response. Supported values are \"text\", \"image\", and \"audio\".
:param model: Model to use for completion
:param models: Models to use for completion
@@ -1220,21 +1064,16 @@ class Chat(BaseSDK):
:param presence_penalty: Presence penalty (-2.0 to 2.0)
:param provider: When multiple model providers are available, optionally indicate your routing preference.
:param reasoning: Configuration options for reasoning models
:param reasoning_effort: Shorthand for setting reasoning effort. Equivalent to setting reasoning.effort. Cannot be used simultaneously with reasoning.effort if they differ.
:param repetition_penalty: Penalizes tokens based on how much they have already appeared in the text. A value of 1.0 means no penalty. Values above 1.0 penalize repeated tokens more strongly. Not all providers support this parameter.
:param response_format: Response format configuration
:param seed: Random seed for deterministic outputs
:param service_tier: The service tier to use for processing this request.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow). When provided, OpenRouter uses it as the sticky routing key, routing all requests in the session to the same provider to maximize prompt cache hits. Also used for observability grouping. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param session_id: A unique identifier for grouping related requests (e.g., a conversation or agent workflow) for observability. If provided in both the request body and the x-session-id header, the body value takes precedence. Maximum of 256 characters.
:param stop: Stop sequences (up to 4)
:param stop_server_tools_when: Stop conditions for the server-tool agent loop. Any condition firing halts the loop (OR logic). When set, this overrides `max_tool_calls`.
:param stream: Enable streaming response
:param stream_options: Streaming configuration options
:param temperature: Sampling temperature (0-2)
:param tool_choice: Tool choice configuration
:param tools: Available tools for function calling
:param top_a: Consider only tokens with \"sufficiently high\" probabilities based on the probability of the most likely token. Not all providers support this parameter.
:param top_k: Limits the model to choose from the top K most likely tokens at each step. A value of 1 means the model will always pick the most likely next token. Not all providers support this parameter.
:param top_logprobs: Number of top log probabilities to return (0-20)
:param top_p: Nucleus sampling parameter (0-1)
:param trace: Metadata for observability and tracing. Known keys (trace_id, trace_name, span_name, generation_name, parent_span_id) have special handling. Additional keys are passed through as custom metadata to configured broadcast destinations.
@@ -1259,7 +1098,6 @@ class Chat(BaseSDK):
http_referer=http_referer,
x_open_router_title=x_open_router_title,
x_open_router_categories=x_open_router_categories,
x_open_router_metadata=x_open_router_metadata,
chat_request=components.ChatRequest(
cache_control=utils.get_pydantic_model(
cache_control, Optional[components.AnthropicCacheControlDirective]
@@ -1277,7 +1115,6 @@ class Chat(BaseSDK):
messages, List[components.ChatMessages]
),
metadata=metadata,
min_p=min_p,
modalities=modalities,
model=model,
models=models,
@@ -1290,10 +1127,8 @@ class Chat(BaseSDK):
provider, OptionalNullable[components.ProviderPreferences]
),
reasoning=utils.get_pydantic_model(
reasoning, Optional[components.ChatRequestReasoning]
reasoning, Optional[components.Reasoning]
),
reasoning_effort=reasoning_effort,
repetition_penalty=repetition_penalty,
response_format=utils.get_pydantic_model(
response_format, Optional[components.ResponseFormat]
),
@@ -1301,10 +1136,6 @@ class Chat(BaseSDK):
service_tier=service_tier,
session_id=session_id,
stop=stop,
stop_server_tools_when=utils.get_pydantic_model(
stop_server_tools_when,
Optional[List[components.StopServerToolsWhenCondition]],
),
stream=stream,
stream_options=utils.get_pydantic_model(
stream_options, OptionalNullable[components.ChatStreamOptions]
@@ -1316,8 +1147,6 @@ class Chat(BaseSDK):
tools=utils.get_pydantic_model(
tools, Optional[List[components.ChatFunctionTool]]
),
top_a=top_a,
top_k=top_k,
top_logprobs=top_logprobs,
top_p=top_p,
trace=utils.get_pydantic_model(trace, Optional[components.TraceConfig]),
@@ -1377,7 +1206,6 @@ class Chat(BaseSDK):
"400",
"401",
"402",
"403",
"404",
"408",
"413",
@@ -1405,7 +1233,7 @@ class Chat(BaseSDK):
return eventstreaming.EventStreamAsync(
http_res,
lambda raw: utils.unmarshal_json(
raw, components.ChatStreamingResponse
raw, operations.SendChatCompletionRequestResponseBody
).data,
sentinel="[DONE]",
client_ref=self,
@@ -1432,12 +1260,6 @@ class Chat(BaseSDK):
raise errors.PaymentRequiredResponseError(
response_data, http_res, http_res_text
)
if utils.match_response(http_res, "403", "application/json"):
http_res_text = await utils.stream_to_text_async(http_res)
response_data = unmarshal_json_response(
errors.ForbiddenResponseErrorData, http_res, http_res_text
)
raise errors.ForbiddenResponseError(response_data, http_res, http_res_text)
if utils.match_response(http_res, "404", "application/json"):
http_res_text = await utils.stream_to_text_async(http_res)
response_data = unmarshal_json_response(
File diff suppressed because it is too large Load Diff
@@ -1,60 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
from pydantic import model_serializer
from typing_extensions import TypedDict
class AABenchmarkEntryTypedDict(TypedDict):
r"""Artificial Analysis benchmark index scores."""
agentic_index: Nullable[float]
r"""Artificial Analysis Agentic Index score"""
coding_index: Nullable[float]
r"""Artificial Analysis Coding Index score"""
intelligence_index: Nullable[float]
r"""Artificial Analysis Intelligence Index score"""
class AABenchmarkEntry(BaseModel):
r"""Artificial Analysis benchmark index scores."""
agentic_index: Nullable[float]
r"""Artificial Analysis Agentic Index score"""
coding_index: Nullable[float]
r"""Artificial Analysis Coding Index score"""
intelligence_index: Nullable[float]
r"""Artificial Analysis Intelligence Index score"""
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["agentic_index", "coding_index", "intelligence_index"]
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,36 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable
import pydantic
from pydantic import ConfigDict
from typing import Any, Dict, Optional
from typing_extensions import NotRequired, TypedDict
class AdvisorNestedToolTypedDict(TypedDict):
r"""A tool made available to the advisor sub-agent. Only OpenRouter server tools (e.g. openrouter:web_search) are supported; function tools are rejected because the advisor has no way to execute them. The advisor tool may not list itself."""
type: str
parameters: NotRequired[Dict[str, Nullable[Any]]]
class AdvisorNestedTool(BaseModel):
r"""A tool made available to the advisor sub-agent. Only OpenRouter server tools (e.g. openrouter:web_search) are supported; function tools are rejected because the advisor has no way to execute them. The advisor tool may not list itself."""
model_config = ConfigDict(
populate_by_name=True, arbitrary_types_allowed=True, extra="allow"
)
__pydantic_extra__: Dict[str, Nullable[Any]] = pydantic.Field(init=False)
type: str
parameters: Optional[Dict[str, Nullable[Any]]] = None
@property
def additional_properties(self):
return self.__pydantic_extra__
@additional_properties.setter
def additional_properties(self, value):
self.__pydantic_extra__ = value # pyright: ignore[reportIncompatibleVariableOverride]
@@ -1,43 +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_open_enum
from pydantic.functional_validators import PlainValidator
from typing import Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypedDict
AdvisorReasoningEffort = Union[
Literal[
"xhigh",
"high",
"medium",
"low",
"minimal",
"none",
],
UnrecognizedStr,
]
r"""Reasoning effort level for the advisor call."""
class AdvisorReasoningTypedDict(TypedDict):
r"""Reasoning configuration forwarded to the advisor call. Use this to control reasoning effort and token budget for models that support extended thinking."""
effort: NotRequired[AdvisorReasoningEffort]
r"""Reasoning effort level for the advisor call."""
max_tokens: NotRequired[int]
r"""Maximum number of reasoning tokens the advisor may use."""
class AdvisorReasoning(BaseModel):
r"""Reasoning configuration forwarded to the advisor call. Use this to control reasoning effort and token budget for models that support extended thinking."""
effort: Annotated[
Optional[AdvisorReasoningEffort], PlainValidator(validate_open_enum(False))
] = None
r"""Reasoning effort level for the advisor call."""
max_tokens: Optional[int] = None
r"""Maximum number of reasoning tokens the advisor may use."""
@@ -1,30 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .advisorservertoolconfig import (
AdvisorServerToolConfig,
AdvisorServerToolConfigTypedDict,
)
from openrouter.types import BaseModel
from typing import Literal, Optional
from typing_extensions import NotRequired, TypedDict
AdvisorServerToolOpenRouterType = Literal["openrouter:advisor",]
class AdvisorServerToolOpenRouterTypedDict(TypedDict):
r"""OpenRouter built-in server tool: consults a higher-intelligence advisor model (any OpenRouter model) for guidance mid-generation and returns its response. The advisor may run as a sub-agent with its own tools. Include multiple entries to offer several named advisors; at most one entry may omit `name` to act as the default advisor."""
type: AdvisorServerToolOpenRouterType
parameters: NotRequired[AdvisorServerToolConfigTypedDict]
r"""Configuration for one openrouter:advisor server tool entry."""
class AdvisorServerToolOpenRouter(BaseModel):
r"""OpenRouter built-in server tool: consults a higher-intelligence advisor model (any OpenRouter model) for guidance mid-generation and returns its response. The advisor may run as a sub-agent with its own tools. Include multiple entries to offer several named advisors; at most one entry may omit `name` to act as the default advisor."""
type: AdvisorServerToolOpenRouterType
parameters: Optional[AdvisorServerToolConfig] = None
r"""Configuration for one openrouter:advisor server tool entry."""
@@ -1,67 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .advisornestedtool import AdvisorNestedTool, AdvisorNestedToolTypedDict
from .advisorreasoning import AdvisorReasoning, AdvisorReasoningTypedDict
from openrouter.types import BaseModel
from typing import List, Optional
from typing_extensions import NotRequired, TypedDict
class AdvisorServerToolConfigTypedDict(TypedDict):
r"""Configuration for one openrouter:advisor server tool entry."""
forward_transcript: NotRequired[bool]
r"""When true, the full parent conversation is forwarded to the advisor so it sees the same context the executor does (and the tool-call `prompt`, if given, is appended as a final user turn). When false or omitted, the advisor receives only the `prompt` the executor passes in the tool call."""
instructions: NotRequired[str]
r"""System instructions for the advisor sub-agent. When omitted, the advisor responds with no system prompt of its own."""
max_completion_tokens: NotRequired[int]
r"""Maximum number of output tokens (including reasoning) the advisor may produce. When omitted, the provider's default applies."""
max_tool_calls: NotRequired[int]
r"""Maximum number of tool-calling steps the advisor sub-agent may take during its agentic loop. Capped at 25. Only relevant when the advisor is given tools."""
model: NotRequired[str]
r"""Slug of the advisor model to consult (any OpenRouter model). When omitted, the executor can choose it via the tool call's `model` argument; if neither is set, the model from the outer API request is used. The advisor tool itself cannot be the advisor model."""
name: NotRequired[str]
r"""Optional name for this advisor. The model sees one tool per named advisor (and one default for an unnamed entry). Names must be unique across advisor entries. Letters, digits, spaces, underscores, and dashes; trimmed; 164 chars."""
reasoning: NotRequired[AdvisorReasoningTypedDict]
r"""Reasoning configuration forwarded to the advisor call. Use this to control reasoning effort and token budget for models that support extended thinking."""
stream: NotRequired[bool]
r"""When true, the advisor's advice streams incrementally as it is produced. In the Responses API this emits `response.output_text.delta` events targeting the advisor output item; the final `advice` field is still set on the completed item. Has no effect on the Chat Completions API (where the advice arrives only as the final tool result). When false or omitted, the advice arrives only as the final result."""
temperature: NotRequired[float]
r"""Sampling temperature forwarded to the advisor call. When omitted, the provider's default applies."""
tools: NotRequired[List[AdvisorNestedToolTypedDict]]
r"""Tools the advisor sub-agent may use while forming its advice. The advisor runs as an agentic sub-agent over these tools, then returns its text. Only OpenRouter server tools are supported — function tools are rejected — and the list must not include the advisor tool itself."""
class AdvisorServerToolConfig(BaseModel):
r"""Configuration for one openrouter:advisor server tool entry."""
forward_transcript: Optional[bool] = None
r"""When true, the full parent conversation is forwarded to the advisor so it sees the same context the executor does (and the tool-call `prompt`, if given, is appended as a final user turn). When false or omitted, the advisor receives only the `prompt` the executor passes in the tool call."""
instructions: Optional[str] = None
r"""System instructions for the advisor sub-agent. When omitted, the advisor responds with no system prompt of its own."""
max_completion_tokens: Optional[int] = None
r"""Maximum number of output tokens (including reasoning) the advisor may produce. When omitted, the provider's default applies."""
max_tool_calls: Optional[int] = None
r"""Maximum number of tool-calling steps the advisor sub-agent may take during its agentic loop. Capped at 25. Only relevant when the advisor is given tools."""
model: Optional[str] = None
r"""Slug of the advisor model to consult (any OpenRouter model). When omitted, the executor can choose it via the tool call's `model` argument; if neither is set, the model from the outer API request is used. The advisor tool itself cannot be the advisor model."""
name: Optional[str] = None
r"""Optional name for this advisor. The model sees one tool per named advisor (and one default for an unnamed entry). Names must be unique across advisor entries. Letters, digits, spaces, underscores, and dashes; trimmed; 164 chars."""
reasoning: Optional[AdvisorReasoning] = None
r"""Reasoning configuration forwarded to the advisor call. Use this to control reasoning effort and token budget for models that support extended thinking."""
stream: Optional[bool] = None
r"""When true, the advisor's advice streams incrementally as it is produced. In the Responses API this emits `response.output_text.delta` events targeting the advisor output item; the final `advice` field is still set on the completed item. Has no effect on the Chat Completions API (where the advice arrives only as the final tool result). When false or omitted, the advice arrives only as the final result."""
temperature: Optional[float] = None
r"""Sampling temperature forwarded to the advisor call. When omitted, the provider's default applies."""
tools: Optional[List[AdvisorNestedTool]] = None
r"""Tools the advisor sub-agent may use while forming its advice. The advisor runs as an agentic sub-agent over these tools, then returns its text. Only OpenRouter server tools are supported — function tools are rejected — and the list must not include the advisor tool itself."""
@@ -1,15 +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
AnthropicAllowedCallers = Union[
Literal[
"direct",
"code_execution_20250825",
"code_execution_20260120",
],
UnrecognizedStr,
]
@@ -1,28 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .anthropicimagemimetype import AnthropicImageMimeType
from openrouter.types import BaseModel
from openrouter.utils import validate_open_enum
from pydantic.functional_validators import PlainValidator
from typing import Literal
from typing_extensions import Annotated, TypedDict
AnthropicBase64ImageSourceType = Literal["base64",]
class AnthropicBase64ImageSourceTypedDict(TypedDict):
data: str
media_type: AnthropicImageMimeType
type: AnthropicBase64ImageSourceType
class AnthropicBase64ImageSource(BaseModel):
data: str
media_type: Annotated[
AnthropicImageMimeType, PlainValidator(validate_open_enum(False))
]
type: AnthropicBase64ImageSourceType
@@ -1,26 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel
from typing import Literal
from typing_extensions import TypedDict
AnthropicBase64PdfSourceMediaType = Literal["application/pdf",]
AnthropicBase64PdfSourceType = Literal["base64",]
class AnthropicBase64PdfSourceTypedDict(TypedDict):
data: str
media_type: AnthropicBase64PdfSourceMediaType
type: AnthropicBase64PdfSourceType
class AnthropicBase64PdfSource(BaseModel):
data: str
media_type: AnthropicBase64PdfSourceMediaType
type: AnthropicBase64PdfSourceType
@@ -13,14 +13,14 @@ AnthropicCacheControlDirectiveType = Literal["ephemeral",]
class AnthropicCacheControlDirectiveTypedDict(TypedDict):
r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""
r"""Enable automatic prompt caching. When set, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""
type: AnthropicCacheControlDirectiveType
ttl: NotRequired[AnthropicCacheControlTTL]
class AnthropicCacheControlDirective(BaseModel):
r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""
r"""Enable automatic prompt caching. When set, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""
type: AnthropicCacheControlDirectiveType
@@ -1,63 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
from pydantic import model_serializer
from typing import Literal
from typing_extensions import TypedDict
AnthropicCitationCharLocationParamType = Literal["char_location",]
class AnthropicCitationCharLocationParamTypedDict(TypedDict):
cited_text: str
document_index: int
document_title: Nullable[str]
end_char_index: int
start_char_index: int
type: AnthropicCitationCharLocationParamType
class AnthropicCitationCharLocationParam(BaseModel):
cited_text: str
document_index: int
document_title: Nullable[str]
end_char_index: int
start_char_index: int
type: AnthropicCitationCharLocationParamType
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["document_title"]
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,63 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
from pydantic import model_serializer
from typing import Literal
from typing_extensions import TypedDict
AnthropicCitationContentBlockLocationParamType = Literal["content_block_location",]
class AnthropicCitationContentBlockLocationParamTypedDict(TypedDict):
cited_text: str
document_index: int
document_title: Nullable[str]
end_block_index: int
start_block_index: int
type: AnthropicCitationContentBlockLocationParamType
class AnthropicCitationContentBlockLocationParam(BaseModel):
cited_text: str
document_index: int
document_title: Nullable[str]
end_block_index: int
start_block_index: int
type: AnthropicCitationContentBlockLocationParamType
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["document_title"]
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,63 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
from pydantic import model_serializer
from typing import Literal
from typing_extensions import TypedDict
AnthropicCitationPageLocationParamType = Literal["page_location",]
class AnthropicCitationPageLocationParamTypedDict(TypedDict):
cited_text: str
document_index: int
document_title: Nullable[str]
end_page_number: int
start_page_number: int
type: AnthropicCitationPageLocationParamType
class AnthropicCitationPageLocationParam(BaseModel):
cited_text: str
document_index: int
document_title: Nullable[str]
end_page_number: int
start_page_number: int
type: AnthropicCitationPageLocationParamType
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["document_title"]
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,66 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
from pydantic import model_serializer
from typing import Literal
from typing_extensions import TypedDict
AnthropicCitationSearchResultLocationType = Literal["search_result_location",]
class AnthropicCitationSearchResultLocationTypedDict(TypedDict):
cited_text: str
end_block_index: int
search_result_index: int
source: str
start_block_index: int
title: Nullable[str]
type: AnthropicCitationSearchResultLocationType
class AnthropicCitationSearchResultLocation(BaseModel):
cited_text: str
end_block_index: int
search_result_index: int
source: str
start_block_index: int
title: Nullable[str]
type: AnthropicCitationSearchResultLocationType
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["title"]
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,60 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from openrouter.types import BaseModel, Nullable, UNSET_SENTINEL
from pydantic import model_serializer
from typing import Literal
from typing_extensions import TypedDict
AnthropicCitationWebSearchResultLocationType = Literal["web_search_result_location",]
class AnthropicCitationWebSearchResultLocationTypedDict(TypedDict):
cited_text: str
encrypted_index: str
title: Nullable[str]
type: AnthropicCitationWebSearchResultLocationType
url: str
class AnthropicCitationWebSearchResultLocation(BaseModel):
cited_text: str
encrypted_index: str
title: Nullable[str]
type: AnthropicCitationWebSearchResultLocationType
url: str
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = []
nullable_fields = ["title"]
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,170 +0,0 @@
"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
from __future__ import annotations
from .anthropicbase64pdfsource import (
AnthropicBase64PdfSource,
AnthropicBase64PdfSourceTypedDict,
)
from .anthropiccachecontroldirective import (
AnthropicCacheControlDirective,
AnthropicCacheControlDirectiveTypedDict,
)
from .anthropicfiledocumentsource import (
AnthropicFileDocumentSource,
AnthropicFileDocumentSourceTypedDict,
)
from .anthropicimageblockparam import (
AnthropicImageBlockParam,
AnthropicImageBlockParamTypedDict,
)
from .anthropicplaintextsource import (
AnthropicPlainTextSource,
AnthropicPlainTextSourceTypedDict,
)
from .anthropictextblockparam import (
AnthropicTextBlockParam,
AnthropicTextBlockParamTypedDict,
)
from .anthropicurlpdfsource import AnthropicURLPdfSource, AnthropicURLPdfSourceTypedDict
from openrouter.types import (
BaseModel,
Nullable,
OptionalNullable,
UNSET,
UNSET_SENTINEL,
)
from openrouter.utils import get_discriminator
from pydantic import Discriminator, Tag, model_serializer
from typing import List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict
class AnthropicDocumentBlockParamCitationsTypedDict(TypedDict):
enabled: NotRequired[bool]
class AnthropicDocumentBlockParamCitations(BaseModel):
enabled: Optional[bool] = None
AnthropicDocumentBlockParamContent1TypedDict = TypeAliasType(
"AnthropicDocumentBlockParamContent1TypedDict",
Union[AnthropicImageBlockParamTypedDict, AnthropicTextBlockParamTypedDict],
)
AnthropicDocumentBlockParamContent1 = Annotated[
Union[
Annotated[AnthropicImageBlockParam, Tag("image")],
Annotated[AnthropicTextBlockParam, Tag("text")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
AnthropicDocumentBlockParamContent2TypedDict = TypeAliasType(
"AnthropicDocumentBlockParamContent2TypedDict",
Union[str, List[AnthropicDocumentBlockParamContent1TypedDict]],
)
AnthropicDocumentBlockParamContent2 = TypeAliasType(
"AnthropicDocumentBlockParamContent2",
Union[str, List[AnthropicDocumentBlockParamContent1]],
)
SourceType = Literal["content",]
class SourceContentTypedDict(TypedDict):
content: AnthropicDocumentBlockParamContent2TypedDict
type: SourceType
class SourceContent(BaseModel):
content: AnthropicDocumentBlockParamContent2
type: SourceType
AnthropicDocumentBlockParamSourceUnionTypedDict = TypeAliasType(
"AnthropicDocumentBlockParamSourceUnionTypedDict",
Union[
SourceContentTypedDict,
AnthropicURLPdfSourceTypedDict,
AnthropicFileDocumentSourceTypedDict,
AnthropicBase64PdfSourceTypedDict,
AnthropicPlainTextSourceTypedDict,
],
)
AnthropicDocumentBlockParamSourceUnion = Annotated[
Union[
Annotated[AnthropicBase64PdfSource, Tag("base64")],
Annotated[AnthropicPlainTextSource, Tag("text")],
Annotated[SourceContent, Tag("content")],
Annotated[AnthropicURLPdfSource, Tag("url")],
Annotated[AnthropicFileDocumentSource, Tag("file")],
],
Discriminator(lambda m: get_discriminator(m, "type", "type")),
]
TypeDocument = Literal["document",]
class AnthropicDocumentBlockParamTypedDict(TypedDict):
source: AnthropicDocumentBlockParamSourceUnionTypedDict
type: TypeDocument
cache_control: NotRequired[AnthropicCacheControlDirectiveTypedDict]
r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""
citations: NotRequired[Nullable[AnthropicDocumentBlockParamCitationsTypedDict]]
context: NotRequired[Nullable[str]]
title: NotRequired[Nullable[str]]
class AnthropicDocumentBlockParam(BaseModel):
source: AnthropicDocumentBlockParamSourceUnion
type: TypeDocument
cache_control: Optional[AnthropicCacheControlDirective] = None
r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""
citations: OptionalNullable[AnthropicDocumentBlockParamCitations] = UNSET
context: OptionalNullable[str] = UNSET
title: OptionalNullable[str] = UNSET
@model_serializer(mode="wrap")
def serialize_model(self, handler):
optional_fields = ["cache_control", "citations", "context", "title"]
nullable_fields = ["citations", "context", "title"]
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

Some files were not shown because too many files have changed in this diff Show More