From 206db95cd2623d07fce163ea0a2d40d25d9d960e Mon Sep 17 00:00:00 2001 From: speakeasybot Date: Wed, 2 Dec 2026 07:33:47 +0000 Subject: [PATCH] ## Python SDK Changes: * `open_router.batch.cancel()`: **Added** --- .speakeasy/gen.lock | 71 +++++-- .speakeasy/gen.yaml | 2 +- .speakeasy/out.openapi.yaml | 122 ++++++++++- .speakeasy/workflow.lock | 10 +- RELEASES.md | 12 +- docs/operations/cancelbatchglobals.mdx | 11 + docs/operations/cancelbatchrequest.mdx | 12 ++ docs/sdks/batch/README.mdx | 52 ++++- docs/sdks/models/README.mdx | 2 +- pyproject.toml | 2 +- src/openrouter/_version.py | 4 +- src/openrouter/batch.py | 252 ++++++++++++++++++++++- src/openrouter/models_.py | 4 + src/openrouter/operations/__init__.py | 14 ++ src/openrouter/operations/cancelbatch.py | 144 +++++++++++++ src/openrouter/sdk.py | 2 +- uv.lock | 2 +- 17 files changed, 679 insertions(+), 39 deletions(-) create mode 100644 docs/operations/cancelbatchglobals.mdx create mode 100644 docs/operations/cancelbatchrequest.mdx create mode 100644 src/openrouter/operations/cancelbatch.py diff --git a/.speakeasy/gen.lock b/.speakeasy/gen.lock index 42d22d1c3..82dcb024e 100644 --- a/.speakeasy/gen.lock +++ b/.speakeasy/gen.lock @@ -1,19 +1,19 @@ lockVersion: 2.0.0 id: c48cf606-fb42-4a45-9c23-8f0555307828 management: - docChecksum: d400e55b15e2a2ae2a255ae0774a55ca + docChecksum: fe7bb52072a7794e3f45f29b6197af42 docVersion: 1.0.0 speakeasyVersion: 1.803.2 generationVersion: 2.950.13 - releaseVersion: 1.3.229 - configChecksum: bc7bc68b68a0b355a7076fc106a19ac7 + releaseVersion: 1.3.230 + configChecksum: 508a1e3ebc5bbb0b12eb9ffcb67b1148 repoURL: https://github.com/OpenRouterTeam/python-sdk.git installationURL: https://github.com/OpenRouterTeam/python-sdk.git published: true persistentEdits: - generation_id: 77639645-43cf-4375-b62c-4575579fe4df - pristine_commit_hash: b2124ee8c2e1856217922344a1fc7caaae8efdd8 - pristine_tree_hash: da1233bc3553a5e1def1838fec5b734a55d1aa48 + generation_id: 4eafa3c1-7515-49bf-b2a7-affc6f8f8545 + pristine_commit_hash: d8c081df637782a4bce857ef067ac3ba01a8ef44 + pristine_tree_hash: 76c93c468190733a0cf292b0226728ce00c0d648 features: python: acceptHeaders: 3.0.0 @@ -10226,6 +10226,14 @@ trackedFiles: id: db4a10e02011 last_write_checksum: sha1:3be9f4acdea977d0907288f33ed0f79fe3389443 pristine_git_object: ed8aded072683a1daefb4174a1c85e367e845cdd + docs/operations/cancelbatchglobals.mdx: + id: 7d5dfc5f85f6 + last_write_checksum: sha1:3f50636695cef4ee34c644ebb0c26b28465858ba + pristine_git_object: 60421ffbc03553b3620eb146f4749e070d3ab1db + docs/operations/cancelbatchrequest.mdx: + id: c4457b710399 + last_write_checksum: sha1:c987d14e76dfea38f17410c473bdba1f16d53bef + pristine_git_object: e392b4a5e348353d9bf83971845d67ac12e5cc2d docs/operations/changeapikeypolicyassignmentglobals.mdx: id: beeb3f2813ca last_write_checksum: sha1:1a0ef422718684ceca1dc4f96c37214f833439f4 @@ -12236,8 +12244,8 @@ trackedFiles: pristine_git_object: e1c261779c6ccbc2b6cf70738af9bf5b5a9925aa docs/sdks/batch/README.mdx: id: e367aa4f4295 - last_write_checksum: sha1:3b4b5a6cc9875a34e7aef2b5a458a35739ef6f41 - pristine_git_object: 6d828a2f0c8e25e0a46fb4f0a99bea0f126fc9e4 + last_write_checksum: sha1:03ddfbe3833af9b7ac3b683e1f57b16bab4aa667 + pristine_git_object: e974a6eda93ac9e3f5eeb83a665e790f0ba06758 docs/sdks/benchmarks/README.mdx: id: 5b483a6770ba last_write_checksum: sha1:10a8edbf3bc300bab53ce72c3a37c974971b74bd @@ -12312,8 +12320,8 @@ trackedFiles: pristine_git_object: a330c3f121d866703e37cd7274051b1caa6023eb docs/sdks/models/README.mdx: id: 58f1ca464e0b - last_write_checksum: sha1:2e89247b7ad63c2bdcf9da989ac4f2e758eee729 - pristine_git_object: 005bce4cf4181e5481bae659bc732b06ec6783c3 + last_write_checksum: sha1:f9c8722391e2a7aa6a7234f57e3ee57bd862dccb + pristine_git_object: 97bc481cdd542560de7051d7e3b08d48cbf09329 docs/sdks/oauth/README.mdx: id: 42b5079343d2 last_write_checksum: sha1:ed962f2d4afda6e456d031d8783a4825aeb85b97 @@ -12388,8 +12396,8 @@ trackedFiles: pristine_git_object: 3e38f1a929f7d6b1d6de74604aa87e3d8f010544 pyproject.toml: id: 5d07e7d72637 - last_write_checksum: sha1:f2c7d0d17b7ffa44991a632dfac10508c764fd02 - pristine_git_object: 1372fe6a79dd3e463a09a2e5507f5dfa92afa93a + last_write_checksum: sha1:b35a57f8ca54edaff98f66c3b036a90765f69c8a + pristine_git_object: 999ad9ef92bbf333e1eb507ea3489e2698146ffd scripts/prepare_readme.py: id: e0c5957a6035 last_write_checksum: sha1:77f44b60b98bc126557ec27391f91dfba764bb54 @@ -12416,8 +12424,8 @@ trackedFiles: pristine_git_object: 86713cfea633e09d33b3d4e65281071fe20e6137 src/openrouter/_version.py: id: d8d15ad6c586 - last_write_checksum: sha1:0d714c038e6c572201ae52e2972e78a332ad81b9 - pristine_git_object: 200b7a2dc144afdf65fe9dde05f9625bc349efbf + last_write_checksum: sha1:30874dfbdb7f4acdabe13127f14c8fd933e9ff10 + pristine_git_object: 515ee52e04cee710287b89b96e1ec460a5dadb4c src/openrouter/alpha.py: id: 306c4d93308d last_write_checksum: sha1:80cc0f39649445431cc2247ed0e0765438467766 @@ -12436,8 +12444,8 @@ trackedFiles: pristine_git_object: 7a562e21c7e66c9db666ead83748b73adefe4278 src/openrouter/batch.py: id: 148f61e34d5b - last_write_checksum: sha1:29652e72df1414686e65cd8f4df75eb871cb2881 - pristine_git_object: f71c1f3f98d9b886fa5cf0c46b1dbc46db279735 + last_write_checksum: sha1:66bf7726b079d007ce8d6eaff76ab3a95a2ea88c + pristine_git_object: 1110b2127b77436a1b3ee7acda5ff3f5040fdf56 src/openrouter/benchmarks.py: id: 178d2ad8d706 last_write_checksum: sha1:be86f24d07ba86e9585f7d2bc2c384dba5185727 @@ -16668,8 +16676,8 @@ trackedFiles: pristine_git_object: 5b741456655ff48919d17ffd552a6410f0587966 src/openrouter/models_.py: id: 4e1ae1fe5b98 - last_write_checksum: sha1:7e3e5275d99180adffb5a4b044a5d93af02fb796 - pristine_git_object: e4a9e3e4f9aee7c6fbb8b9c3b35bea9873e34646 + last_write_checksum: sha1:e672fdc72d2c4a4acaa56b104d2c5cf0c58f4812 + pristine_git_object: 822afd885d0a7308a4f8f939396262ec60bd3927 src/openrouter/oauth.py: id: 1948ce27255b last_write_checksum: sha1:938c8b5ac63c1410e1173a2873b9c2493d720a1d @@ -16680,8 +16688,8 @@ trackedFiles: pristine_git_object: 039fd484b407d7ca13177a892db5939b312ee50d src/openrouter/operations/__init__.py: id: 9afcea1e7161 - last_write_checksum: sha1:4bd14f64e187e92c36bbfbfb10c4d5ca8041199b - pristine_git_object: b5a6b1701ce79c3ee1aebb2511b779038eb048d1 + last_write_checksum: sha1:b307a82a88fcc61b302e44093de78f264461a9dc + pristine_git_object: 96120c9d11e8bc2f5a75fdc89c241c4cb84c8ce6 src/openrouter/operations/activateprivateendpoint.py: id: 3b39eec5d66f last_write_checksum: sha1:9406e6b3d38c82895fd795f637702ef579cc6d36 @@ -16710,6 +16718,10 @@ trackedFiles: id: 8127aafae1ef last_write_checksum: sha1:7e1a34d0a1629bd6ed183a85b71a6897202a02bf pristine_git_object: ff2fc0c099bd5ade18b89e6d39698293ae65e87c + src/openrouter/operations/cancelbatch.py: + id: 4e0c278a1b4e + last_write_checksum: sha1:73485b5a6176b0781056f29a14821ea87304ce0b + pristine_git_object: a5e7d4f18ced703a68576ccb4edf0b9a67b6237a src/openrouter/operations/changeapikeypolicyassignment.py: id: d51b3fed8944 last_write_checksum: sha1:79b58a542c1e2fbbd07534aa5596e5d593e98ea3 @@ -17428,8 +17440,8 @@ trackedFiles: pristine_git_object: c06eab04cb453a67f98177d6f1f28aa1578e9c02 src/openrouter/sdk.py: id: ee9846c4c9c5 - last_write_checksum: sha1:e2ac234f50cf2fa57417f0be1c9222dc8cfcf947 - pristine_git_object: a015bc43a8823e977e7c5f6bdcd46c7cbe2725b8 + last_write_checksum: sha1:16fcee50f867efef65dce82d1d51ad88bdb3584e + pristine_git_object: f385609baf912074872f6742d5b992e75d6f8deb src/openrouter/sdkconfiguration.py: id: 55773bb98d7c last_write_checksum: sha1:c01826125c31a8b8bc99d9d679782c8758fae001 @@ -22781,4 +22793,19 @@ examples: application/json: {"error": {"code": 409, "message": "Resource conflict. Please try again later."}} "500": application/json: {"error": {"code": 500, "message": "Internal Server Error"}} + cancelBatch: + speakeasy-default-cancel-batch: + parameters: + path: + id: "batch_abc123" + responses: + "200": + application/json: {"completion_window": "24h", "created_at": 532952, "endpoint": "", "error": {"message": ""}, "expires_at": 340450, "finalized_at": 285267, "id": "", "model": "Taurus", "object": "batch", "provider": "", "request_counts": {"completed": 228691, "failed": 283504, "total": 213468}, "results": [], "status": "expired", "usage": {"completion_tokens": 41402, "prompt_tokens": 122283, "total_tokens": 34931}} + "400": + application/json: {"error": {"code": 400, "message": "custom_id is required on requests[0]."}} + "500": + application/json: {"error": {"code": 400, "message": "custom_id is required on requests[0]."}} examplesVersion: 1.0.2 +releaseNotes: | + ## Python SDK Changes: + * `open_router.batch.cancel()`: **Added** diff --git a/.speakeasy/gen.yaml b/.speakeasy/gen.yaml index 6164c316a..cf17d4328 100644 --- a/.speakeasy/gen.yaml +++ b/.speakeasy/gen.yaml @@ -37,7 +37,7 @@ generation: documentation: mintlify preApplyUnionDiscriminators: true python: - version: 1.3.229 + version: 1.3.230 additionalDependencies: dev: pytest: '>=8.3' diff --git a/.speakeasy/out.openapi.yaml b/.speakeasy/out.openapi.yaml index 7fffdc4fb..e97a56594 100644 --- a/.speakeasy/out.openapi.yaml +++ b/.speakeasy/out.openapi.yaml @@ -44900,6 +44900,125 @@ paths: - $ref: "#/components/parameters/AppIdentifier" - $ref: "#/components/parameters/AppDisplayName" - $ref: "#/components/parameters/AppCategories" + /batches/{id}/cancel: + post: + description: 'Asks the provider to stop a batch that is still running. Cancellation is enabled per organization; other organizations get `403`. The response is the batch in its current status: it stays `in_progress` until the provider confirms, then becomes `cancelled`, or `completed`, `failed`, or `expired` when the provider job ended first. Poll until the batch has any final status. Repeating the call is safe while the batch is still `in_progress`; once it has a final status the call returns `409`. OpenRouter returns no result rows for a cancelled batch, and the provider still charges for the requests that finished before the cancellation. When the batch wrote its output to your own storage, retrieving the batch can still return that location, and the rows the provider wrote there stay yours to read. See the [Batch API Quickstart](https://openrouter.ai/docs/batch-quickstart).' + operationId: 'cancelBatch' + parameters: + - description: 'The batch job id returned from submit.' + in: 'path' + name: 'id' + required: true + schema: + description: 'The batch job id returned from submit.' + example: 'batch_abc123' + minLength: 1 + type: 'string' + responses: + '200': + content: + application/json: + schema: + $ref: '#/components/schemas/BatchObject' + description: 'The provider accepted the cancellation, or the provider job had already ended while OpenRouter still stores the batch as running. Poll the batch for its final status.' + '400': + content: + application/json: + example: + error: + code: 400 + message: 'No active workspace resolved for this request.' + schema: + $ref: '#/components/schemas/BatchErrorResponse' + description: 'The API key resolved no active workspace.' + '401': + content: + application/json: + example: + error: + code: 401 + message: 'No auth credentials found.' + schema: + $ref: '#/components/schemas/BatchErrorResponse' + description: 'Missing or invalid API key.' + '403': + content: + application/json: + example: + error: + code: 403 + message: 'Batch cancellation is not enabled for this organization.' + schema: + $ref: '#/components/schemas/BatchErrorResponse' + description: 'Batch cancellation is not enabled for the organization.' + '404': + content: + application/json: + example: + error: + code: 404 + message: 'Batch not found.' + schema: + $ref: '#/components/schemas/BatchErrorResponse' + description: 'No batch exists for the given id.' + '409': + content: + application/json: + example: + error: + code: 409 + message: 'This batch has already ended and cannot be cancelled.' + schema: + $ref: '#/components/schemas/BatchErrorResponse' + description: 'The batch has already ended, has not reached the provider yet, runs on a provider without a cancel call, or its required provider key is unavailable.' + '429': + content: + application/json: + example: + error: + code: 429 + message: 'Rate limit exceeded.' + schema: + $ref: '#/components/schemas/BatchErrorResponse' + description: 'Batch API rate limit exceeded for the billable entity.' + '500': + content: + application/json: + example: + error: + code: 500 + message: 'Internal server error.' + schema: + $ref: '#/components/schemas/BatchErrorResponse' + description: 'Unexpected error in the ingress or upstream batch-api.' + '502': + content: + application/json: + example: + error: + code: 502 + message: 'Upstream batch-api is unavailable.' + schema: + $ref: '#/components/schemas/BatchErrorResponse' + description: 'The batch service is unavailable, or an upstream provider operation failed.' + '503': + content: + application/json: + example: + error: + code: 503 + message: 'Service Unavailable' + schema: + $ref: '#/components/schemas/BatchErrorResponse' + description: 'OpenRouter could not check whether the caller may cancel the batch. No cancellation is sent to the provider. Retry the request.' + summary: 'Cancel a batch' + tags: + - 'Batch' + x-speakeasy-name-override: 'cancel' + parameters: + - $ref: "#/components/parameters/AppIdentifier" + - $ref: "#/components/parameters/AppDisplayName" + - $ref: "#/components/parameters/AppCategories" /batches/{id}/results: get: description: 'Returns a cursor-paginated page of normalized OpenRouter-format results for a finished batch. Pass the previous page''s `next_cursor` as `cursor` to read the next page. Pages are stable across retries for the 30-day artifact retention window. See the [Batch API Quickstart](https://openrouter.ai/docs/batch-quickstart).' @@ -55883,6 +56002,7 @@ paths: - $ref: "#/components/parameters/AppCategories" /models: get: + description: 'Lists the models available to the caller with their pricing, context length, modalities, and supported parameters, plus presets when the caller is authenticated. An unfiltered call returns every text-output model (often several hundred KB of JSON or more; set `output_modalities` to list models with other outputs); use `limit` and `offset` to cap the result and filters such as `q`, `output_modalities`, `input_modalities`, or `supported_parameters` to narrow it (`sort` only reorders), or call `GET /api/v1/model/{author}/{slug}` to inspect a single catalog model. `category` is a usage shortlist, not a catalog filter: it returns only the top 20 models in that category by past-week token usage, never presets, and cannot be combined with `limit`, `offset`, or `supported_parameters`.' operationId: 'getModels' parameters: - description: 'Number of records to skip for pagination. When both offset and limit are omitted, the full list is returned' @@ -66727,7 +66847,7 @@ tags: name: 'Anthropic Messages' - description: 'BYOK endpoints' name: 'BYOK' - - description: 'Submit, list, poll, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart.' + - description: 'Submit, list, poll, cancel, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart.' name: 'Batch' - description: 'Benchmarks endpoints' name: 'Benchmarks' diff --git a/.speakeasy/workflow.lock b/.speakeasy/workflow.lock index 68c11c108..b69e06024 100644 --- a/.speakeasy/workflow.lock +++ b/.speakeasy/workflow.lock @@ -2,8 +2,8 @@ speakeasyVersion: 1.803.2 sources: OpenRouter API: sourceNamespace: open-router-chat-completions-api - sourceRevisionDigest: sha256:9e232dde7b839ff47f4658c5dc38abaeb319267cd015acc54c297adcfa8eb791 - sourceBlobDigest: sha256:e69e7c1ef60161df4f8f7f234ed0d6edbdc236458b1e7377f191437096cb2b37 + sourceRevisionDigest: sha256:949837946fc92eb23fc848c709a1e91e906d898d728abf053c93cbfada84a1a6 + sourceBlobDigest: sha256:0839be120b5e22b32c31ec9183489f32a657f14855ed5338122da32b361a957d tags: - latest - 1.0.0 @@ -11,10 +11,10 @@ targets: open-router: source: OpenRouter API sourceNamespace: open-router-chat-completions-api - sourceRevisionDigest: sha256:9e232dde7b839ff47f4658c5dc38abaeb319267cd015acc54c297adcfa8eb791 - sourceBlobDigest: sha256:e69e7c1ef60161df4f8f7f234ed0d6edbdc236458b1e7377f191437096cb2b37 + sourceRevisionDigest: sha256:949837946fc92eb23fc848c709a1e91e906d898d728abf053c93cbfada84a1a6 + sourceBlobDigest: sha256:0839be120b5e22b32c31ec9183489f32a657f14855ed5338122da32b361a957d codeSamplesNamespace: open-router-python-code-samples - codeSamplesRevisionDigest: sha256:7a85751b9e3754b126cd72b5741151420b92924b7469f656ce6c9d2e81b340f1 + codeSamplesRevisionDigest: sha256:384a5798eaa429af85ff3fe34e128ea89de14c339e634a79dbc87e68b71b41e5 workflow: workflowVersion: 1.0.0 speakeasyVersion: 1.803.2 diff --git a/RELEASES.md b/RELEASES.md index 2e9b81466..1ae545795 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -5059,4 +5059,14 @@ Based on: ### Generated - [python v1.3.229] . ### Releases -- [PyPI v1.3.229] https://pypi.org/project/openrouter/1.3.229 - . \ No newline at end of file +- [PyPI v1.3.229] https://pypi.org/project/openrouter/1.3.229 - . + +## 2026-12-02 07:30:28 +### Changes +Based on: +- OpenAPI Doc +- Speakeasy CLI 1.803.2 (2.950.13) https://github.com/speakeasy-api/speakeasy +### Generated +- [python v1.3.230] . +### Releases +- [PyPI v1.3.230] https://pypi.org/project/openrouter/1.3.230 - . \ No newline at end of file diff --git a/docs/operations/cancelbatchglobals.mdx b/docs/operations/cancelbatchglobals.mdx new file mode 100644 index 000000000..60421ffbc --- /dev/null +++ b/docs/operations/cancelbatchglobals.mdx @@ -0,0 +1,11 @@ +--- +title: "CancelBatchGlobals" +--- + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `http_referer` | *Optional[str]* | ➖ | The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
| +| `x_open_router_title` | *Optional[str]* | ➖ | The app display name allows you to customize how your app appears in OpenRouter's dashboard.
| +| `x_open_router_categories` | *Optional[str]* | ➖ | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.
| \ No newline at end of file diff --git a/docs/operations/cancelbatchrequest.mdx b/docs/operations/cancelbatchrequest.mdx new file mode 100644 index 000000000..e392b4a5e --- /dev/null +++ b/docs/operations/cancelbatchrequest.mdx @@ -0,0 +1,12 @@ +--- +title: "CancelBatchRequest" +--- + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `http_referer` | *Optional[str]* | ➖ | The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
| | +| `x_open_router_title` | *Optional[str]* | ➖ | The app display name allows you to customize how your app appears in OpenRouter's dashboard.
| | +| `x_open_router_categories` | *Optional[str]* | ➖ | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.
| | +| `id` | *str* | ✔️ | The batch job id returned from submit. | batch_abc123 | \ No newline at end of file diff --git a/docs/sdks/batch/README.mdx b/docs/sdks/batch/README.mdx index 6d828a2f0..e974a6eda 100644 --- a/docs/sdks/batch/README.mdx +++ b/docs/sdks/batch/README.mdx @@ -1,11 +1,11 @@ --- title: "Batch" -description: "Submit, list, poll, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart." +description: "Submit, list, poll, cancel, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart." --- ## Overview -Submit, list, poll, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart. +Submit, list, poll, cancel, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart. ### Available Operations @@ -13,6 +13,7 @@ Submit, list, poll, and delete asynchronous batches of inference requests. See h * [create_batches](#create_batches) - Create a batch * [delete](#delete) - Delete a batch * [get_batches](#get_batches) - Get a batch +* [cancel](#cancel) - Cancel a batch * [get_results](#get_results) - Get batch results ## list @@ -276,6 +277,53 @@ with OpenRouter( | errors.BatchErrorResponse | 500, 502 | application/json | | errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | +## cancel + +Asks the provider to stop a batch that is still running. Cancellation is enabled per organization; other organizations get `403`. The response is the batch in its current status: it stays `in_progress` until the provider confirms, then becomes `cancelled`, or `completed`, `failed`, or `expired` when the provider job ended first. Poll until the batch has any final status. Repeating the call is safe while the batch is still `in_progress`; once it has a final status the call returns `409`. OpenRouter returns no result rows for a cancelled batch, and the provider still charges for the requests that finished before the cancellation. When the batch wrote its output to your own storage, retrieving the batch can still return that location, and the rows the provider wrote there stay yours to read. See the [Batch API Quickstart](https://openrouter.ai/docs/batch-quickstart). + +### Example Usage + +```python +from openrouter import OpenRouter +import os + + +with OpenRouter( + http_referer="", + x_open_router_title="", + x_open_router_categories="", + api_key=os.getenv("OPENROUTER_API_KEY", ""), +) as open_router: + + res = open_router.batch.cancel(id="batch_abc123") + + # Handle response + print(res) + +``` + +### Parameters + +| Parameter | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `id` | *str* | ✔️ | The batch job id returned from submit. | batch_abc123 | +| `http_referer` | *Optional[str]* | ➖ | The app identifier should be your app's URL and is used as the primary identifier for rankings.
This is used to track API usage per application.
| | +| `x_open_router_title` | *Optional[str]* | ➖ | The app display name allows you to customize how your app appears in OpenRouter's dashboard.
| | +| `x_open_router_categories` | *Optional[str]* | ➖ | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.
| | +| `retries` | [Optional[utils.RetryConfig]](../../models/utils/retryconfig.mdx) | ➖ | Configuration to override the default retry behavior of the client. | | + +### Response + +**[components.BatchObject](../../components/batchobject.mdx)** + +### Errors + +| Error Type | Status Code | Content Type | +| ----------------------------- | ----------------------------- | ----------------------------- | +| errors.BatchErrorResponse | 400, 401, 403, 404, 409, 429 | application/json | +| errors.BatchErrorResponse | 500, 502, 503 | application/json | +| errors.OpenRouterDefaultError | 4XX, 5XX | \*/\* | + ## get_results Returns a cursor-paginated page of normalized OpenRouter-format results for a finished batch. Pass the previous page's `next_cursor` as `cursor` to read the next page. Pages are stable across retries for the 30-day artifact retention window. See the [Batch API Quickstart](https://openrouter.ai/docs/batch-quickstart). diff --git a/docs/sdks/models/README.mdx b/docs/sdks/models/README.mdx index 005bce4cf..97bc481cd 100644 --- a/docs/sdks/models/README.mdx +++ b/docs/sdks/models/README.mdx @@ -65,7 +65,7 @@ with OpenRouter( ## list -List all models and their properties +Lists the models available to the caller with their pricing, context length, modalities, and supported parameters, plus presets when the caller is authenticated. An unfiltered call returns every text-output model (often several hundred KB of JSON or more; set `output_modalities` to list models with other outputs); use `limit` and `offset` to cap the result and filters such as `q`, `output_modalities`, `input_modalities`, or `supported_parameters` to narrow it (`sort` only reorders), or call `GET /api/v1/model/{author}/{slug}` to inspect a single catalog model. `category` is a usage shortlist, not a catalog filter: it returns only the top 20 models in that category by past-week token usage, never presets, and cannot be combined with `limit`, `offset`, or `supported_parameters`. ### Example Usage diff --git a/pyproject.toml b/pyproject.toml index 1372fe6a7..999ad9ef9 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openrouter" -version = "1.3.229" +version = "1.3.230" description = "Official Python Client SDK for OpenRouter." authors = [{ name = "OpenRouter" },] readme = "README-PYPI.md" diff --git a/src/openrouter/_version.py b/src/openrouter/_version.py index 200b7a2dc..515ee52e0 100644 --- a/src/openrouter/_version.py +++ b/src/openrouter/_version.py @@ -3,10 +3,10 @@ import importlib.metadata __title__: str = "openrouter" -__version__: str = "1.3.229" +__version__: str = "1.3.230" __openapi_doc_version__: str = "1.0.0" __gen_version__: str = "2.950.13" -__user_agent__: str = "speakeasy-sdk/python 1.3.229 2.950.13 1.0.0 openrouter" +__user_agent__: str = "speakeasy-sdk/python 1.3.230 2.950.13 1.0.0 openrouter" try: if __package__ is not None: diff --git a/src/openrouter/batch.py b/src/openrouter/batch.py index f71c1f3f9..1110b2127 100644 --- a/src/openrouter/batch.py +++ b/src/openrouter/batch.py @@ -11,7 +11,7 @@ class Batch(BaseSDK): - r"""Submit, list, poll, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart.""" + r"""Submit, list, poll, cancel, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart.""" def list( self, @@ -1204,6 +1204,256 @@ async def get_batches_async( raise errors.OpenRouterDefaultError("Unexpected response received", http_res) + def cancel( + self, + *, + id: str, + 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, + ) -> components.BatchObject: + r"""Cancel a batch + + Asks the provider to stop a batch that is still running. Cancellation is enabled per organization; other organizations get `403`. The response is the batch in its current status: it stays `in_progress` until the provider confirms, then becomes `cancelled`, or `completed`, `failed`, or `expired` when the provider job ended first. Poll until the batch has any final status. Repeating the call is safe while the batch is still `in_progress`; once it has a final status the call returns `409`. OpenRouter returns no result rows for a cancelled batch, and the provider still charges for the requests that finished before the cancellation. When the batch wrote its output to your own storage, retrieving the batch can still return that location, and the rows the provider wrote there stay yours to read. See the [Batch API Quickstart](https://openrouter.ai/docs/batch-quickstart). + + :param id: The batch job id returned from submit. + :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.CancelBatchRequest( + http_referer=http_referer, + x_open_router_title=x_open_router_title, + x_open_router_categories=x_open_router_categories, + id=id, + ) + + req = self._build_request( + method="POST", + path="/batches/{id}/cancel", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + _globals=operations.CancelBatchGlobals( + 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="cancelBatch", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, components.Security + ), + tags=["Batch"], + extensions=None, + ), + request=req, + is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(components.BatchObject, http_res) + if utils.match_response( + http_res, ["400", "401", "403", "404", "409", "429"], "application/json" + ): + response_data = unmarshal_json_response( + errors.BatchErrorResponseData, http_res + ) + raise errors.BatchErrorResponse(response_data, http_res) + if utils.match_response(http_res, ["500", "502", "503"], "application/json"): + response_data = unmarshal_json_response( + errors.BatchErrorResponseData, http_res + ) + raise errors.BatchErrorResponse(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 cancel_async( + self, + *, + id: str, + 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, + ) -> components.BatchObject: + r"""Cancel a batch + + Asks the provider to stop a batch that is still running. Cancellation is enabled per organization; other organizations get `403`. The response is the batch in its current status: it stays `in_progress` until the provider confirms, then becomes `cancelled`, or `completed`, `failed`, or `expired` when the provider job ended first. Poll until the batch has any final status. Repeating the call is safe while the batch is still `in_progress`; once it has a final status the call returns `409`. OpenRouter returns no result rows for a cancelled batch, and the provider still charges for the requests that finished before the cancellation. When the batch wrote its output to your own storage, retrieving the batch can still return that location, and the rows the provider wrote there stay yours to read. See the [Batch API Quickstart](https://openrouter.ai/docs/batch-quickstart). + + :param id: The batch job id returned from submit. + :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.CancelBatchRequest( + http_referer=http_referer, + x_open_router_title=x_open_router_title, + x_open_router_categories=x_open_router_categories, + id=id, + ) + + req = self._build_request_async( + method="POST", + path="/batches/{id}/cancel", + base_url=base_url, + url_variables=url_variables, + request=request, + request_body_required=False, + request_has_path_params=True, + request_has_query_params=True, + user_agent_header="user-agent", + accept_header_value="application/json", + http_headers=http_headers, + _globals=operations.CancelBatchGlobals( + 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="cancelBatch", + oauth2_scopes=None, + security_source=get_security_from_env( + self.sdk_configuration.security, components.Security + ), + tags=["Batch"], + extensions=None, + ), + request=req, + is_error_status_code=lambda c: utils.match_status_codes(["4XX", "5XX"], c), + retry_config=retry_config, + ) + + response_data: Any = None + if utils.match_response(http_res, "200", "application/json"): + return unmarshal_json_response(components.BatchObject, http_res) + if utils.match_response( + http_res, ["400", "401", "403", "404", "409", "429"], "application/json" + ): + response_data = unmarshal_json_response( + errors.BatchErrorResponseData, http_res + ) + raise errors.BatchErrorResponse(response_data, http_res) + if utils.match_response(http_res, ["500", "502", "503"], "application/json"): + response_data = unmarshal_json_response( + errors.BatchErrorResponseData, http_res + ) + raise errors.BatchErrorResponse(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 get_results( self, *, diff --git a/src/openrouter/models_.py b/src/openrouter/models_.py index e4a9e3e4f..822afd885 100644 --- a/src/openrouter/models_.py +++ b/src/openrouter/models_.py @@ -338,6 +338,8 @@ def list( ) -> Optional[operations.GetModelsResponse]: r"""List all models and their properties + Lists the models available to the caller with their pricing, context length, modalities, and supported parameters, plus presets when the caller is authenticated. An unfiltered call returns every text-output model (often several hundred KB of JSON or more; set `output_modalities` to list models with other outputs); use `limit` and `offset` to cap the result and filters such as `q`, `output_modalities`, `input_modalities`, or `supported_parameters` to narrow it (`sort` only reorders), or call `GET /api/v1/model/{author}/{slug}` to inspect a single catalog model. `category` is a usage shortlist, not a catalog filter: it returns only the top 20 models in that category by past-week token usage, never presets, and cannot be combined with `limit`, `offset`, or `supported_parameters`. + :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. @@ -719,6 +721,8 @@ async def list_async( ) -> Optional[operations.GetModelsResponse]: r"""List all models and their properties + Lists the models available to the caller with their pricing, context length, modalities, and supported parameters, plus presets when the caller is authenticated. An unfiltered call returns every text-output model (often several hundred KB of JSON or more; set `output_modalities` to list models with other outputs); use `limit` and `offset` to cap the result and filters such as `q`, `output_modalities`, `input_modalities`, or `supported_parameters` to narrow it (`sort` only reorders), or call `GET /api/v1/model/{author}/{slug}` to inspect a single catalog model. `category` is a usage shortlist, not a catalog filter: it returns only the top 20 models in that category by past-week token usage, never presets, and cannot be combined with `limit`, `offset`, or `supported_parameters`. + :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. diff --git a/src/openrouter/operations/__init__.py b/src/openrouter/operations/__init__.py index b5a6b1701..96120c9d1 100644 --- a/src/openrouter/operations/__init__.py +++ b/src/openrouter/operations/__init__.py @@ -47,6 +47,12 @@ BulkUnassignMembersFromGuardrailRequest, BulkUnassignMembersFromGuardrailRequestTypedDict, ) + from .cancelbatch import ( + CancelBatchGlobals, + CancelBatchGlobalsTypedDict, + CancelBatchRequest, + CancelBatchRequestTypedDict, + ) from .changeapikeypolicyassignment import ( ChangeAPIKeyPolicyAssignmentGlobals, ChangeAPIKeyPolicyAssignmentGlobalsTypedDict, @@ -1384,6 +1390,10 @@ "BulkUnassignMembersFromGuardrailRequestTypedDict", "CREATE_API_ALPHA_DECISIONS_SERVERS", "CREATE_API_ALPHA_EXTRACTIONS_SERVERS", + "CancelBatchGlobals", + "CancelBatchGlobalsTypedDict", + "CancelBatchRequest", + "CancelBatchRequestTypedDict", "ChangeAPIKeyPolicyAssignmentGlobals", "ChangeAPIKeyPolicyAssignmentGlobalsTypedDict", "ChangeAPIKeyPolicyAssignmentRequest", @@ -2370,6 +2380,10 @@ "BulkUnassignMembersFromGuardrailGlobalsTypedDict": ".bulkunassignmembersfromguardrail", "BulkUnassignMembersFromGuardrailRequest": ".bulkunassignmembersfromguardrail", "BulkUnassignMembersFromGuardrailRequestTypedDict": ".bulkunassignmembersfromguardrail", + "CancelBatchGlobals": ".cancelbatch", + "CancelBatchGlobalsTypedDict": ".cancelbatch", + "CancelBatchRequest": ".cancelbatch", + "CancelBatchRequestTypedDict": ".cancelbatch", "ChangeAPIKeyPolicyAssignmentGlobals": ".changeapikeypolicyassignment", "ChangeAPIKeyPolicyAssignmentGlobalsTypedDict": ".changeapikeypolicyassignment", "ChangeAPIKeyPolicyAssignmentRequest": ".changeapikeypolicyassignment", diff --git a/src/openrouter/operations/cancelbatch.py b/src/openrouter/operations/cancelbatch.py new file mode 100644 index 000000000..a5e7d4f18 --- /dev/null +++ b/src/openrouter/operations/cancelbatch.py @@ -0,0 +1,144 @@ +"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.""" + +from __future__ import annotations +from openrouter.types import BaseModel, UNSET_SENTINEL +from openrouter.utils import FieldMetadata, HeaderMetadata, PathParamMetadata +import pydantic +from pydantic import model_serializer +from typing import Optional +from typing_extensions import Annotated, NotRequired, TypedDict + + +class CancelBatchGlobalsTypedDict(TypedDict): + http_referer: NotRequired[str] + r"""The app identifier should be your app's URL and is used as the primary identifier for rankings. + This is used to track API usage per application. + + """ + x_open_router_title: NotRequired[str] + r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard. + + """ + x_open_router_categories: NotRequired[str] + r"""Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings. + + """ + + +class CancelBatchGlobals(BaseModel): + http_referer: Annotated[ + Optional[str], + pydantic.Field(alias="HTTP-Referer"), + FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), + ] = None + r"""The app identifier should be your app's URL and is used as the primary identifier for rankings. + This is used to track API usage per application. + + """ + + x_open_router_title: Annotated[ + Optional[str], + pydantic.Field(alias="X-OpenRouter-Title"), + FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), + ] = None + r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard. + + """ + + x_open_router_categories: Annotated[ + Optional[str], + pydantic.Field(alias="X-OpenRouter-Categories"), + FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), + ] = None + r"""Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings. + + """ + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = set( + ["HTTP-Referer", "X-OpenRouter-Title", "X-OpenRouter-Categories"] + ) + serialized = handler(self) + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k, serialized.get(n)) + + if val != UNSET_SENTINEL: + if val is not None or k not in optional_fields: + m[k] = val + + return m + + +class CancelBatchRequestTypedDict(TypedDict): + id: str + r"""The batch job id returned from submit.""" + http_referer: NotRequired[str] + r"""The app identifier should be your app's URL and is used as the primary identifier for rankings. + This is used to track API usage per application. + + """ + x_open_router_title: NotRequired[str] + r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard. + + """ + x_open_router_categories: NotRequired[str] + r"""Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings. + + """ + + +class CancelBatchRequest(BaseModel): + id: Annotated[ + str, FieldMetadata(path=PathParamMetadata(style="simple", explode=False)) + ] + r"""The batch job id returned from submit.""" + + http_referer: Annotated[ + Optional[str], + pydantic.Field(alias="HTTP-Referer"), + FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), + ] = None + r"""The app identifier should be your app's URL and is used as the primary identifier for rankings. + This is used to track API usage per application. + + """ + + x_open_router_title: Annotated[ + Optional[str], + pydantic.Field(alias="X-OpenRouter-Title"), + FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), + ] = None + r"""The app display name allows you to customize how your app appears in OpenRouter's dashboard. + + """ + + x_open_router_categories: Annotated[ + Optional[str], + pydantic.Field(alias="X-OpenRouter-Categories"), + FieldMetadata(header=HeaderMetadata(style="simple", explode=False)), + ] = None + r"""Comma-separated list of app categories (e.g. \"cli-agent,cloud-agent\"). Used for marketplace rankings. + + """ + + @model_serializer(mode="wrap") + def serialize_model(self, handler): + optional_fields = set( + ["HTTP-Referer", "X-OpenRouter-Title", "X-OpenRouter-Categories"] + ) + serialized = handler(self) + m = {} + + for n, f in type(self).model_fields.items(): + k = f.alias or n + val = serialized.get(k, serialized.get(n)) + + if val != UNSET_SENTINEL: + if val is not None or k not in optional_fields: + m[k] = val + + return m diff --git a/src/openrouter/sdk.py b/src/openrouter/sdk.py index a015bc43a..f385609ba 100644 --- a/src/openrouter/sdk.py +++ b/src/openrouter/sdk.py @@ -71,7 +71,7 @@ class OpenRouter(BaseSDK): o_auth: "OAuth" r"""OAuth authentication endpoints""" batch: "Batch" - r"""Submit, list, poll, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart.""" + r"""Submit, list, poll, cancel, and delete asynchronous batches of inference requests. See https://openrouter.ai/docs/batch-quickstart.""" benchmarks: "Benchmarks" r"""Benchmarks endpoints""" byok: "BYOK" diff --git a/uv.lock b/uv.lock index bf0df5377..a896506d3 100644 --- a/uv.lock +++ b/uv.lock @@ -231,7 +231,7 @@ wheels = [ [[package]] name = "openrouter" -version = "1.3.229" +version = "1.3.230" source = { editable = "." } dependencies = [ { name = "httpcore" },