From baa6cda17d05f29740d2f50f58dba4815deb2b8e Mon Sep 17 00:00:00 2001 From: speakeasybot Date: Wed, 2 Dec 2026 07:33:42 +0000 Subject: [PATCH] ## Typescript SDK Changes: * `openrouter.batch.cancel()`: **Added** --- .speakeasy/gen.lock | 25 ++- .speakeasy/gen.yaml | 2 +- .speakeasy/out.openapi.yaml | 122 ++++++++++- .speakeasy/workflow.lock | 10 +- RELEASES.md | 12 +- docs/models/operations/cancelbatchglobals.mdx | 19 ++ docs/models/operations/cancelbatchrequest.mdx | 22 ++ docs/sdks/batch/README.mdx | 85 +++++++- docs/sdks/models/README.mdx | 2 +- jsr.json | 2 +- package.json | 12 +- src/funcs/batchCancel.ts | 206 ++++++++++++++++++ src/funcs/modelsList.ts | 3 + src/lib/config.ts | 4 +- src/models/operations/cancelbatch.ts | 85 ++++++++ src/models/operations/index.ts | 1 + src/sdk/batch.ts | 18 ++ src/sdk/models.ts | 3 + 18 files changed, 610 insertions(+), 23 deletions(-) create mode 100644 docs/models/operations/cancelbatchglobals.mdx create mode 100644 docs/models/operations/cancelbatchrequest.mdx create mode 100644 src/funcs/batchCancel.ts create mode 100644 src/models/operations/cancelbatch.ts diff --git a/.speakeasy/gen.lock b/.speakeasy/gen.lock index ec13453bb..f35559c85 100644 --- a/.speakeasy/gen.lock +++ b/.speakeasy/gen.lock @@ -1,12 +1,12 @@ lockVersion: "" id: "" management: - docChecksum: 5fa16269d60eadd30774aef31c438680 + docChecksum: 3cdd0a6bb971453b3f08e69bc6940ee5 docVersion: 1.0.0 speakeasyVersion: 1.808.1 generationVersion: 2.960.8 - releaseVersion: 1.5.161 - configChecksum: 0e4fbde82c3e96a5b3e8ad2797dc2afc + releaseVersion: 1.5.162 + configChecksum: d725f07fbdad6b88d9f38aa716b04f93 repoURL: https://github.com/OpenRouterTeam/typescript-sdk.git installationURL: https://github.com/OpenRouterTeam/typescript-sdk published: true @@ -7839,6 +7839,8 @@ trackedFiles: docs/models/operations/bulkunassignmembersfromguardrailrequest.mdx: id: 712e15346453 pristine_git_object: 924d309e1b1b22fc3386c659ef9b6dc903d53b20 + docs/models/operations/cancelbatchglobals.mdx: {} + docs/models/operations/cancelbatchrequest.mdx: {} docs/models/operations/changeapikeypolicyassignmentglobals.mdx: id: 591ea5f13259 pristine_git_object: 651d067d3f9aff7d4a025a6295884e572bd88a54 @@ -14399,6 +14401,7 @@ trackedFiles: src/funcs/apiKeysUpdate.ts: id: 05700884934b pristine_git_object: 913f253c6ba572dc3df10a3d647a70aa13c9ef98 + src/funcs/batchCancel.ts: {} src/funcs/batchCreateBatches.ts: id: 8796df347125 pristine_git_object: 81f8ee7d8254bc065cdd49286648fd487e47e1c0 @@ -16975,6 +16978,7 @@ trackedFiles: src/models/operations/bulkunassignmembersfromguardrail.ts: id: ea6be9164914 pristine_git_object: de9f7c710114cfd263def5b6b7541dadf4ba6244 + src/models/operations/cancelbatch.ts: {} src/models/operations/changeapikeypolicyassignment.ts: id: 23e28972f11c pristine_git_object: fac6e9842a90c1b86b69380dae99c5ef0624d9c6 @@ -23908,4 +23912,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: | + ## Typescript SDK Changes: + * `openrouter.batch.cancel()`: **Added** diff --git a/.speakeasy/gen.yaml b/.speakeasy/gen.yaml index 8f73fc82c..ef8502c3c 100644 --- a/.speakeasy/gen.yaml +++ b/.speakeasy/gen.yaml @@ -38,7 +38,7 @@ generation: documentation: mintlify preApplyUnionDiscriminators: true typescript: - version: 1.5.161 + version: 1.5.162 acceptHeaderEnum: false additionalDependencies: dependencies: diff --git a/.speakeasy/out.openapi.yaml b/.speakeasy/out.openapi.yaml index d793638f3..bbfa86ae9 100644 --- a/.speakeasy/out.openapi.yaml +++ b/.speakeasy/out.openapi.yaml @@ -44918,6 +44918,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).' @@ -55886,6 +56005,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' @@ -66715,7 +66835,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 a57cce041..676ded3b2 100644 --- a/.speakeasy/workflow.lock +++ b/.speakeasy/workflow.lock @@ -2,8 +2,8 @@ speakeasyVersion: 1.808.1 sources: OpenRouter API: sourceNamespace: open-router-chat-completions-api - sourceRevisionDigest: sha256:b1ef5f27d7c77d01346cffa2dad6f9148a5f8230f1ec3a07e44b6e88f8360fff - sourceBlobDigest: sha256:ed93555bcb06d452ae3ba7137cdf7d75bc5bfcc233adbc6e44fdbd53b0e973c9 + sourceRevisionDigest: sha256:156bdb27a76cafe9a8cb5e591993ea477fb203cd76b75b2e210940306fd853b2 + sourceBlobDigest: sha256:5c3e81867d7b6d9c38dabd7d19083b202928e9bde6707c0502925911c17d5308 tags: - latest - 1.0.0 @@ -11,10 +11,10 @@ targets: openrouter: source: OpenRouter API sourceNamespace: open-router-chat-completions-api - sourceRevisionDigest: sha256:b1ef5f27d7c77d01346cffa2dad6f9148a5f8230f1ec3a07e44b6e88f8360fff - sourceBlobDigest: sha256:ed93555bcb06d452ae3ba7137cdf7d75bc5bfcc233adbc6e44fdbd53b0e973c9 + sourceRevisionDigest: sha256:156bdb27a76cafe9a8cb5e591993ea477fb203cd76b75b2e210940306fd853b2 + sourceBlobDigest: sha256:5c3e81867d7b6d9c38dabd7d19083b202928e9bde6707c0502925911c17d5308 codeSamplesNamespace: open-router-chat-completions-api-typescript-code-samples - codeSamplesRevisionDigest: sha256:fc4556311c1bd186547cfe23b49d4f2a6e2e9d7d1e5abe1e80671780fdcbd83f + codeSamplesRevisionDigest: sha256:4025b56ae8d6b4856845dec105f30d44408a7f5f6de257c1e7eaa01cdbc0cc8c workflow: workflowVersion: 1.0.0 speakeasyVersion: 1.808.1 diff --git a/RELEASES.md b/RELEASES.md index 4e2ba82ea..654ca33a3 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -5986,4 +5986,14 @@ Based on: ### Generated - [typescript v1.5.161] . ### Releases -- [NPM v1.5.161] https://www.npmjs.com/package/@openrouter/sdk/v/1.5.161 - . \ No newline at end of file +- [NPM v1.5.161] https://www.npmjs.com/package/@openrouter/sdk/v/1.5.161 - . + +## 2026-12-02 07:30:31 +### Changes +Based on: +- OpenAPI Doc +- Speakeasy CLI 1.808.1 (2.960.8) https://github.com/speakeasy-api/speakeasy +### Generated +- [typescript v1.5.162] . +### Releases +- [NPM v1.5.162] https://www.npmjs.com/package/@openrouter/sdk/v/1.5.162 - . \ No newline at end of file diff --git a/docs/models/operations/cancelbatchglobals.mdx b/docs/models/operations/cancelbatchglobals.mdx new file mode 100644 index 000000000..ac1196955 --- /dev/null +++ b/docs/models/operations/cancelbatchglobals.mdx @@ -0,0 +1,19 @@ +--- +title: "CancelBatchGlobals" +--- + +## Example Usage + +```typescript +import { CancelBatchGlobals } from "@openrouter/sdk/models/operations"; + +let value: CancelBatchGlobals = {}; +``` + +## Fields + +| Field | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `httpReferer` | *string* | ➖ | 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.
| +| `appTitle` | *string* | ➖ | The app display name allows you to customize how your app appears in OpenRouter's dashboard.
| +| `appCategories` | *string* | ➖ | 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/models/operations/cancelbatchrequest.mdx b/docs/models/operations/cancelbatchrequest.mdx new file mode 100644 index 000000000..f812f64f3 --- /dev/null +++ b/docs/models/operations/cancelbatchrequest.mdx @@ -0,0 +1,22 @@ +--- +title: "CancelBatchRequest" +--- + +## Example Usage + +```typescript +import { CancelBatchRequest } from "@openrouter/sdk/models/operations"; + +let value: CancelBatchRequest = { + id: "batch_abc123", +}; +``` + +## Fields + +| Field | Type | Required | Description | Example | +| ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | +| `httpReferer` | *string* | ➖ | 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.
| | +| `appTitle` | *string* | ➖ | The app display name allows you to customize how your app appears in OpenRouter's dashboard.
| | +| `appCategories` | *string* | ➖ | Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings.
| | +| `id` | *string* | ✔️ | 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 5f1cbe64c..c33de7d40 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 * [createBatches](#createbatches) - Create a batch * [delete](#delete) - Delete a batch * [getBatches](#getbatches) - Get a batch +* [cancel](#cancel) - Cancel a batch * [getResults](#getresults) - Get batch results ## list @@ -522,6 +523,86 @@ run(); | 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 + +```typescript +import { OpenRouter } from "@openrouter/sdk"; + +const openRouter = new OpenRouter({ + httpReferer: "", + appTitle: "", + appCategories: "", + apiKey: process.env["OPENROUTER_API_KEY"] ?? "", +}); + +async function run() { + const result = await openRouter.batch.cancel({ + id: "batch_abc123", + }); + + console.log(result); +} + +run(); +``` + +### Standalone function + +The standalone function version of this method: + +```typescript +import { OpenRouterCore } from "@openrouter/sdk/core.js"; +import { batchCancel } from "@openrouter/sdk/funcs/batchCancel.js"; + +// Use `OpenRouterCore` for best tree-shaking performance. +// You can create one instance of it to use across an application. +const openRouter = new OpenRouterCore({ + httpReferer: "", + appTitle: "", + appCategories: "", + apiKey: process.env["OPENROUTER_API_KEY"] ?? "", +}); + +async function run() { + const res = await batchCancel(openRouter, { + id: "batch_abc123", + }); + if (res.ok) { + const { value: result } = res; + console.log(result); + } else { + console.log("batchCancel failed:", res.error); + } +} + +run(); +``` + +### Parameters + +| Parameter | Type | Required | Description | +| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `request` | [operations.CancelBatchRequest](../../models/operations/cancelbatchrequest.mdx) | ✔️ | The request object to use for the request. | +| `options` | RequestOptions | ➖ | Used to set various options for making HTTP requests. | +| `options.fetchOptions` | [RequestInit](https://developer.mozilla.org/en-US/docs/Web/API/Request/Request#options) | ➖ | Options that are passed to the underlying HTTP request. This can be used to inject extra headers for examples. All `Request` options, except `method` and `body`, are allowed. | +| `options.retries` | [RetryConfig](../../lib/utils/retryconfig.mdx) | ➖ | Enables retrying HTTP requests under certain failure conditions. | + +### Response + +**Promise\<[models.BatchObject](../../models/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 | \*/\* | + ## getResults 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 925aacc00..2c188a456 100644 --- a/docs/sdks/models/README.mdx +++ b/docs/sdks/models/README.mdx @@ -99,7 +99,7 @@ run(); ## 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/jsr.json b/jsr.json index d9c847268..dbdfe4830 100644 --- a/jsr.json +++ b/jsr.json @@ -2,7 +2,7 @@ { "name": "@openrouter/sdk", - "version": "1.5.161", + "version": "1.5.162", "exports": { ".": "./src/index.ts", "./models/errors": "./src/models/errors/index.ts", diff --git a/package.json b/package.json index 1cb77cc64..d6fd55b2e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@openrouter/sdk", - "version": "1.5.161", + "version": "1.5.162", "author": "OpenRouter", "description": "The OpenRouter TypeScript SDK is a type-safe toolkit for building AI applications with access to 400+ language models through a unified API.", "keywords": [ @@ -21,8 +21,8 @@ "license": "Apache-2.0", "packageManager": "pnpm@10.22.0", "publishConfig": { - "provenance": true, - "access": "public" + "access": "public", + "provenance": true }, "type": "module", "main": "./esm/index.js", @@ -74,13 +74,13 @@ "build": "node --max-old-space-size=8192 ./node_modules/typescript/bin/tsc && node scripts/unbarrel-imports.js", "prepublishOnly": "npm run build", "compile": "node --max-old-space-size=8192 ./node_modules/typescript/bin/tsc && node scripts/unbarrel-imports.js", - "test": "vitest --run --project unit", - "postinstall": "node scripts/check-types.js || true", "prepare": "npm run build", - "test:e2e": "vitest --run --project e2e", + "test": "vitest --run --project unit", "test:transit": "exit 0", "test:watch": "vitest --watch --project unit", "typecheck": "tsc --noEmit", + "postinstall": "node scripts/check-types.js || true", + "test:e2e": "vitest --run --project e2e", "typecheck:transit": "exit 0" }, "peerDependencies": { diff --git a/src/funcs/batchCancel.ts b/src/funcs/batchCancel.ts new file mode 100644 index 000000000..8c6b88d4a --- /dev/null +++ b/src/funcs/batchCancel.ts @@ -0,0 +1,206 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import { OpenRouterCore } from "../core.js"; +import { encodeSimple } from "../lib/encodings.js"; +import { matchStatusCode } from "../lib/http.js"; +import * as M from "../lib/matchers.js"; +import { compactMap } from "../lib/primitives.js"; +import { safeParse } from "../lib/schemas.js"; +import { RequestOptions } from "../lib/sdks.js"; +import { extractSecurity, resolveGlobalSecurity } from "../lib/security.js"; +import { pathToFunc } from "../lib/url.js"; +import { + ConnectionError, + InvalidRequestError, + RequestAbortedError, + RequestTimeoutError, + UnexpectedClientError, +} from "../models/errors/httpclienterrors.js"; +import * as errors from "../models/errors/index.js"; +import { OpenRouterError } from "../models/errors/openroutererror.js"; +import { ResponseValidationError } from "../models/errors/responsevalidationerror.js"; +import { SDKValidationError } from "../models/errors/sdkvalidationerror.js"; +import * as models from "../models/index.js"; +import * as operations from "../models/operations/index.js"; +import { APICall, APIPromise } from "../types/async.js"; +import { Result } from "../types/fp.js"; + +/** + * Cancel a batch + * + * @remarks + * 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). + */ +export function batchCancel( + client: OpenRouterCore, + request: operations.CancelBatchRequest, + options?: RequestOptions, +): APIPromise< + Result< + models.BatchObject, + | errors.BatchErrorResponse + | OpenRouterError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + > +> { + return new APIPromise($do( + client, + request, + options, + )); +} + +async function $do( + client: OpenRouterCore, + request: operations.CancelBatchRequest, + options?: RequestOptions, +): Promise< + [ + Result< + models.BatchObject, + | errors.BatchErrorResponse + | OpenRouterError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >, + APICall, + ] +> { + const parsed = safeParse( + request, + (value) => operations.CancelBatchRequest$outboundSchema.parse(value), + "Input validation failed", + ); + if (!parsed.ok) { + return [parsed, { status: "invalid" }]; + } + const payload = parsed.value; + const body = null; + + const pathParams = { + id: encodeSimple("id", payload.id, { + explode: false, + charEncoding: "percent", + }), + }; + const path = pathToFunc("/batches/{id}/cancel")(pathParams); + + const headers = new Headers(compactMap({ + Accept: "application/json", + "HTTP-Referer": encodeSimple( + "HTTP-Referer", + payload["HTTP-Referer"] ?? client._options.httpReferer, + { explode: false, charEncoding: "none" }, + ), + "X-OpenRouter-Categories": encodeSimple( + "X-OpenRouter-Categories", + payload.appCategories ?? client._options.appCategories, + { explode: false, charEncoding: "none" }, + ), + "X-OpenRouter-Title": encodeSimple( + "X-OpenRouter-Title", + payload.appTitle ?? client._options.appTitle, + { explode: false, charEncoding: "none" }, + ), + })); + + const secConfig = await extractSecurity(client._options.apiKey); + const securityInput = secConfig == null ? {} : { apiKey: secConfig }; + const requestSecurity = resolveGlobalSecurity(securityInput); + + const context = { + options: client._options, + baseURL: options?.serverURL ?? client._baseURL ?? "", + operationID: "cancelBatch", + oAuth2Scopes: null, + + resolvedSecurity: requestSecurity, + + securitySource: client._options.apiKey, + retryConfig: options?.retries + || client._options.retryConfig + || { + strategy: "backoff", + backoff: { + initialInterval: 500, + maxInterval: 60000, + exponent: 1.5, + maxElapsedTime: 3600000, + }, + retryConnectionErrors: true, + } + || { strategy: "none" }, + retryCodes: options?.retryCodes || ["5XX"], + }; + + const requestRes = client._createRequest(context, { + security: requestSecurity, + method: "POST", + baseURL: options?.serverURL, + path: path, + headers: headers, + body: body, + userAgent: client._options.userAgent, + timeoutMs: options?.timeoutMs || client._options.timeoutMs || -1, + }, options); + if (!requestRes.ok) { + return [requestRes, { status: "invalid" }]; + } + const req = requestRes.value; + + const doResult = await client._do(req, { + context, + isErrorStatusCode: (statusCode: number) => + matchStatusCode({ status: statusCode } as Response, ["4XX", "5XX"]), + retryConfig: context.retryConfig, + retryCodes: context.retryCodes, + }); + if (!doResult.ok) { + return [doResult, { status: "request-error", request: req }]; + } + const response = doResult.value; + + const responseFields = { + HttpMeta: { Response: response, Request: req }, + }; + + const [result] = await M.match< + models.BatchObject, + | errors.BatchErrorResponse + | OpenRouterError + | ResponseValidationError + | ConnectionError + | RequestAbortedError + | RequestTimeoutError + | InvalidRequestError + | UnexpectedClientError + | SDKValidationError + >( + M.json(200, models.BatchObject$inboundSchema), + M.jsonErr( + [400, 401, 403, 404, 409, 429], + errors.BatchErrorResponse$inboundSchema, + ), + M.jsonErr([500, 502, 503], errors.BatchErrorResponse$inboundSchema), + M.fail("4XX"), + M.fail("5XX"), + )(response, req, { extraFields: responseFields }); + if (!result.ok) { + return [result, { status: "complete", request: req, response }]; + } + + return [result, { status: "complete", request: req, response }]; +} diff --git a/src/funcs/modelsList.ts b/src/funcs/modelsList.ts index 30f54a1fa..6dbe225ce 100644 --- a/src/funcs/modelsList.ts +++ b/src/funcs/modelsList.ts @@ -34,6 +34,9 @@ import { /** * List all models and their properties + * + * @remarks + * 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`. */ export function modelsList( client: OpenRouterCore, diff --git a/src/lib/config.ts b/src/lib/config.ts index f45c5ec11..814d6895a 100644 --- a/src/lib/config.ts +++ b/src/lib/config.ts @@ -74,7 +74,7 @@ export function serverURLFromOptions(options: SDKOptions): URL | null { export const SDK_METADATA = { language: "typescript", openapiDocVersion: "1.0.0", - sdkVersion: "1.5.161", + sdkVersion: "1.5.162", genVersion: "2.960.8", - userAgent: "speakeasy-sdk/typescript 1.5.161 2.960.8 1.0.0 @openrouter/sdk", + userAgent: "speakeasy-sdk/typescript 1.5.162 2.960.8 1.0.0 @openrouter/sdk", } as const; diff --git a/src/models/operations/cancelbatch.ts b/src/models/operations/cancelbatch.ts new file mode 100644 index 000000000..955c8c195 --- /dev/null +++ b/src/models/operations/cancelbatch.ts @@ -0,0 +1,85 @@ +/* + * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. + */ + +import * as z from "zod/v4"; +import { remap as remap$ } from "../../lib/primitives.js"; + +export type CancelBatchGlobals = { + /** + * The app identifier should be your app's URL and is used as the primary identifier for rankings. + * + * @remarks + * This is used to track API usage per application. + */ + httpReferer?: string | undefined; + /** + * The app display name allows you to customize how your app appears in OpenRouter's dashboard. + * + * @remarks + */ + appTitle?: string | undefined; + /** + * Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings. + * + * @remarks + */ + appCategories?: string | undefined; +}; + +export type CancelBatchRequest = { + /** + * The app identifier should be your app's URL and is used as the primary identifier for rankings. + * + * @remarks + * This is used to track API usage per application. + */ + httpReferer?: string | undefined; + /** + * The app display name allows you to customize how your app appears in OpenRouter's dashboard. + * + * @remarks + */ + appTitle?: string | undefined; + /** + * Comma-separated list of app categories (e.g. "cli-agent,cloud-agent"). Used for marketplace rankings. + * + * @remarks + */ + appCategories?: string | undefined; + /** + * The batch job id returned from submit. + */ + id: string; +}; + +/** @internal */ +export type CancelBatchRequest$Outbound = { + "HTTP-Referer"?: string | undefined; + appTitle?: string | undefined; + appCategories?: string | undefined; + id: string; +}; + +/** @internal */ +export const CancelBatchRequest$outboundSchema: z.ZodType< + CancelBatchRequest$Outbound, + CancelBatchRequest +> = z.object({ + httpReferer: z.string().optional(), + appTitle: z.string().optional(), + appCategories: z.string().optional(), + id: z.string(), +}).transform((v) => { + return remap$(v, { + httpReferer: "HTTP-Referer", + }); +}); + +export function cancelBatchRequestToJSON( + cancelBatchRequest: CancelBatchRequest, +): string { + return JSON.stringify( + CancelBatchRequest$outboundSchema.parse(cancelBatchRequest), + ); +} diff --git a/src/models/operations/index.ts b/src/models/operations/index.ts index 45c11f921..055d51fbb 100644 --- a/src/models/operations/index.ts +++ b/src/models/operations/index.ts @@ -9,6 +9,7 @@ export * from "./bulkassignmemberstoguardrail.js"; export * from "./bulkremoveworkspacemembers.js"; export * from "./bulkunassignkeysfromguardrail.js"; export * from "./bulkunassignmembersfromguardrail.js"; +export * from "./cancelbatch.js"; export * from "./changeapikeypolicyassignment.js"; export * from "./changememberpolicyassignment.js"; export * from "./copyvaultsecretstointern.js"; diff --git a/src/sdk/batch.ts b/src/sdk/batch.ts index ff873d228..f37e91c08 100644 --- a/src/sdk/batch.ts +++ b/src/sdk/batch.ts @@ -2,6 +2,7 @@ * Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT. */ +import { batchCancel } from "../funcs/batchCancel.js"; import { batchCreateBatches } from "../funcs/batchCreateBatches.js"; import { batchDelete } from "../funcs/batchDelete.js"; import { batchGetBatches } from "../funcs/batchGetBatches.js"; @@ -82,6 +83,23 @@ export class Batch extends ClientSDK { )); } + /** + * Cancel a batch + * + * @remarks + * 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). + */ + async cancel( + request: operations.CancelBatchRequest, + options?: RequestOptions, + ): Promise { + return unwrapAsync(batchCancel( + this, + request, + options, + )); + } + /** * Get batch results * diff --git a/src/sdk/models.ts b/src/sdk/models.ts index 8aaad86ae..99184db4b 100644 --- a/src/sdk/models.ts +++ b/src/sdk/models.ts @@ -32,6 +32,9 @@ export class Models extends ClientSDK { /** * List all models and their properties + * + * @remarks + * 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`. */ async list( request?: operations.GetModelsRequest | undefined,