diff --git a/.eslintignore b/.eslintignore new file mode 100644 index 0000000..654372f --- /dev/null +++ b/.eslintignore @@ -0,0 +1,5 @@ +# Vendored upstream source retains Effect's formatting and lint baseline. Local fork changes are +# covered by focused runtime tests and typechecks; do not rewrite the complete upstream surface. +packages/effect-ai-openai/src/** +packages/effect-ai-anthropic/src/** +packages/effect-ai-openai-compat/src/** diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..39f8a79 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,4 @@ +# Vendored upstream source retains Effect's formatting. Local tests, package metadata, and provenance remain formatted. +packages/effect-ai-openai/src/** +packages/effect-ai-anthropic/src/** +packages/effect-ai-openai-compat/src/** diff --git a/bun.lock b/bun.lock index 32c37e4..42bc127 100644 --- a/bun.lock +++ b/bun.lock @@ -17,6 +17,42 @@ "vitest": "catalog:", }, }, + "packages/effect-ai-anthropic": { + "name": "@humanlayer/effect-ai-anthropic", + "version": "0.0.0", + "devDependencies": { + "@effect/vitest": "catalog:", + "@humanlayer/fold-vitest-config": "workspace:*", + "effect": "catalog:", + }, + "peerDependencies": { + "effect": "catalog:", + }, + }, + "packages/effect-ai-openai": { + "name": "@humanlayer/effect-ai-openai", + "version": "0.0.0", + "devDependencies": { + "@effect/vitest": "catalog:", + "@humanlayer/fold-vitest-config": "workspace:*", + "effect": "catalog:", + }, + "peerDependencies": { + "effect": "catalog:", + }, + }, + "packages/effect-ai-openai-compat": { + "name": "@humanlayer/effect-ai-openai-compat", + "version": "0.0.0", + "devDependencies": { + "@effect/vitest": "catalog:", + "@humanlayer/fold-vitest-config": "workspace:*", + "effect": "catalog:", + }, + "peerDependencies": { + "effect": "catalog:", + }, + }, "packages/effect-branded-id": { "name": "@humanlayer/effect-branded-id", "version": "0.0.0", @@ -104,10 +140,10 @@ "name": "@humanlayer/fold-codex", "version": "0.0.0", "dependencies": { + "@humanlayer/effect-ai-openai": "workspace:*", "@humanlayer/fold-core": "workspace:*", }, "devDependencies": { - "@effect/ai-openai": "catalog:", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@humanlayer/fold-agent": "workspace:*", @@ -117,7 +153,6 @@ "vitest": "catalog:", }, "peerDependencies": { - "@effect/ai-openai": "catalog:", "@effect/platform-node": "catalog:", "effect": "catalog:", }, @@ -126,11 +161,11 @@ "name": "@humanlayer/fold-core", "version": "0.0.0", "dependencies": { + "@humanlayer/effect-ai-anthropic": "workspace:*", + "@humanlayer/effect-ai-openai": "workspace:*", "@humanlayer/effect-branded-id": "workspace:*", }, "devDependencies": { - "@effect/ai-anthropic": "catalog:", - "@effect/ai-openai": "catalog:", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@humanlayer/fold-vitest-config": "workspace:*", @@ -139,8 +174,6 @@ "vitest": "catalog:", }, "peerDependencies": { - "@effect/ai-anthropic": "catalog:", - "@effect/ai-openai": "catalog:", "effect": "catalog:", }, }, @@ -148,11 +181,11 @@ "name": "@humanlayer/fold-opencode", "version": "0.0.0", "dependencies": { + "@humanlayer/effect-ai-openai": "workspace:*", + "@humanlayer/effect-ai-openai-compat": "workspace:*", "@humanlayer/fold-core": "workspace:*", }, "devDependencies": { - "@effect/ai-openai": "catalog:", - "@effect/ai-openai-compat": "catalog:", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@humanlayer/fold-vitest-config": "workspace:*", @@ -161,8 +194,6 @@ "vitest": "catalog:", }, "peerDependencies": { - "@effect/ai-openai": "catalog:", - "@effect/ai-openai-compat": "catalog:", "@effect/platform-node": "catalog:", "effect": "catalog:", }, @@ -188,10 +219,10 @@ "name": "@humanlayer/fold-xai", "version": "0.0.0", "dependencies": { + "@humanlayer/effect-ai-openai-compat": "workspace:*", "@humanlayer/fold-core": "workspace:*", }, "devDependencies": { - "@effect/ai-openai-compat": "catalog:", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@humanlayer/fold-vitest-config": "workspace:*", @@ -200,7 +231,6 @@ "vitest": "catalog:", }, "peerDependencies": { - "@effect/ai-openai-compat": "catalog:", "@effect/platform-node": "catalog:", "effect": "catalog:", }, @@ -213,13 +243,7 @@ }, }, }, - "patchedDependencies": { - "@effect/ai-openai@4.0.0-rc.112": "patches/@effect%2Fai-openai@4.0.0-rc.112.patch", - }, "catalog": { - "@effect/ai-anthropic": "4.0.0-rc.112", - "@effect/ai-openai": "4.0.0-rc.112", - "@effect/ai-openai-compat": "4.0.0-rc.112", "@effect/platform-node": "4.0.0-rc.112", "@effect/vitest": "4.0.0-rc.112", "@kitlangton/terminal-control": "0.3.1", @@ -299,12 +323,6 @@ "@bcoe/v8-coverage": ["@bcoe/v8-coverage@1.0.2", "", {}, "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA=="], - "@effect/ai-anthropic": ["@effect/ai-anthropic@4.0.0-rc.112", "", { "peerDependencies": { "effect": "^4.0.0-rc.112" } }, "sha512-2GQKD3IzfCJuS3DgeuBwUjEYk5iyOqgK5etQkYZ3Ho8IuL8BtGR9d8G5AIiRV0xkNy5DD4vGnDGSHxKWsW2TRg=="], - - "@effect/ai-openai": ["@effect/ai-openai@4.0.0-rc.112", "", { "peerDependencies": { "effect": "^4.0.0-rc.112" } }, "sha512-j2X86xvgpAtNiusyESADHZn3PUzMVatE1zWXd0No2aybx/euKiVBVWZOtzq7ntJ5KvPHRBOFXTGPADdApQrwug=="], - - "@effect/ai-openai-compat": ["@effect/ai-openai-compat@4.0.0-rc.112", "", { "peerDependencies": { "effect": "^4.0.0-rc.112" } }, "sha512-bfNYHgfjhzKhDwaw2na75JshGACrawSXWqqzTncBtBHpUIhZ+VHF2I5AdgCmfh6fnAuvhxcuJnzrixGOkG9YZw=="], - "@effect/platform-node": ["@effect/platform-node@4.0.0-rc.112", "", { "dependencies": { "@effect/platform-node-shared": "^4.0.0-rc.112", "mime": "^4.1.0", "undici": "^8.10.0" }, "peerDependencies": { "effect": "^4.0.0-rc.112", "redis": ">=5.0.0 <7.0.0" } }, "sha512-/BMAcdNGQQskLmI0Zoa95KfTZkr9HV9N4NSxaSrusG6GeW6Ulp9KvZ+Rlaiw8lnOt43CXjFLdfll5/k5rxL4hQ=="], "@effect/platform-node-shared": ["@effect/platform-node-shared@4.0.0-rc.112", "", { "dependencies": { "@types/ws": "^8.18.1", "ws": "^8.21.3" }, "peerDependencies": { "effect": "^4.0.0-rc.112" } }, "sha512-ttjz0xKamFN7vL8pNDYVwddJLjZvqKePc05djlz2VcdaKbLsnYbtMnL1rbOfHgEnIUSHGh7FkjaN4DM1Ov81sQ=="], @@ -333,6 +351,12 @@ "@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-c95qOXkHdydNKhscBTebqEC1CVAZpyqOfVfBzQ1qgzyl3gfeldUjIggDbIZgDKsHLgnsM+igH7TJ/eAasaVuMA=="], + "@humanlayer/effect-ai-anthropic": ["@humanlayer/effect-ai-anthropic@workspace:packages/effect-ai-anthropic"], + + "@humanlayer/effect-ai-openai": ["@humanlayer/effect-ai-openai@workspace:packages/effect-ai-openai"], + + "@humanlayer/effect-ai-openai-compat": ["@humanlayer/effect-ai-openai-compat@workspace:packages/effect-ai-openai-compat"], + "@humanlayer/effect-branded-id": ["@humanlayer/effect-branded-id@workspace:packages/effect-branded-id"], "@humanlayer/fold": ["@humanlayer/fold@workspace:packages/fold"], diff --git a/docs/publishing.md b/docs/publishing.md index 40e1fd2..a8e046c 100644 --- a/docs/publishing.md +++ b/docs/publishing.md @@ -2,43 +2,116 @@ Releases are driven by pushed `v*` tags. `v1.2.3` publishes with the npm `latest` dist-tag. A prerelease uses its first prerelease identifier, so `v1.2.3-rc.2` publishes with `rc`. +## Effect AI provider fork versions + +The three vendored provider packages are regular Fold libraries. Every Fold release publishes the matching version of: + +- `@humanlayer/effect-ai-openai` +- `@humanlayer/effect-ai-anthropic` +- `@humanlayer/effect-ai-openai-compat` + +For example, a Fold `v1.2.3` release publishes all three providers at `1.2.3`. This release version is independent +from the upstream Effect provider version. Each package's `UPSTREAM.md` records the exact upstream package artifact, +immutable checksum, import date, and HumanLayer delta used by that Fold release. + ## One-time npm setup -Trusted publishing cannot create a package. The first version of every package must be published manually by an npm owner: +Trusted publishing cannot create a package. A package's first version must be published manually by an npm owner. + +### Initial release of the complete package family + +For an initial Fold release, run the full build and staging process locally: + +```bash +bun install --frozen-lockfile +bun run typecheck +bun run test +bun run build:packages --version 0.1.0 +bun run build:binaries --version 0.1.0 +bun run release:prepare --version 0.1.0 +bun run release:validate --version 0.1.0 +bun run release:publish --version 0.1.0 --tag latest --dry-run +``` + +Authenticate and publish. The script publishes libraries (ending with `@humanlayer/fold-cli`), native packages, and +finally `@humanlayer/fold`. It is safe to rerun after a partial publish because existing package versions are skipped. + +```bash +npm login +bun run release:publish --version 0.1.0 --tag latest +``` + +npm may briefly return `404` for a newly created package even though retrying the publish returns `403` because the +version already exists. During that registry propagation window, explicitly skip a version you have verified was +published: + +```bash +bun run release:publish --version 0.1.0 --tag latest --skip @humanlayer/effect-branded-id +``` + +Repeat `--skip PACKAGE_NAME` for multiple verified packages if necessary. Do not skip a package based only on a failed +publish; confirm it appears in the npm organization's package access list first. -1. Run the full build and staging process locally: +### Adding the Effect AI provider packages - ```bash - bun install --frozen-lockfile - bun run typecheck - bun run test - bun run build:packages --version 0.1.0 - bun run build:binaries --version 0.1.0 - bun run release:prepare --version 0.1.0 - bun run release:validate --version 0.1.0 - bun run release:publish --version 0.1.0 --tag latest --dry-run - ``` +The provider packages are being added to an existing release family. Do **not** use the complete-family publishing +command above: first create only the three new npm packages. npm cannot configure trusted publishing for a package +that does not yet exist. Use a unique bootstrap prerelease that will never be referenced by a Fold dependency, then +publish only the three staged provider directories from an npm-owner's machine: -2. Authenticate and publish. The script publishes libraries (ending with `@humanlayer/fold-cli`), native packages, and finally `@humanlayer/fold`. It is safe to rerun after a partial publish because existing package versions are skipped. +```bash +export VERSION=0.1.0-provider-bootstrap.0 # choose an unused prerelease version + +bun run build:packages --version "$VERSION" +bun run build:binaries --version "$VERSION" +bun run release:prepare --version "$VERSION" +bun run release:validate --version "$VERSION" + +npm login +for package in effect-ai-openai effect-ai-anthropic effect-ai-openai-compat; do + (cd ".release/packages/$package" && npm pack --dry-run && npm publish --access public --tag bootstrap) +done +``` - ```bash - npm login - bun run release:publish --version 0.1.0 --tag latest - ``` +For a package's first publish, npm also creates a `latest` tag even when `--tag bootstrap` is supplied. npm rejects +removing that tag while it is the package's only published version. Leave it in place: the next normal Fold release +will move `latest` to the corresponding stable provider version. - npm may briefly return `404` for a newly created package even though retrying the publish returns `403` because the version already exists. During that registry propagation window, explicitly skip a version you have verified was published: +Check each result with `npm view @humanlayer/PACKAGE_NAME@"$VERSION" version`. The next normal Fold release publishes +the corresponding provider package at its Fold release version through trusted publishing. - ```bash - bun run release:publish --version 0.1.0 --tag latest --skip @humanlayer/effect-branded-id - ``` +### Trusted publishing - Repeat `--skip PACKAGE_NAME` for multiple verified packages if necessary. Do not skip a package based only on a failed publish; confirm it appears in the npm organization's package access list first. +Trusted publishing is configured per existing npm package. Upgrade to npm 11.15 or later, ensure that 2FA is enabled +on the npm account, then add GitHub Actions as the trusted publisher. The first command requires interactive 2FA; npm +offers a five-minute grace period to approve the remaining commands without another challenge. - After trusted publishing is configured, a partial release can also be resumed from GitHub Actions. Run the `Release` workflow manually with the same version and npm tag, and provide already-published packages as a comma-separated `skip` value. Manual recovery runs publish packages but do not create a GitHub Release; the normal tag-triggered run creates it after publication completes. +```bash +npm install --global npm@^11.15.0 + +for package in effect-ai-openai effect-ai-anthropic effect-ai-openai-compat; do + npm trust github "@humanlayer/$package" \ + --repository humanlayer/fold \ + --file release.yml \ + --allow-publish \ + --yes + sleep 2 +done + +for package in effect-ai-openai effect-ai-anthropic effect-ai-openai-compat; do + npm trust list "@humanlayer/$package" +done +``` -3. On npmjs.com, configure a GitHub Actions trusted publisher for every package. Use repository `humanlayer/fold` and workflow filename `release.yml`. +Leave the GitHub environment unspecified: the current release job does not declare one. npm requires this configuration +independently for each package. The trusted publisher must be added to all eleven library packages (including +`@humanlayer/fold-cli`), all twelve `@humanlayer/fold-*` native packages, and `@humanlayer/fold` (24 packages total). +Do not specify a GitHub environment unless the release workflow is updated to use the same protected environment. -The trusted publisher must be added to all eight library packages (including `@humanlayer/fold-cli`), all twelve `@humanlayer/fold-*` native packages, and `@humanlayer/fold` (21 packages total). Do not specify a GitHub environment because the release job does not use one. +After trusted publishing is configured, a partial release can be resumed from GitHub Actions. Run the `Release` +workflow manually with the same version and npm tag, and provide already-published packages as a comma-separated +`skip` value. Manual recovery runs publish packages but does not create a GitHub Release; the normal tag-triggered run +creates it after publication completes. ## Install choices diff --git a/package.json b/package.json index 11878d6..b432a5f 100644 --- a/package.json +++ b/package.json @@ -8,12 +8,13 @@ "scripts": { "build": "bun run build:packages", "build:packages": "bun run scripts/build/packages.ts", + "build:providers": "bun run scripts/build/packages.ts --providers --quiet", "build:binaries": "bun run scripts/build/binaries.ts", "release:tag-info": "bun run scripts/release/tag-info.ts", "release:prepare": "bun run scripts/release/prepare.ts", "release:validate": "bun run scripts/release/validate-manifest.ts", "release:publish": "bun run scripts/release/publish.ts", - "typecheck": "bun run --parallel --if-present --filter './packages/*' typecheck", + "typecheck": "bun run build:providers && bun run --parallel --if-present --filter './packages/*' typecheck", "test": "bun run --parallel --if-present --filter './packages/*' test", "test:watch": "bun run --parallel --if-present --filter './packages/*' test:watch", "lint": "oxlint --type-aware", @@ -33,8 +34,6 @@ "@opentui/solid": "0.4.3", "solid-js": "1.9.12", "effect": "4.0.0-rc.112", - "@effect/ai-openai": "4.0.0-rc.112", - "@effect/ai-openai-compat": "4.0.0-rc.112", "@effect/platform-node": "4.0.0-rc.112", "@effect/vitest": "4.0.0-rc.112", "@silvia-odwyer/photon-node": "0.3.4", @@ -45,8 +44,7 @@ "@vitest/coverage-v8": "4.1.9", "typescript": "7.0.2", "@types/bun": "1.3.14", - "@types/node": "26.1.0", - "@effect/ai-anthropic": "4.0.0-rc.112" + "@types/node": "26.1.0" } }, "devDependencies": { @@ -60,8 +58,5 @@ "oxlint-tsgolint": "0.24.0", "typescript": "catalog:", "vitest": "catalog:" - }, - "patchedDependencies": { - "@effect/ai-openai@4.0.0-rc.112": "patches/@effect%2Fai-openai@4.0.0-rc.112.patch" } } diff --git a/packages/effect-ai-anthropic/LICENSE b/packages/effect-ai-anthropic/LICENSE new file mode 100644 index 0000000..be1f5c1 --- /dev/null +++ b/packages/effect-ai-anthropic/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Effectful Technologies Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/effect-ai-anthropic/README.md b/packages/effect-ai-anthropic/README.md new file mode 100644 index 0000000..7617c5b --- /dev/null +++ b/packages/effect-ai-anthropic/README.md @@ -0,0 +1,14 @@ +# @humanlayer/effect-ai-anthropic + +An [Anthropic](https://www.anthropic.com) provider for the Effect AI modules. Includes a typed Anthropic API client, language model layers, tools, and telemetry helpers. + +## Installation + +```sh +npm install effect@4.0.0-rc.112 @humanlayer/effect-ai-anthropic +``` + +## Documentation + +- [Effect website](https://effect.website) +- [API reference](https://effect.website/docs/v4/api/ai-anthropic) diff --git a/packages/effect-ai-anthropic/UPSTREAM.md b/packages/effect-ai-anthropic/UPSTREAM.md new file mode 100644 index 0000000..6c111b2 --- /dev/null +++ b/packages/effect-ai-anthropic/UPSTREAM.md @@ -0,0 +1,28 @@ +# Upstream provenance + +This directory is a vendored source snapshot of the published Effect Anthropic provider. It does not contain upstream +`dist/` output. + +| Field | Value | +| ---------------- | ------------------------------------------------------------------------------------------------- | +| Upstream package | `@effect/ai-anthropic@4.0.0-rc.112` | +| Source artifact | `https://registry.npmjs.org/@effect/ai-anthropic/-/ai-anthropic-4.0.0-rc.112.tgz` | +| npm integrity | `sha512-2GQKD3IzfCJuS3DgeuBwUjEYk5iyOqgK5etQkYZ3Ho8IuL8BtGR9d8G5AIiRV0xkNy5DD4vGnDGSHxKWsW2TRg==` | +| Tarball SHA-256 | `4a1bc081405cd7b11e7b4a2f4d1f5eb113b72270ed58043fbd7d104b29e473fc` | +| Imported at | `2026-09-03` | +| Imported inputs | `src/**`, `README.md`, and `LICENSE` | +| License | MIT; copied to [`LICENSE`](./LICENSE) | + +## HumanLayer delta + +- `src/AnthropicLanguageModel.ts` preserves string tool results, converts ordered `Prompt` text/image parts into + Anthropic `tool_result` content, and continues to JSON-stringify unknown result objects. +- Provider service/config keys use the `@humanlayer/effect-ai-anthropic` namespace so upstream and forked layers + cannot satisfy one another accidentally in the same Effect context. +- `test/HumanlayerFork.test.ts` covers the changed behavior through the public HumanLayer provider package. + +## Refresh rule + +Refresh from a released npm package or an explicit immutable upstream commit that has been verified against the +supported `effect` peer runtime. Update this table and review the full source diff; do not sync from a moving branch +reference or hand-edit generated `src/Generated.ts`. diff --git a/packages/effect-ai-anthropic/package.json b/packages/effect-ai-anthropic/package.json new file mode 100644 index 0000000..89b2269 --- /dev/null +++ b/packages/effect-ai-anthropic/package.json @@ -0,0 +1,37 @@ +{ + "name": "@humanlayer/effect-ai-anthropic", + "version": "0.0.0", + "private": true, + "license": "MIT", + "type": "module", + "description": "HumanLayer's vendored Anthropic provider for Effect AI SDK", + "sideEffects": [], + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./dist/index.d.ts", + "import": "./src/index.ts", + "default": "./src/index.ts" + }, + "./*": { + "types": "./dist/*.d.ts", + "import": "./src/*.ts", + "default": "./src/*.ts" + }, + "./internal/*": null, + "./index": null, + "./*/index": null + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun vitest run test/HumanlayerFork.test.ts" + }, + "peerDependencies": { + "effect": "catalog:" + }, + "devDependencies": { + "@effect/vitest": "catalog:", + "@humanlayer/fold-vitest-config": "workspace:*", + "effect": "catalog:" + } +} diff --git a/packages/effect-ai-anthropic/src/AnthropicClient.ts b/packages/effect-ai-anthropic/src/AnthropicClient.ts new file mode 100644 index 0000000..d9b672e --- /dev/null +++ b/packages/effect-ai-anthropic/src/AnthropicClient.ts @@ -0,0 +1,437 @@ +/** + * The `AnthropicClient` module defines the low-level Effect service for + * Anthropic's Messages API. It builds a generated Anthropic HTTP client with + * authentication headers, API version headers, response decoding, and error + * mapping, then exposes helpers for regular and streaming message requests. + * + * @since 4.0.0 + */ +import * as Array from "effect/Array" +import type * as Config from "effect/Config" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { identity } from "effect/Function" +import * as Layer from "effect/Layer" +import * as Predicate from "effect/Predicate" +import * as Redacted from "effect/Redacted" +import * as Schema from "effect/Schema" +import * as Stream from "effect/Stream" +import type * as AiError from "effect/unstable/ai/AiError" +import * as Sse from "effect/unstable/encoding/Sse" +import * as Headers from "effect/unstable/http/Headers" +import * as HttpBody from "effect/unstable/http/HttpBody" +import * as HttpClient from "effect/unstable/http/HttpClient" +import type * as HttpClientError from "effect/unstable/http/HttpClientError" +import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import { AnthropicConfig } from "./AnthropicConfig.ts" +import * as Generated from "./Generated.ts" +import * as Errors from "./internal/errors.ts" + +// ============================================================================= +// Service Interface +// ============================================================================= + +/** + * Represents the Anthropic client service with methods for the Messages API, including regular and streaming message + * creation. + * + * @category services + * @since 4.0.0 + */ +export interface Service { + /** + * The underlying generated Anthropic client that exposes all API endpoints. + */ + readonly client: Generated.AnthropicClient + + /** + * Executes a low-level streaming HTTP request and decodes the Server-Sent Events response using the provided schema. + */ + readonly streamRequest: ( + schema: S + ) => (request: HttpClientRequest.HttpClientRequest) => Stream.Stream< + S["Type"], + HttpClientError.HttpClientError | Schema.SchemaError | Sse.Retry | Sse.SseError, + S["DecodingServices"] + > + + /** + * Creates a message using the Anthropic Messages API and maps all errors to the unified `AiError` type. + */ + readonly createMessage: (options: { + readonly payload: typeof Generated.BetaCreateMessageParams.Encoded + readonly params?: typeof Generated.BetaMessagesPostParams.Encoded | undefined + }) => Effect.Effect< + [body: typeof Generated.BetaMessage.Type, response: HttpClientResponse.HttpClientResponse], + AiError.AiError + > + + /** + * Creates a streaming message using the Anthropic Messages API and maps all errors to the unified `AiError` type. + * + * **Details** + * + * The returned Effect yields the HTTP response and a stream of events as the model generates its response. The stream + * automatically terminates when a `message_stop` event is received. + */ + readonly createMessageStream: (options: { + readonly payload: Omit + readonly params?: typeof Generated.BetaMessagesPostParams.Encoded | undefined + }) => Effect.Effect< + [response: HttpClientResponse.HttpClientResponse, stream: Stream.Stream], + AiError.AiError + > +} + +/** + * Represents an event received from the Anthropic Messages API during a streaming request. + * + * **Details** + * + * Events include: + * - `message_start`: Initial event containing message metadata + * - `message_delta`: Incremental updates to the message (e.g., stop reason) + * - `message_stop`: Final event indicating the message is complete + * - `content_block_start`: Start of a content block + * - `content_block_delta`: Incremental content updates (text, tool use, etc.) + * - `content_block_stop`: End of a content block + * - `error`: Error events with type and message + * + * @category models + * @since 4.0.0 + */ +export type MessageStreamEvent = + | typeof Generated.BetaMessageStartEvent.Type + | typeof Generated.BetaMessageDeltaEvent.Type + | typeof Generated.BetaMessageStopEvent.Type + | typeof Generated.BetaContentBlockStartEvent.Type + | typeof Generated.BetaContentBlockDeltaEvent.Type + | typeof Generated.BetaContentBlockStopEvent.Type + | typeof Generated.BetaErrorResponse.Type + +// ============================================================================= +// Service Identifier +// ============================================================================= + +/** + * Service tag for the Anthropic client. + * + * **When to use** + * + * Use when accessing or providing the Anthropic client service through Effect's + * context. + * + * @see {@link make} for constructing an Anthropic client effectfully + * @see {@link layer} for providing a client from explicit options + * @see {@link layerConfig} for providing a client from `Config` + * + * @category services + * @since 4.0.0 + */ +export class AnthropicClient extends Context.Service()( + "@humanlayer/effect-ai-anthropic/AnthropicClient" +) {} + +// ============================================================================= +// Options +// ============================================================================= + +/** + * Configuration for creating an Anthropic client. + * + * **When to use** + * + * Use when the Anthropic client settings are already available as values and + * should be passed directly to `make` or `layer`. + * + * **Details** + * + * These options configure the base Anthropic URL, the `x-api-key` + * authentication header, the `anthropic-version` header, and an optional + * transformation of the underlying `HttpClient`. + * + * @see {@link make} for constructing an Anthropic client from explicit options + * @see {@link layer} for providing an Anthropic client from explicit options + * @see {@link layerConfig} for loading Anthropic client settings from `Config` + * + * @category options + * @since 4.0.0 + */ +export type Options = { + /** + * The Anthropic API key for authentication. Requests are made without authentication when this is omitted, which is + * useful for proxied setups or testing. + */ + readonly apiKey?: Redacted.Redacted | undefined + + /** + * The base URL for the Anthropic API. Override this to use a proxy or a different API-compatible endpoint. + * + * @default "https://api.anthropic.com" + */ + readonly apiUrl?: string | undefined + + /** + * The Anthropic API version header value. This controls which version of the API to use. + * + * @default "2023-06-01" + */ + readonly apiVersion?: string | undefined + + /** + * Optional transformer for the underlying HTTP client, such as middleware, logging, or custom request/response + * handling. + */ + readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined +} + +// ============================================================================= +// Constructor +// ============================================================================= + +const RedactedAnthropicHeaders = { + AnthropicApiKey: "x-api-key" +} + +const withRedactedHeaders = Effect.updateService( + Headers.CurrentRedactedNames, + Array.appendAll(Object.values(RedactedAnthropicHeaders)) +) + +/** + * Creates an Anthropic client service with the given options. + * + * **When to use** + * + * Use when you have explicit configuration values and need an `Effect` that + * constructs the Anthropic client service, rather than providing it as a `Layer`. + * + * **Details** + * + * The client handles API key authentication via the `x-api-key` header, API versioning via the `anthropic-version` + * header, error mapping to the unified `AiError` type, and request/response transformations via `AnthropicConfig`. It + * requires an `HttpClient` in the context. + * + * @see {@link layer} for providing the client as a `Layer` from explicit options + * @see {@link layerConfig} for providing the client as a `Layer` with `Config`-based settings + * + * @category constructors + * @since 4.0.0 + */ +export const make = Effect.fnUntraced( + function*(options: Options): Effect.fn.Return { + const baseClient = yield* HttpClient.HttpClient + const apiVersion = options.apiVersion ?? "2023-06-01" + + const httpClient = baseClient.pipe( + HttpClient.mapRequest((request) => + request.pipe( + HttpClientRequest.prependUrl(options.apiUrl ?? "https://api.anthropic.com"), + Predicate.isNotUndefined(options.apiKey) + ? HttpClientRequest.setHeader( + RedactedAnthropicHeaders.AnthropicApiKey, + Redacted.value(options.apiKey) + ) + : identity, + HttpClientRequest.setHeader("anthropic-version", apiVersion), + HttpClientRequest.acceptJson + ) + ), + Predicate.isNotUndefined(options.transformClient) + ? options.transformClient + : identity + ) + + const client = Generated.make(httpClient, { + transformClient: Effect.fnUntraced(function*(client) { + const config = yield* AnthropicConfig.getOrUndefined + if (Predicate.isNotUndefined(config?.transformClient)) { + return config.transformClient(client) + } + return client + }) + }) + + const httpClientOk = HttpClient.filterStatusOk(httpClient) + + const streamRequest = + (schema: S) => + (request: HttpClientRequest.HttpClientRequest): Stream.Stream< + S["Type"], + HttpClientError.HttpClientError | Schema.SchemaError | Sse.Retry | Sse.SseError, + S["DecodingServices"] + > => + httpClientOk.execute(request).pipe( + Effect.map((response) => response.stream), + Stream.unwrap, + Stream.decodeText, + Stream.pipeThroughChannel(Sse.decodeSchema(schema)) + ) + + const createMessage = (options: { + readonly payload: typeof Generated.BetaCreateMessageParams.Encoded + readonly params?: typeof Generated.BetaMessagesPostParams.Encoded | undefined + }): Effect.Effect< + [body: typeof Generated.BetaMessage.Type, response: HttpClientResponse.HttpClientResponse], + AiError.AiError + > => + client.betaMessagesPost({ ...options, config: { includeResponse: true } }).pipe( + Effect.catchTags({ + BetaMessagesPost4XX: (error) => Effect.fail(Errors.mapClientError(error, "createMessage")), + HttpClientError: (error) => Errors.mapHttpClientError(error, "createMessage"), + SchemaError: (error) => Effect.fail(Errors.mapSchemaError(error, "createMessage")) + }), + withRedactedHeaders + ) + + const PingEvent = Schema.Struct({ + type: Schema.Literal("ping") + }) + + const MessageEvent = Schema.Union([ + PingEvent, + Generated.BetaMessageStartEvent, + Generated.BetaMessageDeltaEvent, + Generated.BetaMessageStopEvent, + Generated.BetaContentBlockStartEvent, + Generated.BetaContentBlockDeltaEvent, + Generated.BetaContentBlockStopEvent, + Generated.BetaErrorResponse + ]) + + const buildMessageStream = ( + response: HttpClientResponse.HttpClientResponse + ): [HttpClientResponse.HttpClientResponse, Stream.Stream] => { + const stream = response.stream.pipe( + Stream.decodeText, + Stream.pipeThroughChannel(Sse.decodeDataSchema(MessageEvent)), + Stream.takeUntil((event) => event.data.type === "message_stop"), + Stream.map((event) => event.data), + Stream.filter((event): event is MessageStreamEvent => event.type !== "ping"), + Stream.catchTags({ + // TODO: handle SSE retries + Retry: (error) => Stream.die(error), + SseError: (error) => Stream.fail(Errors.mapSseError(error, "createMessageStream")), + HttpClientError: (error) => Stream.fromEffect(Errors.mapHttpClientError(error, "createMessageStream")), + SchemaError: (error) => Stream.fail(Errors.mapSchemaError(error, "createMessageStream")) + }) + ) as any + return [response, stream] + } + + const createMessageStream: Service["createMessageStream"] = (options) => { + const request = HttpClientRequest.post("/v1/messages", { + headers: Headers.fromInput({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? apiVersion + }), + body: HttpBody.jsonUnsafe({ + ...options.payload, + stream: true + }) + }) + return httpClientOk.execute(request).pipe( + Effect.map(buildMessageStream), + Effect.catchTag( + "HttpClientError", + (error) => Errors.mapHttpClientError(error, "createMessageStream") + ), + withRedactedHeaders + ) + } + + return AnthropicClient.of({ + client, + streamRequest, + createMessage, + createMessageStream + }) + }, + withRedactedHeaders +) + +// ============================================================================= +// Layers +// ============================================================================= + +/** + * Creates a layer for the Anthropic client with the given options. + * + * **When to use** + * + * Use when you already have explicit `Options` values, such as an API key or + * custom API URL, and want to provide `AnthropicClient` as a `Layer`. + * + * @see {@link make} for constructing the client service effectfully + * @see {@link layerConfig} for loading client settings from `Config` + * + * @category layers + * @since 4.0.0 + */ +export const layer = (options: Options): Layer.Layer => + Layer.effect(AnthropicClient, make(options)) + +/** + * Creates a layer for the Anthropic client, loading the requisite configuration + * via Effect's `Config` module. + * + * **When to use** + * + * Use when you want to provide the Anthropic client as a `Layer` with + * configuration loaded from Effect's `Config` module, such as from environment + * variables or a secrets provider. + * + * @see {@link layer} for providing the client from explicit options instead of `Config` + * @see {@link make} for constructing the client service effectfully + * + * @category layers + * @since 4.0.0 + */ +export const layerConfig = (options?: { + /** + * The Anthropic API key for authentication. Requests are made without authentication when this is omitted, which is + * useful for proxied setups or testing. + */ + readonly apiKey?: Config.Config | undefined> | undefined + + /** + * The base URL for the Anthropic API. Override this to use a proxy or a different API-compatible endpoint. + * + * @default "https://api.anthropic.com" + */ + readonly apiUrl?: Config.Config | undefined + + /** + * The Anthropic API version header value. This controls which version of the API to use. + * + * @default "2023-06-01" + */ + readonly apiVersion?: Config.Config | undefined + + /** + * Optional transformer for the underlying HTTP client, such as middleware, logging, or custom request/response + * handling. + */ + readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined +}): Layer.Layer => + Layer.effect( + AnthropicClient, + Effect.gen(function*() { + const apiKey = Predicate.isNotUndefined(options?.apiKey) + ? yield* options.apiKey : + undefined + const apiUrl = Predicate.isNotUndefined(options?.apiUrl) + ? yield* options.apiUrl : + undefined + const apiVersion = Predicate.isNotUndefined(options?.apiVersion) + ? yield* options.apiVersion : + undefined + return yield* make({ + apiKey, + apiUrl, + apiVersion, + transformClient: options?.transformClient + }) + }) + ) diff --git a/packages/effect-ai-anthropic/src/AnthropicConfig.ts b/packages/effect-ai-anthropic/src/AnthropicConfig.ts new file mode 100644 index 0000000..4481983 --- /dev/null +++ b/packages/effect-ai-anthropic/src/AnthropicConfig.ts @@ -0,0 +1,109 @@ +/** + * The `AnthropicConfig` module lets a workflow temporarily customize the HTTP + * client used by generated Anthropic requests. It is used by + * `AnthropicClient` when request helpers run, so code can add middleware, + * logging, or other client changes without rebuilding the client layer. + * + * @since 4.0.0 + */ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { dual } from "effect/Function" +import type { HttpClient } from "effect/unstable/http/HttpClient" + +/** + * Service tag for Anthropic client configuration overrides, such as transformations applied to the generated HTTP client. + * + * **When to use** + * + * Use when you need to provide or read Anthropic client configuration through + * Effect's context from a layer or integration. + * + * @see {@link withClientTransform} for scoping an HTTP client transformation + * + * @category services + * @since 4.0.0 + */ +export class AnthropicConfig extends Context.Service< + AnthropicConfig, + AnthropicConfig.Service +>()("@humanlayer/effect-ai-anthropic/AnthropicConfig") { + /** + * Gets the configured Anthropic service from the current context when present. + * + * @since 4.0.0 + */ + static readonly getOrUndefined: Effect.Effect = Effect.map( + Effect.context(), + Context.getOrUndefined(AnthropicConfig) + ) +} + +/** + * Namespace containing types associated with the `AnthropicConfig` service. + * + * @since 4.0.0 + */ +export declare namespace AnthropicConfig { + /** + * Configuration provided through `AnthropicConfig`. + * + * **Details** + * + * Use `transformClient` to wrap or replace the `HttpClient` used by generated Anthropic API requests. + * + * @category services + * @since 4.0.0 + */ + export interface Service { + readonly transformClient?: ((client: HttpClient) => HttpClient) | undefined + } +} + +/** + * Runs an effect with an `AnthropicConfig` override that transforms the underlying `HttpClient` used by generated Anthropic requests. + * + * **When to use** + * + * Use when you need to apply a temporary `HttpClient` transformation, such as adding middleware or logging, to a + * specific scope of an effectful program. + * + * @category configuration + * @since 4.0.0 + */ +export const withClientTransform: { + /** + * Runs an effect with an `AnthropicConfig` override that transforms the underlying `HttpClient` used by generated Anthropic requests. + * + * **When to use** + * + * Use when you need to apply a temporary `HttpClient` transformation, such as adding middleware or logging, to a + * specific scope of an effectful program. + * + * @category configuration + * @since 4.0.0 + */ + (transform: (client: HttpClient) => HttpClient): (self: Effect.Effect) => Effect.Effect + /** + * Runs an effect with an `AnthropicConfig` override that transforms the underlying `HttpClient` used by generated Anthropic requests. + * + * **When to use** + * + * Use when you need to apply a temporary `HttpClient` transformation, such as adding middleware or logging, to a + * specific scope of an effectful program. + * + * @category configuration + * @since 4.0.0 + */ + ( + self: Effect.Effect, + transform: (client: HttpClient) => HttpClient + ): Effect.Effect +} = dual(2, ( + self: Effect.Effect, + transformClient: (client: HttpClient) => HttpClient +) => + Effect.flatMap( + AnthropicConfig.getOrUndefined, + (config) => Effect.provideService(self, AnthropicConfig, { ...config, transformClient }) + )) diff --git a/packages/effect-ai-anthropic/src/AnthropicError.ts b/packages/effect-ai-anthropic/src/AnthropicError.ts new file mode 100644 index 0000000..590176e --- /dev/null +++ b/packages/effect-ai-anthropic/src/AnthropicError.ts @@ -0,0 +1,212 @@ +/** + * Anthropic error metadata augmentation. + * + * Provides Anthropic-specific metadata fields for AI error types through module + * augmentation, enabling typed access to Anthropic error details. + * + * @since 4.0.0 + */ + +/** + * Anthropic-specific error metadata fields. + * + * **Details** + * + * Contains the Anthropic error type and request identifier copied from provider + * error responses when available. Either field may be `null` when Anthropic + * does not include it or the response cannot be decoded. + * + * @see {@link AnthropicRateLimitMetadata} for rate-limit responses that also include parsed Anthropic rate-limit headers + * + * @category models + * @since 4.0.0 + */ +export type AnthropicErrorMetadata = { + /** + * The Anthropic error type returned by the API. + */ + readonly errorType: string | null + /** + * The unique request ID for debugging with Anthropic support. + */ + readonly requestId: string | null +} + +/** + * Anthropic-specific rate limit metadata fields. + * + * **Details** + * + * Extends base error metadata with rate limit-specific information from Anthropic's rate limit headers. + * + * @category models + * @since 4.0.0 + */ +export type AnthropicRateLimitMetadata = AnthropicErrorMetadata & { + /** + * Number of requests allowed in the current period. + */ + readonly requestsLimit: number | null + /** + * Number of requests remaining in the current period. + */ + readonly requestsRemaining: number | null + /** + * Time when the request rate limit resets. + */ + readonly requestsReset: string | null + /** + * Number of tokens allowed in the current period. + */ + readonly tokensLimit: number | null + /** + * Number of tokens remaining in the current period. + */ + readonly tokensRemaining: number | null + /** + * Time when the token rate limit resets. + */ + readonly tokensReset: string | null +} + +declare module "effect/unstable/ai/AiError" { + /** + * Anthropic metadata attached to `RateLimitError` values. + * + * **Details** + * + * Includes request identifiers, Anthropic error types, and parsed request or token limit headers when the provider rejects a request due to rate limits. + * + * @category models + * @since 4.0.0 + */ + export interface RateLimitErrorMetadata { + readonly anthropic?: AnthropicRateLimitMetadata | null + } + + /** + * Anthropic metadata attached to `QuotaExhaustedError` values. + * + * **Details** + * + * Captures the Anthropic error type and request identifier for failures where the account or workspace has exhausted its available quota. + * + * @category models + * @since 4.0.0 + */ + export interface QuotaExhaustedErrorMetadata { + readonly anthropic?: AnthropicErrorMetadata | null + } + + /** + * Anthropic metadata attached to `AuthenticationError` values. + * + * **Details** + * + * Preserves Anthropic error details for missing, invalid, or unauthorized API credentials while keeping the error in the shared AI error model. + * + * @category models + * @since 4.0.0 + */ + export interface AuthenticationErrorMetadata { + readonly anthropic?: AnthropicErrorMetadata | null + } + + /** + * Anthropic metadata attached to `ContentPolicyError` values. + * + * **Details** + * + * Records Anthropic error details returned when a request or response is rejected by Anthropic safety or content policy enforcement. + * + * @category models + * @since 4.0.0 + */ + export interface ContentPolicyErrorMetadata { + readonly anthropic?: AnthropicErrorMetadata | null + } + + /** + * Anthropic metadata attached to `InvalidRequestError` values. + * + * **Details** + * + * Provides the Anthropic error type and request identifier for malformed or unsupported requests rejected before model execution. + * + * @category models + * @since 4.0.0 + */ + export interface InvalidRequestErrorMetadata { + readonly anthropic?: AnthropicErrorMetadata | null + } + + /** + * Anthropic metadata attached to `InternalProviderError` values. + * + * **Details** + * + * Preserves Anthropic request correlation data for provider-side failures that should be reported or investigated with Anthropic support. + * + * @category models + * @since 4.0.0 + */ + export interface InternalProviderErrorMetadata { + readonly anthropic?: AnthropicErrorMetadata | null + } + + /** + * Anthropic metadata attached to `InvalidOutputError` values. + * + * **Details** + * + * Describes Anthropic-specific context for responses that could not be decoded or interpreted as valid AI output. + * + * @category models + * @since 4.0.0 + */ + export interface InvalidOutputErrorMetadata { + readonly anthropic?: AnthropicErrorMetadata | null + } + + /** + * Anthropic metadata attached to `StructuredOutputError` values. + * + * **Details** + * + * Captures Anthropic error details for structured-output failures, including request correlation data useful when diagnosing schema-related responses. + * + * @category models + * @since 4.0.0 + */ + export interface StructuredOutputErrorMetadata { + readonly anthropic?: AnthropicErrorMetadata | null + } + + /** + * Anthropic metadata attached to `UnsupportedSchemaError` values. + * + * **Details** + * + * Provides Anthropic error details for schemas that cannot be represented by or submitted to the Anthropic API. + * + * @category models + * @since 4.0.0 + */ + export interface UnsupportedSchemaErrorMetadata { + readonly anthropic?: AnthropicErrorMetadata | null + } + + /** + * Anthropic metadata attached to `UnknownError` values. + * + * **Details** + * + * Retains the Anthropic error type and request identifier when a provider response cannot be classified as a more specific AI error. + * + * @category models + * @since 4.0.0 + */ + export interface UnknownErrorMetadata { + readonly anthropic?: AnthropicErrorMetadata | null + } +} diff --git a/packages/effect-ai-anthropic/src/AnthropicLanguageModel.ts b/packages/effect-ai-anthropic/src/AnthropicLanguageModel.ts new file mode 100644 index 0000000..3228e90 --- /dev/null +++ b/packages/effect-ai-anthropic/src/AnthropicLanguageModel.ts @@ -0,0 +1,3245 @@ +/** + * The `AnthropicLanguageModel` module provides the Anthropic implementation of + * Effect AI's `LanguageModel` service. It translates Effect AI prompts, tools, + * files, reasoning content, and Anthropic-specific options into Messages API + * requests, then converts normal and streaming Anthropic responses back into + * Effect AI response content with provider metadata. + * + * @since 4.0.0 + */ +/** @effect-diagnostics preferSchemaOverJson:skip-file */ +import * as Arr from "effect/Array" +import * as Context from "effect/Context" +import * as DateTime from "effect/DateTime" +import * as Effect from "effect/Effect" +import * as Encoding from "effect/Encoding" +import { dual } from "effect/Function" +import * as Layer from "effect/Layer" +import * as Option from "effect/Option" +import * as Predicate from "effect/Predicate" +import * as Redactable from "effect/Redactable" +import * as Schema from "effect/Schema" +import * as SchemaAST from "effect/SchemaAST" +import * as SchemaIssue from "effect/SchemaIssue" +import * as Stream from "effect/Stream" +import type { Span } from "effect/Tracer" +import type { Mutable, Simplify } from "effect/Types" +import * as AiError from "effect/unstable/ai/AiError" +import { toCodecAnthropic } from "effect/unstable/ai/AnthropicStructuredOutput" +import * as IdGenerator from "effect/unstable/ai/IdGenerator" +import * as LanguageModel from "effect/unstable/ai/LanguageModel" +import * as AiModel from "effect/unstable/ai/Model" +import * as Prompt from "effect/unstable/ai/Prompt" +import type * as Response from "effect/unstable/ai/Response" +import * as Tool from "effect/unstable/ai/Tool" +import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import { AnthropicClient, type MessageStreamEvent } from "./AnthropicClient.ts" +import { addGenAIAnnotations } from "./AnthropicTelemetry.ts" +import type { AnthropicTool } from "./AnthropicTool.ts" +import type * as Generated from "./Generated.ts" +import * as InternalUtilities from "./internal/utilities.ts" + +const formatIssue = SchemaIssue.makeFormatterDefault() + +/** + * Known Anthropic Claude model identifiers exposed by the generated Anthropic schema. + * + * @category models + * @since 4.0.0 + */ +export type Model = (typeof Generated.Model)["members"][1]["Encoded"] + +// ============================================================================= +// Configuration +// ============================================================================= + +/** + * Context service for Anthropic language model configuration. + * + * **When to use** + * + * Use when you need scoped Anthropic model request defaults or per-operation + * overrides from Effect context. + * + * **Details** + * + * The service stores request fields that are merged into Anthropic Messages API + * requests. Scoped configuration overrides defaults supplied to `model`, + * `make`, or `layer`. + * + * @category services + * @since 4.0.0 + */ +export class Config extends Context.Service< + Config, + Simplify< + & Partial< + Omit< + typeof Generated.BetaCreateMessageParams.Encoded, + "messages" | "output_config" | "tools" | "tool_choice" | "stream" + > + > + & { + readonly output_config?: { + readonly effort?: "low" | "medium" | "high" | null + } + /** + * Disables Claude's ability to use multiple tools to respond to a query. + */ + readonly disableParallelToolCalls?: boolean | undefined + /** + * Whether the model supports native structured outputs. + * + * Overrides automatic capability detection based on the model identifier. + */ + readonly structuredOutputs?: boolean | undefined + /** + * Whether to use strict JSON schema validation for tool calls. + * + * **Details** + * + * Only applies to models that support structured outputs. Defaults to + * `true` when structured outputs are supported. + */ + readonly strictJsonSchema?: boolean | undefined + } + > +>()("@humanlayer/effect-ai-anthropic/AnthropicLanguageModel/Config") {} + +// ============================================================================= +// Provider Options / Metadata +// ============================================================================= + +declare module "effect/unstable/ai/Prompt" { + /** + * Anthropic-specific options for system messages. + * + * **Details** + * + * These options are used when translating system messages into Anthropic + * request content. + * + * @category models + * @since 4.0.0 + */ + export interface SystemMessageOptions extends ProviderOptions { + readonly anthropic?: { + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } + + /** + * Anthropic-specific options for user messages. + * + * **Details** + * + * These options are used when translating user messages into Anthropic + * request content. + * + * @category models + * @since 4.0.0 + */ + export interface UserMessageOptions extends ProviderOptions { + readonly anthropic?: { + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } + + /** + * Anthropic-specific options for assistant messages. + * + * **Details** + * + * These options are used when replaying assistant messages in Anthropic + * conversation history. + * + * @category models + * @since 4.0.0 + */ + export interface AssistantMessageOptions extends ProviderOptions { + readonly anthropic?: { + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } + + /** + * Anthropic-specific options for tool messages. + * + * **Details** + * + * These options are used when converting tool results into Anthropic user + * content blocks. + * + * @category models + * @since 4.0.0 + */ + export interface ToolMessageOptions extends ProviderOptions { + readonly anthropic?: { + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } + + /** + * Anthropic-specific options for text prompt parts. + * + * **When to use** + * + * Use when you use these options to control how text blocks are sent to Anthropic. + * + * @category models + * @since 4.0.0 + */ + export interface TextPartOptions extends ProviderOptions { + readonly anthropic?: { + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } + + /** + * Anthropic-specific options for reasoning prompt parts. + * + * **Details** + * + * Preserves Claude thinking metadata when reasoning content is sent back to + * Anthropic in later turns. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningPartOptions extends ProviderOptions { + readonly anthropic?: { + readonly info?: { + readonly type: "thinking" + /** + * Thinking content as an encrypted string, which is used to verify + * that thinking content was indeed generated by Anthropic's API. + */ + readonly signature: typeof Generated.ResponseThinkingBlock.fields.thinking.Encoded + } | { + readonly type: "redacted_thinking" + /** + * Thinking content which was flagged by Anthropic's safety systems, and + * was therefore encrypted. + */ + readonly redactedData: typeof Generated.ResponseRedactedThinkingBlock.fields.data.Encoded + } | null + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } + + /** + * Anthropic-specific options for file prompt parts. + * + * **Details** + * + * Controls document metadata, citations, and prompt caching for files sent to + * Anthropic. + * + * @category models + * @since 4.0.0 + */ + export interface FilePartOptions extends ProviderOptions { + readonly anthropic?: { + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + /** + * Whether or not citations should be enabled for the file part. + */ + readonly citations?: typeof Generated.RequestCitationsConfig.Encoded | null + /** + * A custom title to provide to the document. If omitted, the file part's + * `fileName` property will be used. + */ + readonly documentTitle?: string | null + /** + * Additional context about the document that will be forwarded to the + * large language model, but will not be used towards cited content. + * + * **When to use** + * + * Use when storing additional document metadata as text or stringified JSON. + */ + readonly documentContext?: string | null + } | null + } + + /** + * Anthropic-specific options for tool call prompt parts. + * + * **Details** + * + * Carries Anthropic tool caller metadata, MCP metadata, and cache control for + * tool use blocks. + * + * @category models + * @since 4.0.0 + */ + export interface ToolCallPartOptions extends ProviderOptions { + readonly anthropic?: { + readonly caller?: { + readonly type: string + readonly toolId?: string | null + } | null + /** + * Contains details about the MCP tool that was called. + */ + readonly mcp_tool?: { + /** + * The name of the MCP server + */ + readonly server: string + } | null + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } + + /** + * Anthropic-specific options for tool result prompt parts. + * + * **Details** + * + * Carries Anthropic MCP metadata and controls prompt caching for tool result + * content. + * + * @category models + * @since 4.0.0 + */ + export interface ToolResultPartOptions extends ProviderOptions { + readonly anthropic?: { + /** + * Contains details about the MCP tool that produced the result. + */ + readonly mcp_tool?: { + /** + * The name of the MCP server + */ + readonly server: string + } | null + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } + + /** + * Anthropic-specific options for tool approval request prompt parts. + * + * **Details** + * + * Controls prompt caching for human approval requests in conversations. + * + * @category models + * @since 4.0.0 + */ + export interface ToolApprovalRequestPartOptions extends ProviderOptions { + readonly anthropic?: { + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } + + /** + * Anthropic-specific options for tool approval response prompt parts. + * + * **Details** + * + * Controls prompt caching for human approval responses in conversations. + * + * @category models + * @since 4.0.0 + */ + export interface ToolApprovalResponsePartOptions extends ProviderOptions { + readonly anthropic?: { + /** + * A breakpoint which marks the end of reusable content eligible for caching. + */ + readonly cacheControl?: typeof Generated.CacheControlEphemeral.Encoded | null + } | null + } +} + +declare module "effect/unstable/ai/Response" { + /** + * Anthropic metadata attached when a reasoning block begins. + * + * **Details** + * + * Includes Claude thinking metadata needed to continue reasoning-aware + * conversations. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningStartPartMetadata extends ProviderMetadata { + readonly anthropic?: { + readonly info?: { + readonly type: "thinking" + /** + * Thinking content as an encrypted string, which is used to verify + * that thinking content was indeed generated by Anthropic's API. + */ + readonly signature: typeof Generated.ResponseThinkingBlock.fields.thinking.Encoded + } | { + readonly type: "redacted_thinking" + /** + * Thinking content which was flagged by Anthropic's safety systems, and + * was therefore encrypted. + */ + readonly redactedData: typeof Generated.ResponseRedactedThinkingBlock.fields.data.Encoded + } | null + } | null + } + + /** + * Anthropic metadata attached to streaming reasoning deltas. + * + * **Details** + * + * Includes the signature for streamed Claude thinking content when available. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningDeltaPartMetadata extends ProviderMetadata { + readonly anthropic?: { + readonly info?: { + readonly type: "thinking" + /** + * Thinking content as an encrypted string, which is used to verify + * that thinking content was indeed generated by Anthropic's API. + */ + readonly signature: typeof Generated.ResponseThinkingBlock.fields.thinking.Encoded + } | null + } | null + } + + /** + * Anthropic metadata attached to completed reasoning parts. + * + * **Details** + * + * Preserves Claude thinking or redacted thinking information for later turns. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningPartMetadata extends ProviderMetadata { + readonly anthropic?: { + readonly info?: { + readonly type: "thinking" + /** + * Thinking content as an encrypted string, which is used to verify + * that thinking content was indeed generated by Anthropic's API. + */ + readonly signature: typeof Generated.ResponseThinkingBlock.fields.thinking.Encoded + } | { + readonly type: "redacted_thinking" + /** + * Thinking content which was flagged by Anthropic's safety systems, and + * was therefore encrypted. + */ + readonly redactedData: typeof Generated.ResponseRedactedThinkingBlock.fields.data.Encoded + } | null + } | null + } + + /** + * Anthropic metadata attached to tool call response parts. + * + * **Details** + * + * Identifies Anthropic caller details and MCP tool metadata emitted by the + * provider. + * + * @category models + * @since 4.0.0 + */ + export interface ToolCallPartMetadata extends ProviderMetadata { + readonly anthropic?: { + readonly caller?: { + readonly type: string + readonly toolId?: string | null + } | null + /** + * Contains details about the MCP tool that was called. + */ + readonly mcp_tool?: { + /** + * The name of the MCP server + */ + readonly server: string + } | null + } | null + } + + /** + * Anthropic metadata attached to tool result response parts. + * + * **Details** + * + * Identifies MCP tool metadata associated with provider-executed tool + * results. + * + * @category models + * @since 4.0.0 + */ + export interface ToolResultPartMetadata extends ProviderMetadata { + readonly anthropic?: { + /** + * Contains details about the MCP tool that was called. + */ + readonly mcp_tool?: { + /** + * The name of the MCP server + */ + readonly server: string + } | null + } | null + } + + /** + * Anthropic metadata for document citations in model responses. + * + * **Details** + * + * Records the cited document span by character position or page number. + * + * @category models + * @since 4.0.0 + */ + export interface DocumentSourcePartMetadata extends ProviderMetadata { + readonly anthropic?: { + readonly source: "document" + readonly type: "char_location" + /** + * The text that was cited in the response. + */ + readonly citedText: string + /** + * The 0-indexed starting position of the characters that were cited. + */ + readonly startCharIndex: number + /** + * The exclusive ending position of the characters that were cited. + */ + readonly endCharIndex: number + } | { + readonly source: "document" + readonly type: "page_location" + /** + * The text that was cited in the response. + */ + readonly citedText: string + /** + * The 1-indexed starting page of pages that were cited. + */ + readonly startPageNumber: number + /** + * The exclusive ending position of the pages that were cited. + */ + readonly endPageNumber: number + } | null + } + + /** + * Anthropic metadata for URL and web citations in model responses. + * + * **Details** + * + * Records cited URL text or web-search source freshness information. + * + * @category models + * @since 4.0.0 + */ + export interface UrlSourcePartMetadata extends ProviderMetadata { + readonly anthropic?: { + readonly source: "url" + /** + * Up to 150 characters of the text content that was referenced from the + * URL source material. + */ + readonly citedText: string + /** + * An internal reference that must be passed back to the Anthropic API + * during multi-turn conversations. + */ + readonly encryptedIndex: string + } | { + readonly source: "web" + readonly pageAge: string | null + } | null + } + + /** + * Anthropic metadata attached to the finish part of a response. + * + * **Details** + * + * Includes container state, context management information, stop details, and + * token usage reported by Anthropic. + * + * @category models + * @since 4.0.0 + */ + export interface FinishPartMetadata extends ProviderMetadata { + readonly anthropic?: { + readonly container: typeof Generated.BetaContainer.Encoded | null + readonly contextManagement: typeof Generated.BetaResponseContextManagement.Encoded | null + readonly stopSequence: string | null + readonly usage: typeof Generated.BetaMessage.Encoded["usage"] | null + } | null + } + + /** + * Anthropic metadata attached to error response parts. + * + * **Details** + * + * Includes the provider request identifier when Anthropic returns one. + * + * @category models + * @since 4.0.0 + */ + export interface ErrorPartMetadata extends ProviderMetadata { + readonly anthropic?: { + requestId?: string | null + } | null + } +} + +// ============================================================================= +// Language Model +// ============================================================================= + +/** + * Creates an Anthropic model descriptor that can be provided with `Effect.provide`. + * + * **When to use** + * + * Use when you want an Anthropic Claude model value that carries provider and + * model metadata and can be supplied directly to an Effect program. + * + * @see {@link layer} for creating a `LanguageModel.LanguageModel` layer directly + * @see {@link make} for constructing the language model service effectfully + * + * @category constructors + * @since 4.0.0 + */ +export const model = ( + model: (string & {}) | Model, + config?: Omit +): AiModel.Model<"anthropic", LanguageModel.LanguageModel, AnthropicClient> => + AiModel.make("anthropic", model, layer({ model, config })) + +/** + * Creates an Anthropic `LanguageModel` service from a model identifier and optional request defaults. + * + * **When to use** + * + * Use when you need to construct a `LanguageModel.Service` value backed by + * `AnthropicClient` inside an Effect. + * + * **Details** + * + * The returned effect requires `AnthropicClient`. Request defaults from the + * `config` option are merged with any `Config` service in the context, with + * context values taking precedence. + * + * @see {@link layer} for providing the service as a `Layer` + * @see {@link model} for creating a model descriptor for `AiModel.provide` + * + * @category constructors + * @since 4.0.0 + */ +export const make = Effect.fnUntraced(function*({ model, config: providerConfig }: { + readonly model: (string & {}) | Model + readonly config?: Omit | undefined +}): Effect.fn.Return { + const client = yield* AnthropicClient + + const makeConfig: Effect.Effect = Effect.contextWith((services) => + Effect.succeed({ + model, + ...providerConfig, + ...Context.getOrUndefined(services, Config) + }) + ) + + const makeRequest = Effect.fnUntraced( + function*>({ config, options, toolNameMapper }: { + readonly config: typeof Config.Service & { readonly model: string } + readonly options: LanguageModel.ProviderOptions + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return<{ + readonly params: typeof Generated.BetaMessagesPostParams.Encoded + readonly payload: typeof Generated.BetaCreateMessageParams.Encoded + }, AiError.AiError> { + const betas = new Set() + const modelCapabilities = getModelCapabilities(config.model!) + const capabilities = Predicate.isNotUndefined(config.structuredOutputs) + ? { ...modelCapabilities, supportsStructuredOutput: config.structuredOutputs } + : modelCapabilities + const { messages, system } = yield* prepareMessages({ betas, options, toolNameMapper }) + const outputFormat = yield* getOutputFormat({ capabilities, options }) + const { tools, toolChoice } = yield* prepareTools({ betas, capabilities, config, options }) + const params: Mutable = {} + if (betas.size > 0) { + params["anthropic-beta"] = Array.from(betas).join(",") + } + const { disableParallelToolCalls: _, output_config, structuredOutputs: _structuredOutputs, ...requestConfig } = + config + const payload: Mutable = { + ...requestConfig, + max_tokens: requestConfig.max_tokens ?? capabilities.maxOutputTokens, + messages, + ...(Predicate.isNotUndefined(system) ? { system } : undefined), + ...(Predicate.isNotUndefined(tools) ? { tools } : undefined), + ...(Predicate.isNotUndefined(toolChoice) ? { tool_choice: toolChoice } : undefined) + } + const outputConfig: Mutable = {} + if (Predicate.isNotUndefined(outputFormat)) { + outputConfig.format = outputFormat + } + if (Predicate.isNotUndefined(output_config?.effort)) { + outputConfig.effort = output_config.effort + } + if (Object.keys(outputConfig).length > 0) { + payload.output_config = outputConfig + } + return { params, payload } + } + ) + + return yield* LanguageModel.make({ + codecTransformer: toCodecAnthropic, + generateText: Effect.fnUntraced(function*(options) { + const config = yield* makeConfig + const toolNameMapper = new Tool.NameMapper(options.tools) + const request = yield* makeRequest({ config, options, toolNameMapper }) + annotateRequest(options.span, request.payload) + const [rawResponse, response] = yield* client.createMessage(request) + annotateResponse(options.span, rawResponse) + return yield* makeResponse({ options, rawResponse, response, toolNameMapper }) + }), + streamText: Effect.fnUntraced(function*(options) { + const config = yield* makeConfig + const toolNameMapper = new Tool.NameMapper(options.tools) + const request = yield* makeRequest({ config, options, toolNameMapper }) + annotateRequest(options.span, request.payload) + const [response, stream] = yield* client.createMessageStream(request) + return yield* makeStreamResponse({ stream, response, options, toolNameMapper }) + }, (effect, options) => + effect.pipe( + Stream.unwrap, + Stream.map((response) => { + annotateStreamResponse(options.span, response) + return response + }) + )) + }) +}) + +/** + * Creates a layer for the Anthropic language model. + * + * **When to use** + * + * Use when composing application layers and you want Anthropic to satisfy + * `LanguageModel.LanguageModel` while supplying `AnthropicClient` from another + * layer. + * + * @see {@link make} for constructing the language model service effectfully + * @see {@link model} for creating a model service directly + * + * @category layers + * @since 4.0.0 + */ +export const layer = (options: { + readonly model: (string & {}) | Model + readonly config?: Omit | undefined +}): Layer.Layer => + Layer.effect(LanguageModel.LanguageModel, make(options)) + +/** + * Provides config overrides for Anthropic language model operations. + * + * **When to use** + * + * Use to apply Anthropic request configuration to one effect without changing + * the model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available Anthropic request configuration fields + * + * @category configuration + * @since 4.0.0 + */ +export const withConfigOverride: { + /** + * Provides config overrides for Anthropic language model operations. + * + * **When to use** + * + * Use to apply Anthropic request configuration to one effect without changing + * the model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available Anthropic request configuration fields + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service): (self: Effect.Effect) => Effect.Effect> + /** + * Provides config overrides for Anthropic language model operations. + * + * **When to use** + * + * Use to apply Anthropic request configuration to one effect without changing + * the model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available Anthropic request configuration fields + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service): Effect.Effect> +} = dual< + /** + * Provides config overrides for Anthropic language model operations. + * + * **When to use** + * + * Use to apply Anthropic request configuration to one effect without changing + * the model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available Anthropic request configuration fields + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service) => (self: Effect.Effect) => Effect.Effect>, + /** + * Provides config overrides for Anthropic language model operations. + * + * **When to use** + * + * Use to apply Anthropic request configuration to one effect without changing + * the model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available Anthropic request configuration fields + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service) => Effect.Effect> +>(2, (self, overrides) => + Effect.flatMap( + Effect.serviceOption(Config), + (config) => + Effect.provideService(self, Config, { + ...(config._tag === "Some" ? config.value : {}), + ...overrides + }) + )) + +// ============================================================================= +// Prompt Conversion +// ============================================================================= + +const prepareMessages = Effect.fnUntraced( + function*>({ betas, options, toolNameMapper }: { + readonly betas: Set + readonly options: LanguageModel.ProviderOptions + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return<{ + readonly system: ReadonlyArray | undefined + readonly messages: ReadonlyArray + }, AiError.AiError> { + const groups = groupMessages(options.prompt) + + let system: Array | undefined = undefined + const messages: Array = [] + + for (let i = 0; i < groups.length; i++) { + const group = groups[i] + const isLastGroup = i === groups.length - 1 + + switch (group.type) { + case "system": { + system = group.messages.map((message) => ({ + type: "text", + text: message.content, + cache_control: getCacheControl(message) + })) + break + } + + case "user": { + const content: Array = [] + + for (const message of group.messages) { + switch (message.role) { + case "user": { + for (let j = 0; j < message.content.length; j++) { + const part = message.content[j] + const isLastPart = j === message.content.length - 1 + + // Attempt to get the cache control from the part first. If + // the part does not have cache control defined and we are + // evaluating the last part for this message, also check the + // message for cache control. + const cacheControl = getCacheControl(part) ?? ( + isLastPart ? getCacheControl(message) : null + ) + + switch (part.type) { + case "text": { + content.push({ + type: "text", + text: part.text, + cache_control: cacheControl + }) + break + } + + case "file": { + if (part.mediaType.startsWith("image/")) { + const mediaType: typeof Generated.Base64ImageSource.Type["media_type"] = + (part.mediaType === "image/*" ? "image/jpeg" : part.mediaType) as any + + const source = isUrlData(part.data) + ? { type: "url", url: getUrlString(part.data) } as const + : { type: "base64", media_type: mediaType, data: Encoding.encodeBase64(part.data) } as const + + content.push({ type: "image", source, cache_control: cacheControl }) + } else if (part.mediaType === "application/pdf" || part.mediaType === "text/plain") { + betas.add("pdfs-2024-09-25") + + const enableCitations = areCitationsEnabled(part) + const documentOptions = getDocumentMetadata(part) + + const source = isUrlData(part.data) + ? { + type: "url", + url: getUrlString(part.data) + } as const + : part.mediaType === "application/pdf" + ? { + type: "base64", + media_type: "application/pdf", + data: typeof part.data === "string" ? part.data : Encoding.encodeBase64(part.data) + } as const + : { + type: "text", + media_type: "text/plain", + data: typeof part.data === "string" ? part.data : new TextDecoder().decode(part.data) + } as const + + content.push({ + type: "document", + source, + title: documentOptions?.title ?? part.fileName ?? null, + cache_control: cacheControl, + ...(documentOptions?.context ? { context: documentOptions.context } : undefined), + ...(enableCitations ? { citations: { enabled: true } } : undefined) + }) + } else { + return yield* new AiError.AiError({ + module: "AnthropicLanguageModel", + method: "prepareMessages", + reason: new AiError.InvalidUserInputError({ + description: `Detected unsupported media type for file: '${part.mediaType}'` + }) + }) + } + + break + } + } + } + break + } + + case "tool": { + for (let j = 0; j < message.content.length; j++) { + const part = message.content[j] + + // Skip evaluation of tool approval parts + if (part.type === "tool-approval-response") { + continue + } + + const isLastPart = j === message.content.length - 1 + + // Attempt to get the cache control from the part first. If + // the part does not have cache control defined and we are + // evaluating the last part for this message, also check the + // message for cache control. + const cacheControl = getCacheControl(part) ?? ( + isLastPart ? getCacheControl(message) : null + ) + + let toolResultContent: + | string + | Array + if (Predicate.isString(part.result)) { + toolResultContent = part.result + } else if ( + Array.isArray(part.result) && + part.result.every((item) => Prompt.isPart(item) && (item.type === "text" || item.type === "file")) + ) { + toolResultContent = [] + for (const outputPart of part.result) { + if (outputPart.type === "text") { + toolResultContent.push({ type: "text", text: outputPart.text }) + continue + } + + if (!outputPart.mediaType.startsWith("image/")) { + return yield* new AiError.AiError({ + module: "AnthropicLanguageModel", + method: "prepareMessages", + reason: new AiError.InvalidUserInputError({ + description: `Detected unsupported media type for tool result: '${outputPart.mediaType}'` + }) + }) + } + + const mediaType: typeof Generated.Base64ImageSource.Type["media_type"] = + (outputPart.mediaType === "image/*" ? "image/jpeg" : outputPart.mediaType) as any + const source = outputPart.data instanceof URL + ? { type: "url" as const, url: outputPart.data.toString() } + : { + type: "base64" as const, + media_type: mediaType, + data: Predicate.isString(outputPart.data) + ? outputPart.data + : Encoding.encodeBase64(outputPart.data) + } + toolResultContent.push({ type: "image", source }) + } + } else { + toolResultContent = JSON.stringify(part.result) + } + + content.push({ + type: "tool_result", + tool_use_id: part.id, + content: toolResultContent, + is_error: part.isFailure, + cache_control: cacheControl + }) + } + } + } + } + + messages.push({ role: "user", content }) + + break + } + + case "assistant": { + const content: Array = [] + const mcpToolIds = new Set() + + for (let j = 0; j < group.messages.length; j++) { + const message = group.messages[j] + const isLastMessage = j === group.messages.length - 1 + + for (let k = 0; k < message.content.length; k++) { + const part = message.content[k] + + if (part.type === "file" || part.type === "tool-approval-request") { + continue + } + + const isLastPart = k === message.content.length - 1 + + // Attempt to get the cache control from the part first. If + // the part does not have cache control defined and we are + // evaluating the last part for this message, also check the + // message for cache control. + const cacheControl = getCacheControl(part) ?? ( + isLastPart ? getCacheControl(message) : undefined + ) + + // TODO: use cache_control in content blocks + void cacheControl + + switch (part.type) { + case "text": { + content.push({ + type: "text", + // Anthropic does not allow trailing whitespace in assistant + // content blocks + text: isLastGroup && isLastMessage && isLastPart + ? part.text.trim() + : part.text + }) + break + } + case "reasoning": { + // TODO: make sending reasoning configurable + const info = part.options.anthropic?.info + if (Predicate.isNotNullish(info)) { + if (info.type === "thinking") { + content.push({ + type: "thinking", + thinking: part.text, + signature: info.signature + }) + } else { + content.push({ + type: "redacted_thinking", + data: info.redactedData + }) + } + } + break + } + + case "tool-call": { + if (part.providerExecuted) { + const toolName = toolNameMapper.getProviderName(part.name) + + const isMcpTool = Predicate.isNotNullish(part.options.anthropic?.mcp_tool) + + if (isMcpTool) { + const { server } = part.options.anthropic.mcp_tool + + mcpToolIds.add(part.id) + + content.push({ + type: "mcp_tool_use", + id: part.id, + name: part.name, + input: part.params as any, + server_name: server + }) + } else if ( + toolName === "code_execution" && + Predicate.hasProperty(part.params, "type") && + ( + part.params.type === "bash_code_execution" || + part.params.type === "text_editor_code_execution" + ) + ) { + content.push({ + type: "server_tool_use", + id: part.id, + name: part.params.type, + input: part.params as any + }) + } else if ( + // code execution 20250825 programmatic tool calling: + // Strip the fake 'programmatic-tool-call' type before sending to Anthropic + toolName === "code_execution" && + Predicate.hasProperty(part.params, "type") && + part.params.type === "programmatic-tool-call" + ) { + const { type, ...params } = part.params + content.push({ + type: "server_tool_use", + id: part.id, + name: toolName, + input: params as any + }) + } else { + if ( + // code execution 20250522 + toolName === "code_execution" || + toolName === "tool_search_tool_regex" || + toolName === "tool_search_tool_bm25" || + toolName === "web_fetch" || + toolName === "web_search" + ) { + content.push({ + type: "server_tool_use", + id: part.id, + name: toolName, + input: part.params as any + }) + } + } + } else { + // Extract caller info from provider options for programmatic tool calling + const options = part.options.anthropic + const caller = Predicate.isNotNullish(options?.caller) + ? ( + options.caller.type === "code_execution_20250825" && + Predicate.isNotNullish(options.caller.toolId) + ) + ? { + type: "code_execution_20250825", + tool_id: options.caller.toolId + } as const + : options.caller.type === "direct" + ? { + type: "direct" + } as const + : undefined + : undefined + + content.push({ + type: "tool_use", + id: part.id, + name: part.name, + input: part.params as any, + ...(Predicate.isNotUndefined(caller) ? { caller } : undefined) + }) + } + + break + } + + case "tool-result": { + const toolName = toolNameMapper.getProviderName(part.name) + + if (mcpToolIds.has(part.id)) { + content.push({ + type: "mcp_tool_result", + tool_use_id: part.id, + is_error: part.isFailure, + content: part.result as any + }) + break + } + + if (toolName === "code_execution" && Predicate.hasProperty(part.result, "type")) { + if (part.result.type === "code_execution_result") { + content.push({ + type: "code_execution_tool_result", + tool_use_id: part.id, + content: part.result as any + }) + } else if ( + part.result.type === "bash_code_execution_result" || + part.result.type === "bash_code_execution_tool_result_error" + ) { + content.push({ + type: "bash_code_execution_tool_result", + tool_use_id: part.id, + content: part.result as any + }) + } else if ( + part.result.type === "text_editor_code_execution_tool_result" || + part.result.type === "text_editor_code_execution_tool_result_error" + ) { + content.push({ + type: "text_editor_code_execution_tool_result", + tool_use_id: part.id, + content: part.result as any + }) + } + break + } + + if (toolName === "web_fetch") { + content.push({ + type: "web_fetch_tool_result", + tool_use_id: part.id, + content: part.result as any + }) + break + } + + if (toolName === "web_search") { + content.push({ + type: "web_search_tool_result", + tool_use_id: part.id, + content: part.result as any + }) + break + } + + if ( + toolName === "tool_search_tool_regex" || + toolName === "tool_search_tool_bm25" + ) { + content.push({ + type: "tool_search_tool_result", + tool_use_id: part.id, + content: part.result as any + }) + break + } + + break + } + } + } + } + + messages.push({ role: "assistant", content }) + + break + } + } + } + + return { + system, + messages + } + } +) + +// ============================================================================= +// Tool Conversion +// ============================================================================= + +/** + * Encoded Anthropic custom tool definition that can be sent in a Messages API request. + * + * **When to use** + * + * Use when you need to type or inspect the provider-specific request payload for + * a custom Anthropic tool. + * + * **Details** + * + * This type aliases the encoded `Generated.BetaTool` schema used for Effect + * user-defined and dynamic tools after conversion. It contains the tool `name`, + * optional `description`, and `input_schema`, plus Anthropic-specific fields + * such as `strict` and `cache_control`. + * + * @see {@link AnthropicProviderDefinedTool} for the request shape used by Anthropic built-in provider tools + * + * @category tools + * @since 4.0.0 + */ +export type AnthropicUserDefinedTool = typeof Generated.BetaTool.Encoded + +/** + * Represents a provider-defined tool that can be passed to the Anthropic API. + * + * **Details** + * + * These include Anthropic's built-in tools like computer use, code execution, + * web search, and text editing. + * + * @category tools + * @since 4.0.0 + */ +export type AnthropicProviderDefinedTool = + | typeof Generated.BetaBashTool_20241022.Encoded + | typeof Generated.BetaBashTool_20250124.Encoded + | typeof Generated.BetaCodeExecutionTool_20250522.Encoded + | typeof Generated.BetaCodeExecutionTool_20250825.Encoded + | typeof Generated.BetaComputerUseTool_20241022.Encoded + | typeof Generated.BetaComputerUseTool_20250124.Encoded + | typeof Generated.BetaComputerUseTool_20251124.Encoded + | typeof Generated.BetaMemoryTool_20250818.Encoded + | typeof Generated.BetaTextEditor_20241022.Encoded + | typeof Generated.BetaTextEditor_20250124.Encoded + | typeof Generated.BetaTextEditor_20250429.Encoded + | typeof Generated.BetaTextEditor_20250728.Encoded + | typeof Generated.BetaToolSearchToolBM25_20251119.Encoded + | typeof Generated.BetaToolSearchToolRegex_20251119.Encoded + | typeof Generated.BetaWebFetchTool_20250910.Encoded + | typeof Generated.BetaWebSearchTool_20250305.Encoded + +const prepareTools = Effect.fnUntraced( + function*({ betas, capabilities, config, options }: { + readonly betas: Set + readonly capabilities: ModelCapabilities + readonly config: typeof Config.Service + readonly options: LanguageModel.ProviderOptions + }): Effect.fn.Return<{ + readonly tools: ReadonlyArray | undefined + readonly toolChoice: typeof Generated.BetaToolChoice.Encoded | undefined + }, AiError.AiError> { + if (options.tools.length === 0 || options.toolChoice === "none") { + return { tools: undefined, toolChoice: undefined } + } + + // Return a JSON response tool when using non-native structured outputs + if (options.responseFormat.type === "json" && !capabilities.supportsStructuredOutput) { + const input_schema = yield* tryJsonSchema(options.responseFormat.schema, "prepareTools") + const userDescription = SchemaAST.resolveDescription(options.responseFormat.schema.ast) + const description = Predicate.isNotUndefined(userDescription) ? `${userDescription} - ` : "" + return { + tools: [{ + name: options.responseFormat.objectName, + description: `${description}You MUST respond with a JSON object.`, + input_schema: input_schema as any + }], + toolChoice: { + type: "tool", + name: options.responseFormat.objectName, + disable_parallel_tool_use: true + } + } + } + + const userTools: Array = [] + const providerTools: Array = [] + + for (const tool of options.tools) { + if (Tool.isUserDefined(tool) || Tool.isDynamic(tool)) { + const description = Tool.getDescription(tool) + const input_schema = yield* tryToolJsonSchema(tool, "prepareTools") + const toolStrict = Tool.getStrictMode(tool) + const strict = capabilities.supportsStructuredOutput + ? (toolStrict ?? config.strictJsonSchema ?? true) + : undefined + + userTools.push({ + name: tool.name, + input_schema: input_schema as any, + ...(Predicate.isNotUndefined(description) ? { description } : undefined), + ...(Predicate.isNotUndefined(strict) ? { strict } : undefined) + }) + + if (capabilities.supportsStructuredOutput === true) { + betas.add("structured-outputs-2025-11-13") + } + } + + if (Tool.isProviderDefined(tool)) { + const providerTool = tool as AnthropicTool + switch (providerTool.id) { + case "anthropic.bash_20241022": { + betas.add("computer-use-2024-10-22") + providerTools.push({ name: "bash", type: "bash_20241022" }) + break + } + + case "anthropic.bash_20250124": { + betas.add("computer-use-2025-01-24") + providerTools.push({ name: "bash", type: "bash_20250124" }) + break + } + + case "anthropic.code_execution_20250522": { + betas.add("code-execution-2025-05-22") + providerTools.push({ name: "code_execution", type: "code_execution_20250522" }) + break + } + + case "anthropic.code_execution_20250825": { + betas.add("code-execution-2025-08-25") + providerTools.push({ name: "code_execution", type: "code_execution_20250825" }) + break + } + + case "anthropic.computer_use_20241022": { + betas.add("computer-use-2024-10-22") + providerTools.push({ + name: "computer", + type: "computer_20241022", + display_height_px: providerTool.args.displayHeightPx, + display_width_px: providerTool.args.displayWidthPx, + display_number: providerTool.args.displayNumber ?? null + }) + break + } + + case "anthropic.computer_20250124": { + betas.add("computer-use-2025-01-24") + providerTools.push({ + name: "computer", + type: "computer_20250124", + display_height_px: providerTool.args.displayHeightPx, + display_width_px: providerTool.args.displayWidthPx, + display_number: providerTool.args.displayNumber ?? null + }) + break + } + + case "anthropic.computer_20251124": { + betas.add("computer-use-2025-11-24") + providerTools.push({ + name: "computer", + type: "computer_20251124", + display_height_px: providerTool.args.displayHeightPx, + display_width_px: providerTool.args.displayWidthPx, + display_number: providerTool.args.displayNumber ?? null, + enable_zoom: providerTool.args.enableZoom ?? false + }) + break + } + + case "anthropic.memory_20250818": { + betas.add("context-management-2025-06-27") + providerTools.push({ name: "memory", type: "memory_20250818" }) + break + } + + case "anthropic.text_editor_20241022": { + betas.add("computer-use-2024-10-22") + providerTools.push({ name: "str_replace_editor", type: "text_editor_20241022" }) + break + } + + case "anthropic.text_editor_20250124": { + betas.add("computer-use-2025-01-24") + providerTools.push({ name: "str_replace_editor", type: "text_editor_20250124" }) + break + } + + case "anthropic.text_editor_20250429": { + betas.add("computer-use-2025-01-24") + providerTools.push({ name: "str_replace_based_edit_tool", type: "text_editor_20250429" }) + break + } + + case "anthropic.text_editor_20250728": { + providerTools.push({ + name: "str_replace_based_edit_tool", + type: "text_editor_20250728", + max_characters: providerTool.args.max_characters ?? null + }) + break + } + + case "anthropic.tool_search_tool_bm25_20251119": { + betas.add("advanced-tool-use-2025-11-20") + providerTools.push({ name: "tool_search_tool_bm25", type: "tool_search_tool_bm25_20251119" }) + break + } + + case "anthropic.tool_search_tool_regex_20251119": { + providerTools.push({ name: "tool_search_tool_regex", type: "tool_search_tool_regex_20251119" }) + break + } + + case "anthropic.web_search_20250305": { + providerTools.push({ + name: "web_search", + type: "web_search_20250305", + max_uses: providerTool.args.maxUses ?? null, + allowed_domains: providerTool.args.allowedDomains ?? null, + blocked_domains: providerTool.args.blockedDomains ?? null, + user_location: Predicate.isNotUndefined(providerTool.args.userLocation) + ? { + type: providerTool.args.userLocation.type, + region: providerTool.args.userLocation.region ?? null, + city: providerTool.args.userLocation.city ?? null, + country: providerTool.args.userLocation.country ?? null, + timezone: providerTool.args.userLocation.timezone ?? null + } + : null + }) + break + } + + case "anthropic.web_fetch_20250910": { + betas.add("web-fetch-2025-09-10") + providerTools.push({ + name: "web_fetch", + type: "web_fetch_20250910", + max_uses: providerTool.args.maxUses ?? null, + allowed_domains: providerTool.args.allowedDomains ?? null, + blocked_domains: providerTool.args.blockedDomains ?? null, + citations: providerTool.args.citations ?? null, + max_content_tokens: providerTool.args.maxContentTokens ?? null + }) + break + } + + default: { + return yield* AiError.make({ + module: "AnthropicLanguageModel", + method: "prepareTools", + reason: new AiError.InvalidUserInputError({ + description: `Received request to call unknown provider-defined tool '${tool.name}'` + }) + }) + } + } + } + } + + let tools = [...userTools, ...providerTools] + let toolChoice: Mutable | undefined = undefined + + if (options.toolChoice === "auto") { + toolChoice = { type: "auto" } + } else if (options.toolChoice === "required") { + toolChoice = { type: "any" } + } else if ("tool" in options.toolChoice) { + toolChoice = { type: "tool", name: options.toolChoice.tool } + } else { + const allowedTools = new Set(options.toolChoice.oneOf) + tools = tools.filter((tool) => allowedTools.has(tool.name)) + toolChoice = { type: options.toolChoice.mode === "required" ? "any" : "auto" } + } + + if ( + Predicate.isNotUndefined(config.disableParallelToolCalls) && + Predicate.isNotUndefined(toolChoice) && + toolChoice.type !== "none" + ) { + toolChoice.disable_parallel_tool_use = config.disableParallelToolCalls + } + + return { + tools, + toolChoice + } + } +) + +// ============================================================================= +// HTTP Details +// ============================================================================= + +const buildHttpRequestDetails = ( + request: HttpClientRequest.HttpClientRequest +): typeof Response.HttpRequestDetails.Type => ({ + method: request.method, + url: request.url, + urlParams: Array.from(request.urlParams), + hash: Option.getOrUndefined(request.hash), + headers: Redactable.redact(request.headers) as Record +}) + +const buildHttpResponseDetails = ( + response: HttpClientResponse.HttpClientResponse +): typeof Response.HttpResponseDetails.Type => ({ + status: response.status, + headers: Redactable.redact(response.headers) as Record +}) + +// ============================================================================= +// Response Conversion +// ============================================================================= + +const makeResponse = Effect.fnUntraced( + function*>({ + options, + rawResponse, + response, + toolNameMapper + }: { + readonly options: LanguageModel.ProviderOptions + readonly rawResponse: Generated.BetaMessage + readonly response: HttpClientResponse.HttpClientResponse + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return< + Array, + AiError.AiError, + IdGenerator.IdGenerator + > { + const parts: Array = [] + const mcpToolCalls: Map = new Map() + const serverToolCalls: Map = new Map() + const citableDocuments = extractCitableDocuments(options.prompt) + + parts.push({ + type: "response-metadata", + id: rawResponse.id, + modelId: rawResponse.model, + timestamp: DateTime.formatIso(yield* DateTime.now), + request: buildHttpRequestDetails(response.request) + }) + + for (const part of rawResponse.content) { + switch (part.type) { + case "text": { + // Text parts are added for both text and json response formats. + // For native structured output (json_schema), the JSON comes directly + // in a text content block. For tool-based structured output, text may + // also be present alongside the tool_use. + parts.push({ + type: "text", + text: part.text + }) + + if (Predicate.isNotNullish(part.citations)) { + for (const citation of part.citations) { + const source = yield* processCitation(citation, citableDocuments) + if (Predicate.isNotUndefined(source)) { + parts.push(source) + } + } + } + + break + } + + case "thinking": { + const metadata = { + info: { type: "thinking", signature: part.signature } + } as const + + parts.push({ + type: "reasoning", + text: part.thinking, + metadata: { anthropic: metadata } + }) + break + } + + case "redacted_thinking": { + const metadata = { + info: { type: "redacted_thinking", redactedData: part.data } + } as const + + parts.push({ + type: "reasoning", + text: "", + metadata: { anthropic: metadata } + }) + break + } + + case "tool_use": { + // When the `"json"` response format is requested, the JSON we need + // is returned by a tool call injected into the request + if (options.responseFormat.type === "json") { + parts.push({ + type: "text", + text: JSON.stringify(part.input) + }) + } else { + // Extract caller info if present + const caller = (part as any).caller + const callerInfo = Predicate.isNotNullish(caller) + ? { + type: caller.type, + toolId: "tool_id" in caller ? caller.tool_id : null + } + : undefined + + // Map the provider wire name (e.g. "memory") back to the tool's + // custom name (e.g. "AnthropicMemory") that the toolkit is keyed by + const toolName = toolNameMapper.getCustomName(part.name) + const params = yield* transformToolCallParams(options.tools, toolName, part.input) + + parts.push({ + type: "tool-call", + id: part.id, + name: toolName, + params, + ...(Predicate.isNotUndefined(callerInfo) + ? { metadata: { anthropic: { caller: callerInfo } } } + : undefined) + }) + } + + break + } + + case "server_tool_use": { + const toolName = toolNameMapper.getCustomName(part.name) + + if ( + part.name === "bash_code_execution" || + part.name === "text_editor_code_execution" + ) { + parts.push({ + type: "tool-call", + id: part.id, + name: toolName, + params: { type: part.name, ...part.input }, + providerExecuted: true + }) + } else if ( + part.name === "code_execution" || + part.name === "web_fetch" || + part.name === "web_search" + ) { + const toolParams: Record = { ...part.input } + + // Inject `type: "programmatic-tool-call"` when the input parameters + // has the format `{ code: ... }` + if ( + part.name === "code_execution" && + Predicate.hasProperty(part.input, "code") && + !Predicate.hasProperty(part.input, "type") + ) { + toolParams.type = "programmatic-tool-call" + } + + parts.push({ + type: "tool-call", + id: part.id, + name: toolName, + params: toolParams, + providerExecuted: true + }) + } else if ( + part.name === "tool_search_tool_bm25" || + part.name === "tool_search_tool_regex" + ) { + serverToolCalls.set(part.id, part.name) + parts.push({ + type: "tool-call", + id: part.id, + name: toolName, + params: part.input, + providerExecuted: true + }) + } + + break + } + + case "mcp_tool_use": { + const toolCall: Response.ToolCallPartEncoded = { + type: "tool-call", + id: part.id, + name: part.name, + params: part.input, + providerExecuted: true, + metadata: { anthropic: { mcp_tool: { server: part.server_name } } } + } + + mcpToolCalls.set(part.id, toolCall) + + parts.push(toolCall) + + break + } + + case "mcp_tool_result": { + const toolCall = mcpToolCalls.get(part.tool_use_id) + const mcpMetadata = toolCall?.metadata?.anthropic?.mcp_tool + + if (Predicate.isNotUndefined(toolCall)) { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolCall.name, + isFailure: part.is_error, + result: part.content, + metadata: { + anthropic: { + ...(Predicate.isNotNullish(mcpMetadata) + ? { mcp_tool: mcpMetadata } : + undefined) + } + } + }) + } + + break + } + + // Code Execution 20250522 + case "code_execution_tool_result": { + const toolName = toolNameMapper.getCustomName("code_execution") + + if (part.content.type === "code_execution_result") { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content + }) + } else { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } + + break + } + + // Code Execution 20250825 + case "bash_code_execution_tool_result": + case "text_editor_code_execution_tool_result": { + const toolName = toolNameMapper.getCustomName("code_execution") + + if ( + part.content.type === "bash_code_execution_tool_result_error" || + part.content.type === "text_editor_code_execution_tool_result_error" + ) { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } else { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content + }) + } + + break + } + + case "tool_search_tool_result": { + let providerName = serverToolCalls.get(part.tool_use_id) + + if (Predicate.isUndefined(providerName)) { + const bm25Name = toolNameMapper.getCustomName("tool_search_tool_bm25") + const regexName = toolNameMapper.getCustomName("tool_search_tool_regex") + + if (bm25Name !== "tool_search_tool_bm25") { + providerName = "tool_search_tool_bm25" + } else if (regexName !== "tool_search_tool_regex") { + providerName = "tool_search_tool_regex" + } + } + + const toolName = toolNameMapper.getCustomName(providerName!) + + if (part.content.type === "tool_search_tool_search_result") { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content.tool_references + }) + } else { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } + + break + } + + case "web_fetch_tool_result": { + const toolName = toolNameMapper.getCustomName("web_fetch") + + if (part.content.type === "web_fetch_result") { + citableDocuments.push({ + title: part.content.content.title ?? part.content.url, + mediaType: part.content.content.source.media_type + }) + + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content + }) + } else { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } + + break + } + + case "web_search_tool_result": { + const toolName = toolNameMapper.getCustomName("web_search") + + if (Predicate.hasProperty(part.content, "type")) { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } else { + const idGenerator = yield* IdGenerator.IdGenerator + + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content + }) + + const content = part.content as ReadonlyArray + + for (const result of content) { + const id = yield* idGenerator.generateId() + + parts.push({ + type: "source", + sourceType: "url", + id, + url: result.url, + title: result.title, + metadata: { anthropic: { source: "web", pageAge: result.page_age } } + }) + } + } + + break + } + } + } + + // Anthropic always returns a non-null `stop_reason` for non-streaming responses + const finishReason = InternalUtilities.resolveFinishReason( + rawResponse.stop_reason!, + options.responseFormat.type === "json" + ) + + const inputTokens = rawResponse.usage.input_tokens + const outputTokens = rawResponse.usage.output_tokens + const cacheWriteTokens = rawResponse.usage.cache_creation_input_tokens ?? 0 + const cacheReadTokens = rawResponse.usage.cache_read_input_tokens ?? 0 + + parts.push({ + type: "finish", + reason: finishReason, + usage: { + inputTokens: { + uncached: inputTokens, + total: inputTokens + cacheWriteTokens + cacheReadTokens, + cacheRead: cacheReadTokens, + cacheWrite: cacheWriteTokens + }, + outputTokens: { + total: outputTokens, + text: undefined, + reasoning: undefined + } + }, + response: buildHttpResponseDetails(response), + metadata: { + anthropic: { + container: rawResponse.container ?? null, + contextManagement: rawResponse.context_management ?? null, + usage: rawResponse.usage, + stopSequence: rawResponse.stop_sequence + } + } + }) + + return parts + } +) + +const makeStreamResponse = Effect.fnUntraced( + function*>({ + stream, + response, + options, + toolNameMapper + }: { + readonly stream: Stream.Stream + readonly response: HttpClientResponse.HttpClientResponse + readonly options: LanguageModel.ProviderOptions + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return< + Stream.Stream, + AiError.AiError + > { + const citableDocuments = extractCitableDocuments(options.prompt) + + let container: typeof Generated.BetaContainer.Encoded | null = null + let contextManagement: typeof Generated.BetaResponseContextManagement.Encoded | null = null + let finishReason: Response.FinishReason = "unknown" + let stopSequence: string | null = null + let rawUsage: typeof Generated.BetaMessage.Encoded["usage"] | null = null + const mcpToolCalls: Map = new Map() + const serverToolCalls: Map = new Map() + const contentBlocks: Map< + number, + | { + readonly type: "text" + } + | { + readonly type: "reasoning" + } + | { + readonly type: "tool-call" + readonly id: string + readonly name: string + params: string + firstDelta: boolean + readonly providerName?: string | undefined + readonly providerExecuted?: boolean | undefined + readonly caller?: { type: string; toolId: string | null } | undefined + } + > = new Map() + const usage: Mutable<{ + inputTokens: number + outputTokens: number + cacheReadInputTokens: number + cacheWriteInputTokens: number + }> = { + inputTokens: 0, + outputTokens: 0, + cacheReadInputTokens: 0, + cacheWriteInputTokens: 0 + } + + let blockType: typeof Generated.BetaContentBlockStartEvent.Encoded["content_block"]["type"] | undefined = undefined + + return stream.pipe( + Stream.mapEffect(Effect.fnUntraced(function*(event) { + const parts: Array = [] + + switch (event.type) { + case "message_start": { + rawUsage = { ...event.message.usage } + usage.inputTokens = event.message.usage.input_tokens + usage.cacheReadInputTokens = event.message.usage.cache_read_input_tokens ?? 0 + usage.cacheWriteInputTokens = event.message.usage.cache_creation_input_tokens ?? 0 + + if (Predicate.isNotNullish(event.message.container)) { + container = event.message.container + } + + if (Predicate.isNotNull(event.message.stop_sequence)) { + stopSequence = event.message.stop_sequence + } + + if (Predicate.isNotNull(event.message.stop_reason)) { + finishReason = InternalUtilities.resolveFinishReason(event.message.stop_reason) + } + + parts.push({ + type: "response-metadata", + id: event.message.id, + modelId: event.message.model, + timestamp: DateTime.formatIso(yield* DateTime.now), + request: buildHttpRequestDetails(response.request) + }) + + // Process pre-populated content blocks + if (Predicate.isNotNullish(event.message.content) && event.message.content.length > 0) { + for (let i = 0; i < event.message.content.length; i++) { + const part = event.message.content[i] + + if (part.type === "tool_use") { + const callerInfo = Predicate.isNotUndefined(part.caller) + ? { + type: part.caller.type, + toolId: "tool_id" in part.caller ? part.caller.tool_id : null + } + : undefined + + // Map the provider wire name (e.g. "memory") back to the + // tool's custom name (e.g. "AnthropicMemory") that the toolkit + // is keyed by + const toolName = toolNameMapper.getCustomName(part.name) + + parts.push({ + type: "tool-params-start", + id: part.id, + name: toolName + }) + + parts.push({ + type: "tool-params-delta", + id: part.id, + delta: JSON.stringify(part.input ?? {}) + }) + + parts.push({ + type: "tool-params-end", + id: part.id + }) + + const params = yield* transformToolCallParams(options.tools, toolName, part.input) + + parts.push({ + type: "tool-call", + id: part.id, + name: toolName, + params, + ...(Predicate.isNotUndefined(callerInfo) + ? { metadata: { anthropic: { caller: callerInfo } } } + : undefined) + }) + } + } + } + + break + } + + case "message_delta": { + rawUsage = { ...rawUsage, ...event.usage } as any + + if ( + Predicate.isNotNull(event.usage.input_tokens) && + usage.inputTokens !== event.usage.input_tokens + ) { + usage.inputTokens = event.usage.input_tokens + } + usage.outputTokens = event.usage.output_tokens + + if ( + Predicate.isNotNull(event.usage.cache_read_input_tokens) && + usage.cacheReadInputTokens !== event.usage.cache_read_input_tokens + ) { + usage.cacheReadInputTokens = event.usage.cache_read_input_tokens + } + if ( + Predicate.isNotNull(event.usage.cache_creation_input_tokens) && + usage.cacheWriteInputTokens !== event.usage.cache_creation_input_tokens + ) { + usage.cacheWriteInputTokens = event.usage.cache_creation_input_tokens + } + + if (Predicate.isNotNullish(event.delta.container)) { + container = event.delta.container + } + + if (Predicate.isNotNullish(event.context_management)) { + contextManagement = event.context_management + } + + if (Predicate.isNotNull(event.delta.stop_reason)) { + finishReason = InternalUtilities.resolveFinishReason(event.delta.stop_reason) + } + + if (Predicate.isNotNull(event.delta.stop_sequence)) { + stopSequence = event.delta.stop_sequence + } + + break + } + + case "message_stop": { + const metadata: Response.FinishPartMetadata = { + anthropic: { + container, + contextManagement, + stopSequence, + usage: rawUsage + } + } + + parts.push({ + type: "finish", + reason: finishReason, + usage: { + inputTokens: { + uncached: usage.inputTokens, + total: usage.inputTokens + usage.cacheWriteInputTokens + usage.cacheReadInputTokens, + cacheRead: usage.cacheReadInputTokens, + cacheWrite: usage.cacheWriteInputTokens + }, + outputTokens: { + total: usage.outputTokens, + text: undefined, + reasoning: undefined + } + }, + response: buildHttpResponseDetails(response), + metadata + }) + + break + } + + case "content_block_start": { + blockType = event.content_block.type + + switch (event.content_block.type) { + case "text": { + contentBlocks.set(event.index, { type: "text" }) + + parts.push({ + type: "text-start", + id: event.index.toString() + }) + + break + } + + case "thinking": { + contentBlocks.set(event.index, { type: "reasoning" }) + + parts.push({ + type: "reasoning-start", + id: event.index.toString() + }) + + break + } + + case "redacted_thinking": { + contentBlocks.set(event.index, { type: "reasoning" }) + + const metadata: Response.ReasoningStartPartMetadata = { + anthropic: { + info: { + type: "redacted_thinking", + redactedData: event.content_block.data + } + } + } + + parts.push({ + type: "reasoning-start", + id: event.index.toString(), + metadata + }) + + break + } + + case "tool_use": { + const part = event.content_block + + const caller = Predicate.isNotUndefined(part.caller) + ? { + type: part.caller.type, + toolId: "tool_id" in part.caller ? part.caller.tool_id : null + } + : undefined + + const hasParams = Object.keys(part.input).length > 0 + const initialParams = hasParams ? JSON.stringify(part.input) : "" + // Map the provider wire name (e.g. "memory") back to the tool's + // custom name (e.g. "AnthropicMemory") that the toolkit is keyed + // by. The mapped name flows to the finalized tool-call via + // `contentBlock.name` on `content_block_stop`. + const toolName = toolNameMapper.getCustomName(part.name) + contentBlocks.set(event.index, { + type: "tool-call", + id: part.id, + name: toolName, + params: initialParams, + firstDelta: initialParams.length > 0, + ...(Predicate.isNotUndefined(caller) ? { caller } : undefined) + }) + + parts.push({ + type: "tool-params-start", + id: part.id, + name: toolName + }) + + break + } + + case "server_tool_use": { + const part = event.content_block + + if ( + part.name === "code_execution" || + part.name === "bash_code_execution" || + part.name === "text_editor_code_execution" || + part.name === "web_fetch" || + part.name === "web_search" + ) { + const toolName = toolNameMapper.getCustomName( + part.name === "bash_code_execution" || part.name === "text_editor_code_execution" + ? "code_execution" + : part.name + ) + + contentBlocks.set(event.index, { + type: "tool-call", + id: part.id, + name: toolName, + params: "", + firstDelta: true, + providerName: part.name, + providerExecuted: true + }) + + parts.push({ + type: "tool-params-start", + id: part.id, + name: toolName, + providerExecuted: true + }) + } else if ( + part.name === "tool_search_tool_bm25" || + part.name === "tool_search_tool_regex" + ) { + serverToolCalls.set(part.id, part.name) + + const toolName = toolNameMapper.getCustomName(part.name) + + contentBlocks.set(event.index, { + type: "tool-call", + id: part.id, + name: toolName, + params: "", + firstDelta: true, + providerName: part.name, + providerExecuted: true + }) + + parts.push({ + type: "tool-params-start", + id: part.id, + name: toolName, + providerExecuted: true + }) + } + + break + } + + case "web_fetch_tool_result": { + const part = event.content_block + const toolName = toolNameMapper.getCustomName("web_fetch") + + if (part.content.type === "web_fetch_result") { + citableDocuments.push({ + title: part.content.content.title ?? part.content.url, + mediaType: part.content.content.source.media_type + }) + + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content + }) + } else { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } + + break + } + + case "web_search_tool_result": { + const part = event.content_block + const toolName = toolNameMapper.getCustomName("web_search") + + if (Predicate.hasProperty(part.content, "type")) { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } else { + const idGenerator = yield* IdGenerator.IdGenerator + + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content + }) + + const content = part.content as ReadonlyArray + + for (const result of content) { + const id = yield* idGenerator.generateId() + + parts.push({ + type: "source", + sourceType: "url", + id, + url: result.url, + title: result.title, + metadata: { anthropic: { source: "web", pageAge: result.page_age } } + }) + } + } + break + } + + case "code_execution_tool_result": { + const part = event.content_block + const toolName = toolNameMapper.getCustomName("code_execution") + + if (part.content.type === "code_execution_result") { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content + }) + } else { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } + break + } + + case "bash_code_execution_tool_result": + case "text_editor_code_execution_tool_result": { + const part = event.content_block + const toolName = toolNameMapper.getCustomName("code_execution") + + if ( + part.content.type === "bash_code_execution_tool_result_error" || + part.content.type === "text_editor_code_execution_tool_result_error" + ) { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } else { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content + }) + } + break + } + + case "tool_search_tool_result": { + const part = event.content_block + let providerName = serverToolCalls.get(part.tool_use_id) + + if (Predicate.isUndefined(providerName)) { + const bm25Name = toolNameMapper.getCustomName("tool_search_tool_bm25") + const regexName = toolNameMapper.getCustomName("tool_search_tool_regex") + + if (bm25Name !== "tool_search_tool_bm25") { + providerName = "tool_search_tool_bm25" + } else if (regexName !== "tool_search_tool_regex") { + providerName = "tool_search_tool_regex" + } + } + + const toolName = toolNameMapper.getCustomName(providerName!) + + if (part.content.type === "tool_search_tool_search_result") { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: false, + result: part.content.tool_references + }) + } else { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolName, + isFailure: true, + result: part.content + }) + } + break + } + + case "mcp_tool_use": { + const part = event.content_block + + const toolCall: Response.ToolCallPartEncoded = { + type: "tool-call", + id: part.id, + name: part.name, + params: part.input, + providerExecuted: true, + metadata: { anthropic: { mcp_tool: { server: part.server_name } } } + } + + mcpToolCalls.set(part.id, toolCall) + + parts.push(toolCall) + + break + } + + case "mcp_tool_result": { + const part = event.content_block + const toolCall = mcpToolCalls.get(part.tool_use_id) + const mcpMetadata = toolCall?.metadata?.anthropic?.mcp_tool + + if (Predicate.isNotUndefined(toolCall)) { + parts.push({ + type: "tool-result", + id: part.tool_use_id, + name: toolCall.name, + isFailure: part.is_error, + result: part.content, + metadata: { + anthropic: { + ...(Predicate.isNotNullish(mcpMetadata) + ? { mcp_tool: mcpMetadata } : + undefined) + } + } + }) + } + + break + } + } + + break + } + + case "content_block_delta": { + const part = event.delta + + switch (part.type) { + case "text_delta": { + parts.push({ + type: "text-delta", + id: event.index.toString(), + delta: part.text + }) + + break + } + + case "thinking_delta": { + parts.push({ + type: "reasoning-delta", + id: event.index.toString(), + delta: part.thinking + }) + + break + } + + case "signature_delta": { + if (blockType === "thinking") { + parts.push({ + type: "reasoning-delta", + id: event.index.toString(), + delta: "", + metadata: { + anthropic: { + info: { + type: "thinking", + signature: part.signature + } + } + } + }) + } + + break + } + + case "input_json_delta": { + let delta = part.partial_json + + // Skip empty deltas + if (delta.length === 0) { + break + } + + const contentBlock = contentBlocks.get(event.index) + + // Skip invalid deltas + if (Predicate.isUndefined(contentBlock)) { + break + } + + // Skip non-tool-call deltas + if (contentBlock.type !== "tool-call") { + break + } + + if ( + contentBlock.firstDelta && + (contentBlock.providerName === "bash_code_execution" || + contentBlock.providerName === "text_editor_code_execution") + ) { + delta = `{"type":${JSON.stringify(contentBlock.providerName)},${delta.substring(1)}` + } + + parts.push({ + type: "tool-params-delta", + id: contentBlock.id, + delta + }) + + contentBlock.params += delta + contentBlock.firstDelta = false + + break + } + + case "citations_delta": { + const source = yield* processCitation(part.citation, citableDocuments) + + if (Predicate.isNotUndefined(source)) { + parts.push(source) + } + + break + } + } + + break + } + + case "content_block_stop": { + const contentBlock = contentBlocks.get(event.index) + + if (Predicate.isNotUndefined(contentBlock)) { + switch (contentBlock.type) { + case "text": { + parts.push({ + type: "text-end", + id: event.index.toString() + }) + + break + } + + case "reasoning": { + parts.push({ + type: "reasoning-end", + id: event.index.toString() + }) + + break + } + + case "tool-call": { + parts.push({ + type: "tool-params-end", + id: contentBlock.id + }) + + // For code execution, inject the `programmatic-tool-call` type + // when the input format is `{ code }` + let finalParams = contentBlock.params.length === 0 ? "{}" : contentBlock.params + + if (contentBlock.providerName === "code_execution") { + // @effect-diagnostics-next-line tryCatchInEffectGen:off + try { + const params = Tool.unsafeSecureJsonParse(finalParams) + if (Predicate.hasProperty(params, "code") && !Predicate.hasProperty(params, "type")) { + finalParams = JSON.stringify({ type: "programmatic-tool-call", ...params }) + } + } catch { + // Ignore errors and use original tool call parameters + } + } + + const params = contentBlock.providerExecuted === true + ? Tool.unsafeSecureJsonParse(finalParams) + : yield* transformToolCallParams( + options.tools, + contentBlock.name, + Tool.unsafeSecureJsonParse(finalParams) + ) + + parts.push({ + type: "tool-call", + id: contentBlock.id, + name: contentBlock.name, + params, + ...(Predicate.isNotUndefined(contentBlock.providerExecuted) + ? { providerExecuted: contentBlock.providerExecuted } + : undefined), + ...(Predicate.isNotUndefined(contentBlock.caller) + ? { metadata: { anthropic: { caller: contentBlock.caller } } } + : undefined) + }) + } + } + + contentBlocks.delete(event.index) + } + + blockType = undefined + + break + } + + case "error": { + parts.push({ + type: "error", + error: event.error, + metadata: { anthropic: { requestId: event.request_id } } + }) + + break + } + } + + return parts + })), + Stream.flattenIterable + ) + } +) + +// ============================================================================= +// Telemetry +// ============================================================================= + +const annotateRequest = ( + span: Span, + request: typeof Generated.BetaCreateMessageParams.Encoded +): void => { + addGenAIAnnotations(span, { + system: "anthropic", + operation: { name: "chat" }, + request: { + model: request.model, + temperature: request.temperature, + topK: request.top_k, + topP: request.top_p, + maxTokens: request.max_tokens, + stopSequences: Arr.ensure(request.stop_sequences).filter( + Predicate.isNotNullish + ) + } + }) +} + +const annotateResponse = (span: Span, response: Generated.BetaMessage): void => { + addGenAIAnnotations(span, { + response: { + id: response.id, + model: response.model, + finishReasons: response.stop_reason ? [response.stop_reason] : undefined + }, + usage: { + inputTokens: response.usage.input_tokens, + outputTokens: response.usage.output_tokens + } + }) +} + +const annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => { + if (part.type === "response-metadata") { + addGenAIAnnotations(span, { + response: { + id: part.id, + model: part.modelId + } + }) + } + if (part.type === "finish") { + addGenAIAnnotations(span, { + response: { + finishReasons: [part.reason] + }, + usage: { + inputTokens: part.usage.inputTokens.uncached, + outputTokens: part.usage.outputTokens.total + } + }) + } +} + +// ============================================================================= +// Internal Utilities +// ============================================================================= + +type ContentGroup = SystemMessageGroup | AssistantMessageGroup | UserMessageGroup + +interface SystemMessageGroup { + readonly type: "system" + readonly messages: Array +} + +interface AssistantMessageGroup { + readonly type: "assistant" + readonly messages: Array +} + +interface UserMessageGroup { + readonly type: "user" + readonly messages: Array +} + +const groupMessages = (prompt: Prompt.Prompt): Array => { + const messages: Array = [] + let current: ContentGroup | undefined = undefined + for (const message of prompt.content) { + switch (message.role) { + case "system": { + if (current?.type !== "system") { + current = { type: "system", messages: [] } + messages.push(current) + } + current.messages.push(message) + break + } + case "assistant": { + if (current?.type !== "assistant") { + current = { type: "assistant", messages: [] } + messages.push(current) + } + current.messages.push(message) + break + } + case "tool": + case "user": { + if (current?.type !== "user") { + current = { type: "user", messages: [] } + messages.push(current) + } + current.messages.push(message) + break + } + } + } + return messages +} + +/** + * Checks whether data is a URL (either a URL object or a URL string). + */ +const isUrlData = ( + data: typeof Prompt.FilePart.Type["data"] +): data is URL => data instanceof URL || isUrlString(data) + +const isUrlString = (data: typeof Prompt.FilePart.Type["data"]): boolean => + typeof data === "string" && /^https?:\/\//i.test(data) + +const getUrlString = (data: string | URL): string => data instanceof URL ? data.toString() : data + +const getCacheControl = ( + part: + | Prompt.SystemMessage + | Prompt.UserMessage + | Prompt.AssistantMessage + | Prompt.ToolMessage + | Prompt.UserMessagePart + | Prompt.AssistantMessagePart + | Prompt.ToolMessagePart +): typeof Generated.CacheControlEphemeral.Encoded | null => part.options.anthropic?.cacheControl ?? null + +const getDocumentMetadata = (part: Prompt.FilePart): { + readonly title: string | null + readonly context: string | null +} | null => { + const options = part.options.anthropic + if (Predicate.isNotUndefined(options)) { + return { + title: options?.documentTitle ?? null, + context: options?.documentContext ?? null + } + } + return null +} + +const areCitationsEnabled = (part: Prompt.FilePart): boolean => part.options.anthropic?.citations?.enabled ?? false + +const isCitationPart = (part: Prompt.UserMessagePart): part is Prompt.FilePart => + part.type === "file" && (part.mediaType === "application/pdf" || part.mediaType === "text/plain") + ? areCitationsEnabled(part) + : false + +interface CitableDocument { + readonly title: string + readonly fileName?: string | undefined + readonly mediaType: string +} + +const extractCitableDocuments = (prompt: Prompt.Prompt): Array => { + const citableDocuments: Array = [] + + for (const message of prompt.content) { + if (message.role === "user") { + for (const part of message.content) { + if (isCitationPart(part)) { + citableDocuments.push({ + title: part.fileName ?? "Untitled Document", + fileName: part.fileName, + mediaType: part.mediaType + }) + } + } + } + } + + return citableDocuments +} + +const processCitation = Effect.fnUntraced( + function*( + citation: + | Generated.ResponseCharLocationCitation + | Generated.ResponsePageLocationCitation + | Generated.ResponseContentBlockLocationCitation + | Generated.ResponseWebSearchResultLocationCitation + | Generated.ResponseSearchResultLocationCitation, + citableDocuments: ReadonlyArray + ): Effect.fn.Return< + Response.DocumentSourcePartEncoded | Response.UrlSourcePartEncoded | undefined, + never, + IdGenerator.IdGenerator + > { + const idGenerator = yield* IdGenerator.IdGenerator + + if (citation.type === "page_location" || citation.type === "char_location") { + const citedDocument = citableDocuments[citation.document_index] + if (Predicate.isNotUndefined(citedDocument)) { + const id = yield* idGenerator.generateId() + const metadata = citation.type === "char_location" + ? { + source: "document", + type: citation.type, + citedText: citation.cited_text, + startCharIndex: citation.start_char_index, + endCharIndex: citation.end_char_index + } as const + : { + source: "document", + type: citation.type, + citedText: citation.cited_text, + startPageNumber: citation.start_page_number, + endPageNumber: citation.end_page_number + } as const + + return { + type: "source", + sourceType: "document", + id, + mediaType: citedDocument.mediaType, + title: citation.document_title ?? citedDocument.title, + ...(Predicate.isNotUndefined(citedDocument.fileName) + ? { fileName: citedDocument.fileName } + : undefined), + metadata: { anthropic: metadata } + } + } + } + + if (citation.type === "web_search_result_location") { + const id = yield* idGenerator.generateId() + + const metadata = { + source: "url", + citedText: citation.cited_text, + encryptedIndex: citation.encrypted_index + } as const + + return { + type: "source", + sourceType: "url", + id, + url: citation.url, + title: citation.title ?? "Untitled", + metadata: { anthropic: metadata } + } + } + + return undefined + } +) + +interface ModelCapabilities { + readonly maxOutputTokens: number + readonly supportsStructuredOutput: boolean +} + +/** + * Returns the capabilities of a Claude model that are used for defaults and feature selection. + * Legacy models are listed as exceptions so newly released models inherit modern defaults. + * + * @see https://docs.claude.com/en/docs/about-claude/models/overview#model-comparison-table + * @see https://platform.claude.com/docs/en/build-with-claude/structured-outputs + */ +const getModelCapabilities = (modelId: string): ModelCapabilities => { + if ( + modelId.includes("claude-sonnet-4-5") || + modelId.includes("claude-opus-4-5") || + modelId.includes("claude-haiku-4-5") + ) { + return { + maxOutputTokens: 64000, + supportsStructuredOutput: true + } + } else if (modelId.includes("claude-opus-4-1")) { + return { + maxOutputTokens: 32000, + supportsStructuredOutput: true + } + } else if ( + modelId.includes("claude-sonnet-4-0") || + modelId.includes("claude-sonnet-4-20250514") || + modelId.includes("claude-3-7-sonnet") + ) { + return { + maxOutputTokens: 64000, + supportsStructuredOutput: false + } + } else if ( + modelId.includes("claude-opus-4-0") || + modelId.includes("claude-opus-4-20250514") + ) { + return { + maxOutputTokens: 32000, + supportsStructuredOutput: false + } + } else if (modelId.includes("claude-3-5-haiku")) { + return { + maxOutputTokens: 8192, + supportsStructuredOutput: false + } + } else if (modelId.includes("claude-3-")) { + return { + maxOutputTokens: 4096, + supportsStructuredOutput: false + } + } else { + return { + maxOutputTokens: 128000, + supportsStructuredOutput: true + } + } +} + +const unsupportedSchemaError = (error: unknown, method: string): AiError.AiError => + AiError.make({ + module: "AnthropicLanguageModel", + method, + reason: new AiError.UnsupportedSchemaError({ + description: error instanceof Error ? error.message : String(error) + }) + }) + +const tryCodecTransform = (schema: S, method: string) => + Effect.try({ + try: () => toCodecAnthropic(schema), + catch: (error) => unsupportedSchemaError(error, method) + }) + +const tryJsonSchema = (schema: S, method: string) => + Effect.try({ + try: () => Tool.getJsonSchemaFromSchema(schema, { transformer: toCodecAnthropic }), + catch: (error) => unsupportedSchemaError(error, method) + }) + +const tryToolJsonSchema = (tool: T, method: string) => + Effect.try({ + try: () => Tool.getJsonSchema(tool, { transformer: toCodecAnthropic }), + catch: (error) => unsupportedSchemaError(error, method) + }) + +const getOutputFormat = Effect.fnUntraced(function*({ capabilities, options }: { + readonly capabilities: ModelCapabilities + readonly options: LanguageModel.ProviderOptions +}): Effect.fn.Return { + if (options.responseFormat.type === "json" && capabilities.supportsStructuredOutput) { + const jsonSchema = yield* tryJsonSchema(options.responseFormat.schema, "getOutputFormat") + return { + type: "json_schema", + schema: jsonSchema as any + } + } + return undefined +}) + +const transformToolCallParams = Effect.fnUntraced(function*>( + tools: Tools, + toolName: string, + toolParams: unknown +): Effect.fn.Return { + const tool = tools.find((tool) => tool.name === toolName) + + if (Predicate.isUndefined(tool)) { + return yield* AiError.make({ + module: "AnthropicLanguageModel", + method: "makeResponse", + reason: new AiError.ToolNotFoundError({ + toolName, + availableTools: tools.map((tool) => tool.name) + }) + }) + } + + const { codec } = yield* tryCodecTransform(tool.parametersSchema, "makeResponse") + + const transform = Schema.decodeEffect(codec) + + return yield* ( + transform(toolParams) as Effect.Effect + ).pipe(Effect.mapError((error) => + AiError.make({ + module: "AnthropicLanguageModel", + method: "makeResponse", + reason: new AiError.ToolParameterValidationError({ + toolName, + toolParams, + description: formatIssue(error.issue) + }) + }) + )) +}) diff --git a/packages/effect-ai-anthropic/src/AnthropicTelemetry.ts b/packages/effect-ai-anthropic/src/AnthropicTelemetry.ts new file mode 100644 index 0000000..b8252bc --- /dev/null +++ b/packages/effect-ai-anthropic/src/AnthropicTelemetry.ts @@ -0,0 +1,164 @@ +/** + * The `AnthropicTelemetry` module defines Anthropic-specific telemetry + * attributes and a helper for adding them to a tracing span. It keeps the + * standard GenAI telemetry attributes and adds request and response metadata + * under the `gen_ai.anthropic.*` OpenTelemetry namespaces. + * + * @since 4.0.0 + */ +import { dual } from "effect/Function" +import * as String from "effect/String" +import type { Span } from "effect/Tracer" +import type { Simplify } from "effect/Types" +import * as Telemetry from "effect/unstable/ai/Telemetry" + +/** + * The attributes used to describe telemetry in the context of Generative + * Artificial Intelligence (GenAI) Models requests and responses. + * + * **Details** + * + * These attributes follow the OpenTelemetry generative AI semantic + * conventions: + * https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/ + * + * @category models + * @since 4.0.0 + */ +export type AnthropicTelemetryAttributes = Simplify< + & Telemetry.GenAITelemetryAttributes + & Telemetry.AttributesWithPrefix + & Telemetry.AttributesWithPrefix +> + +/** + * All telemetry attributes which are part of the GenAI specification, + * including the Anthropic-specific attributes. + * + * @category models + * @since 4.0.0 + */ +export type AllAttributes = Telemetry.AllAttributes & RequestAttributes & ResponseAttributes + +/** + * Telemetry attributes which are part of the GenAI specification and are + * namespaced by `gen_ai.anthropic.request`. + * + * @category models + * @since 4.0.0 + */ +export interface RequestAttributes { + /** + * Whether extended thinking is enabled. + */ + readonly extendedThinking?: boolean | null | undefined + /** + * The budget tokens for extended thinking. + */ + readonly thinkingBudgetTokens?: number | null | undefined +} + +/** + * Telemetry attributes which are part of the GenAI specification and are + * namespaced by `gen_ai.anthropic.response`. + * + * @category models + * @since 4.0.0 + */ +export interface ResponseAttributes { + /** + * The stop reason from the response. + */ + readonly stopReason?: string | null | undefined + /** + * Number of cache creation input tokens. + */ + readonly cacheCreationInputTokens?: number | null | undefined + /** + * Number of cache read input tokens. + */ + readonly cacheReadInputTokens?: number | null | undefined +} + +/** + * Options accepted by `addGenAIAnnotations`, combining standard GenAI telemetry attributes with optional Anthropic request and response attributes. + * + * @category options + * @since 4.0.0 + */ +export type AnthropicTelemetryAttributeOptions = Telemetry.GenAITelemetryAttributeOptions & { + anthropic?: { + request?: RequestAttributes | undefined + response?: ResponseAttributes | undefined + } | undefined +} + +const addAnthropicRequestAttributes = Telemetry.addSpanAttributes("gen_ai.anthropic.request", String.camelToSnake)< + RequestAttributes +> +const addAnthropicResponseAttributes = Telemetry.addSpanAttributes("gen_ai.anthropic.response", String.camelToSnake)< + ResponseAttributes +> + +/** + * Applies the specified Anthropic GenAI telemetry attributes to the provided + * `Span`. + * + * **When to use** + * + * Use to annotate an Anthropic model span with standard GenAI telemetry + * attributes and Anthropic-specific request or response metadata. + * + * **Gotchas** + * + * This method mutates the `Span` in place. + * + * @category tracing + * @since 4.0.0 + */ +export const addGenAIAnnotations: { + /** + * Applies the specified Anthropic GenAI telemetry attributes to the provided + * `Span`. + * + * **When to use** + * + * Use to annotate an Anthropic model span with standard GenAI telemetry + * attributes and Anthropic-specific request or response metadata. + * + * **Gotchas** + * + * This method mutates the `Span` in place. + * + * @category tracing + * @since 4.0.0 + */ + (options: AnthropicTelemetryAttributeOptions): (span: Span) => void + /** + * Applies the specified Anthropic GenAI telemetry attributes to the provided + * `Span`. + * + * **When to use** + * + * Use to annotate an Anthropic model span with standard GenAI telemetry + * attributes and Anthropic-specific request or response metadata. + * + * **Gotchas** + * + * This method mutates the `Span` in place. + * + * @category tracing + * @since 4.0.0 + */ + (span: Span, options: AnthropicTelemetryAttributeOptions): void +} = dual(2, (span: Span, options: AnthropicTelemetryAttributeOptions) => { + Telemetry.addGenAIAnnotations(span, options) + if (options.anthropic != null) { + if (options.anthropic.request != null) { + addAnthropicRequestAttributes(span, options.anthropic.request) + } + if (options.anthropic.response != null) { + addAnthropicResponseAttributes(span, options.anthropic.response) + } + } +}) diff --git a/packages/effect-ai-anthropic/src/AnthropicTool.ts b/packages/effect-ai-anthropic/src/AnthropicTool.ts new file mode 100644 index 0000000..e0f9751 --- /dev/null +++ b/packages/effect-ai-anthropic/src/AnthropicTool.ts @@ -0,0 +1,2518 @@ +/** + * The `AnthropicTool` module defines Anthropic provider tools and the schemas + * for their inputs and results. It covers Anthropic-owned tools such as Bash, + * Code Execution, Computer Use, Memory, Text Editor, Web Search, Web Fetch, and + * Tool Search, which can be attached to Anthropic-backed Effect AI language + * model requests. + * + * @since 4.0.0 + */ +import * as Schema from "effect/Schema" +import * as Tool from "effect/unstable/ai/Tool" +import * as Generated from "./Generated.ts" + +/** + * Union of all Anthropic provider-defined tool definitions exported by this module. + * + * **When to use** + * + * Use when a helper, collection, or option accepts any Anthropic + * provider-defined tool value created by this module. + * + * **Details** + * + * The union is built from the return types of the exported constructors, + * including Bash, Code Execution, Computer Use, Memory, Text Editor, Tool + * Search, Web Fetch, and Web Search tool versions. + * + * @category models + * @since 4.0.0 + */ +export type AnthropicTool = + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + +// ============================================================================= +// Bash +// ============================================================================= + +/** + * Defines the Anthropic Bash tool (2024-10-22 version). + * + * **When to use** + * + * Use when you want the model to execute bash commands with the 2024-10-22 + * Anthropic computer-use beta. + * + * **Details** + * + * Allows the model to execute bash commands in a sandboxed environment. + * Requires the "computer-use-2024-10-22" beta header. + * + * @see {@link Bash_20250124} for the newer 2025-01-24 version of the bash tool + * + * @category tools + * @since 4.0.0 + */ +export const Bash_20241022 = Tool.providerDefined({ + id: "anthropic.bash_20241022", + customName: "AnthropicBash", + providerName: "bash", + requiresHandler: true, + success: Schema.String, + parameters: Schema.Struct({ + command: Schema.String, + restart: Schema.optionalKey(Schema.Boolean) + }) +}) + +/** + * Defines the Anthropic Bash tool (2025-01-24 version). + * + * **When to use** + * + * Use when you want the model to execute bash commands with the 2025-01-24 + * Anthropic computer-use beta. + * + * **Details** + * + * Allows the model to execute bash commands in a sandboxed environment. + * Requires the "computer-use-2025-01-24" beta header. + * + * @see {@link Bash_20241022} for the older 2024-10-22 version of the bash tool + * + * @category tools + * @since 4.0.0 + */ +export const Bash_20250124 = Tool.providerDefined({ + id: "anthropic.bash_20250124", + customName: "AnthropicBash", + providerName: "bash", + requiresHandler: true, + success: Schema.String, + parameters: Schema.Struct({ + command: Schema.String, + restart: Schema.optionalKey(Schema.Boolean) + }) +}) + +// ============================================================================= +// Code Execution +// ============================================================================= + +// ----------------------------------------------------------------------------- +// Code Execution 20250522 Parameters +// ----------------------------------------------------------------------------- + +/** + * Schema for a code execution request that asks Anthropic to run source code as a programmatic tool call. + * + * **When to use** + * + * Use when constructing or validating a programmatic tool call for the Anthropic + * Code Execution tool. + * + * @see {@link CodeExecution_20250522} for the parent tool definition + * + * @category schemas + * @since 4.0.0 + */ +export const CodeExecutionProgrammaticToolCall = Schema.Struct({ + type: Schema.Literal("programmatic-tool-call"), + /** + * The code to execute. + */ + code: Schema.String +}) +/** + * Input payload for a programmatic code execution tool call, including the source code to execute. + * + * @category models + * @since 4.0.0 + */ +export type CodeExecutionProgrammaticToolCall = typeof CodeExecutionProgrammaticToolCall.Type + +/** + * Schema for the `bash_code_execution` input variant of Anthropic Code Execution. + * + * **When to use** + * + * Use when validating or constructing a bash command request for + * `CodeExecution_20250522`. + * + * **Details** + * + * The schema requires `type` to be `"bash_code_execution"` and `command` to + * contain the bash command sent to Anthropic. + * + * @see {@link CodeExecution_20250522} for the provider-defined tool that consumes this input variant + * + * @category schemas + * @since 4.0.0 + */ +export const CodeExecutionBashCommand = Schema.Struct({ + type: Schema.Literal("bash_code_execution"), + /** + * The bash command to execute. + */ + command: Schema.String +}) +/** + * Input payload for a bash command routed through the Anthropic code execution tool. + * + * **When to use** + * + * Use when representing a provider-executed bash command request for the + * 2025-05-22 code execution tool. + * + * **Details** + * + * The payload uses `type: "bash_code_execution"` to distinguish bash execution + * from programmatic code and text editor operations, and `command` contains the + * bash command to run. + * + * @see {@link CodeExecutionProgrammaticToolCall} for programmatic code execution input + * @see {@link CodeExecutionTextEditorView} for viewing files through text editor code execution + * @see {@link CodeExecutionTextEditorCreate} for creating files through text editor code execution + * @see {@link CodeExecutionTextEditorStrReplace} for replacing text through text editor code execution + * @see {@link CodeExecution_20250522} for the provider-defined tool that consumes this payload + * + * @category models + * @since 4.0.0 + */ +export type CodeExecutionBashCommand = typeof CodeExecutionBashCommand.Type + +/** + * Schema for a code execution text editor request that views a file by path. + * + * **When to use** + * + * Use when you need the schema for provider-bound code-execution view requests + * before distinguishing them from create or replace text-editor commands. + * + * **Details** + * + * The encoded payload uses `type: "text_editor_code_execution"`, + * `command: "view"`, and a `path` string. + * + * @see {@link CodeExecutionTextEditorCreate} for the command that creates a file + * @see {@link CodeExecutionTextEditorStrReplace} for the command that replaces text in a file + * + * @category schemas + * @since 4.0.0 + */ +export const CodeExecutionTextEditorView = Schema.Struct({ + type: Schema.Literal("text_editor_code_execution"), + command: Schema.Literal("view"), + /** + * Path to the file to view. + */ + path: Schema.String +}) +/** + * Input payload for the `view` command of Anthropic's text editor code execution tool. + * + * **When to use** + * + * Use when working at the Anthropic protocol boundary and the code-execution + * view request must be distinguished from standalone text-editor view requests. + * + * **Details** + * + * The payload is discriminated by `type: "text_editor_code_execution"` and + * `command: "view"`. The `path` field identifies the file to view. + * + * **Gotchas** + * + * This code execution view payload does not include `view_range`; line ranges + * are part of the standalone text editor view payload, not this code execution + * payload. + * + * @see {@link CodeExecution_20250522} for the provider-defined code execution tool that includes this payload + * @see {@link TextEditorViewCommand} for the standalone text editor view payload + * + * @category models + * @since 4.0.0 + */ +export type CodeExecutionTextEditorView = typeof CodeExecutionTextEditorView.Type + +/** + * Schema for a text editor code execution request that creates a file at a path. + * + * **When to use** + * + * Use when validating or constructing an Anthropic `text_editor_code_execution` + * tool call that should create a file. + * + * **Details** + * + * The request is discriminated by `type: "text_editor_code_execution"` and + * `command: "create"`. It requires `path` and accepts optional `file_text`; the + * schema allows `file_text` to be omitted, `null`, or a string. + * + * @see {@link CodeExecution_20250522} for the provider-defined tool that consumes this request + * @see {@link CodeExecutionTextEditorView} for the matching view request + * @see {@link CodeExecutionTextEditorStrReplace} for the matching replace request + * + * @category schemas + * @since 4.0.0 + */ +export const CodeExecutionTextEditorCreate = Schema.Struct({ + type: Schema.Literal("text_editor_code_execution"), + command: Schema.Literal("create"), + /** + * Path where the file should be created. + */ + path: Schema.String, + /** + * The content to write to the new file. + */ + file_text: Schema.optional(Schema.NullOr(Schema.String)) +}) +/** + * Input payload for creating a file through the text editor code execution tool, optionally including initial file text. + * + * @category models + * @since 4.0.0 + */ +export type CodeExecutionTextEditorCreate = typeof CodeExecutionTextEditorCreate.Type + +/** + * Schema for a code execution text editor request that replaces one exact string in a file. + * + * **When to use** + * + * Use when validating or constructing the `str_replace` text editor operation + * for the 2025-05-22 Anthropic code execution tool. + * + * **Gotchas** + * + * The `old_str` must match the file contents exactly, including whitespace and + * indentation, and must identify a single occurrence. + * + * @see {@link CodeExecutionTextEditorView} for reading file contents before choosing the replacement text + * @see {@link CodeExecution_20250522} for the provider-defined tool that consumes this payload + * + * @category schemas + * @since 4.0.0 + */ +export const CodeExecutionTextEditorStrReplace = Schema.Struct({ + type: Schema.Literal("text_editor_code_execution"), + command: Schema.Literal("str_replace"), + /** + * Path to the file to modify. + */ + path: Schema.String, + /** + * The text to replace. + */ + old_str: Schema.String, + /** + * The replacement text. + */ + new_str: Schema.String +}) +/** + * Input payload for replacing text in a file through the text editor code execution tool. + * + * @category models + * @since 4.0.0 + */ +export type CodeExecutionTextEditorStrReplace = typeof CodeExecutionTextEditorStrReplace.Type + +const CodeExecution_20250522_Parameters = Schema.Union([ + CodeExecutionProgrammaticToolCall, + CodeExecutionBashCommand, + CodeExecutionTextEditorView, + CodeExecutionTextEditorCreate, + CodeExecutionTextEditorStrReplace +]) + +// ----------------------------------------------------------------------------- +// Code Execution 20250825 Parameters +// ----------------------------------------------------------------------------- + +/** + * Schema for the 2025-08-25 code execution tool input, containing the code to execute. + * + * **When to use** + * + * Use when you need the schema for code-execution input at the Anthropic + * protocol boundary before sending source code to the 2025-08-25 tool. + * + * @see {@link CodeExecution_20250825} for the provider-defined tool that consumes this schema + * + * @category schemas + * @since 4.0.0 + */ +export const CodeExecution_20250825_Parameters = Schema.Struct({ + /** + * The code to execute. + */ + code: Schema.String +}) +/** + * Input payload for the 2025-08-25 Anthropic code execution tool. + * + * **When to use** + * + * Use when exposing the 2025-08-25 code-execution payload separately from the + * provider tool definition, such as at a transport or persistence boundary. + * + * **Details** + * + * The payload has a single `code` field containing the source code string to + * execute. + * + * @see {@link CodeExecution_20250825} for the provider-defined tool that consumes this payload + * + * @category models + * @since 4.0.0 + */ +export type CodeExecution_20250825_Parameters = typeof CodeExecution_20250825_Parameters.Type + +// ----------------------------------------------------------------------------- +// Code Execution Tool Definitions +// ----------------------------------------------------------------------------- + +/** + * Defines the Anthropic Code Execution tool (2025-05-22 version). + * + * **When to use** + * + * Use when you want the model to execute code in a sandboxed environment with + * the 2025-05-22 Anthropic code-execution beta. + * + * **Details** + * + * Allows the model to execute code in a sandboxed environment with support + * for multiple execution types including programmatic tool calls, bash + * execution, and text editor operations. + * + * @see {@link CodeExecutionProgrammaticToolCall} for the programmatic tool call schema + * + * @category tools + * @since 4.0.0 + */ +export const CodeExecution_20250522 = Tool.providerDefined({ + id: "anthropic.code_execution_20250522", + customName: "AnthropicCodeExecution", + providerName: "code_execution", + parameters: CodeExecution_20250522_Parameters, + success: Generated.BetaResponseCodeExecutionResultBlock, + failure: Generated.BetaResponseCodeExecutionToolResultError +}) + +/** + * Defines the Anthropic Code Execution tool (2025-08-25 version). + * + * **When to use** + * + * Use when you want the model to execute code in a sandboxed environment with + * the 2025-08-25 Anthropic code-execution beta. + * + * **Details** + * + * Requires the `code-execution-2025-08-25` beta header and uses + * `CodeExecution_20250825_Parameters` as its input schema. + * + * @see {@link CodeExecution_20250522} for the older 2025-05-22 code execution tool + * @see {@link CodeExecution_20250825_Parameters} for the input schema consumed by this tool + * + * @category tools + * @since 4.0.0 + */ +export const CodeExecution_20250825 = Tool.providerDefined({ + id: "anthropic.code_execution_20250825", + customName: "AnthropicCodeExecution", + providerName: "code_execution", + parameters: CodeExecution_20250825_Parameters, + success: Schema.Union([ + Generated.BetaResponseCodeExecutionResultBlock, + Generated.BetaResponseBashCodeExecutionResultBlock, + Generated.BetaResponseTextEditorCodeExecutionViewResultBlock, + Generated.BetaResponseTextEditorCodeExecutionCreateResultBlock, + Generated.BetaResponseTextEditorCodeExecutionStrReplaceResultBlock + ]), + failure: Schema.Union([ + Generated.BetaResponseCodeExecutionToolResultError, + Generated.BetaResponseBashCodeExecutionToolResultError, + Generated.BetaResponseTextEditorCodeExecutionToolResultError + ]) +}) + +// ============================================================================= +// Computer Use +// ============================================================================= + +// ----------------------------------------------------------------------------- +// Common Types +// ----------------------------------------------------------------------------- + +/** + * Schema for an `[x, y]` screen coordinate in pixels. + * + * **When to use** + * + * Use when validating computer-use action payloads that carry a single screen + * position and provider-side bounds checks remain acceptable. + * + * **Details** + * + * This is a two-number tuple used by computer-use actions that accept screen + * positions. + * + * **Gotchas** + * + * This schema validates tuple shape only and does not check display bounds. + * + * @category schemas + * @since 4.0.0 + */ +export const Coordinate = Schema.Tuple([Schema.Int, Schema.Int]) +/** + * An `[x, y]` screen coordinate in pixels. + * + * @category models + * @since 4.0.0 + */ +export type Coordinate = typeof Coordinate.Type + +/** + * Schema for an `[x1, y1, x2, y2]` screen region in pixels. + * + * **When to use** + * + * Use when validating computer-use action payloads that carry a rectangular + * screen region and provider-side bounds checks remain acceptable. + * + * **Details** + * + * The tuple represents top-left and bottom-right corners. + * + * **Gotchas** + * + * This schema validates four numbers only and does not check coordinate ordering + * or display bounds. + * + * @category schemas + * @since 4.0.0 + */ +export const Region = Schema.Tuple([Schema.Int, Schema.Int, Schema.Int, Schema.Int]) +/** + * An `[x1, y1, x2, y2]` screen region in pixels, from top-left to bottom-right. + * + * @category models + * @since 4.0.0 + */ +export type Region = typeof Region.Type + +/** + * Schema for scroll direction literals: `"up"`, `"down"`, `"left"`, or `"right"`. + * + * @see {@link ComputerUseScrollAction} for the action payload that consumes this schema + * + * @category schemas + * @since 4.0.0 + */ +export const ScrollDirection = Schema.Literals(["up", "down", "left", "right"]) +/** + * Direction used by computer-use scroll actions: `"up"`, `"down"`, `"left"`, or `"right"`. + * + * @category models + * @since 4.0.0 + */ +export type ScrollDirection = typeof ScrollDirection.Type + +/** + * Schema for modifier key literals. + * + * **Details** + * + * Allowed values are `"alt"`, `"ctrl"`, `"meta"`, and `"shift"`. + * + * @category schemas + * @since 4.0.0 + */ +export const ModifierKey = Schema.Literals(["alt", "ctrl", "meta", "shift"]) +/** + * Modifier key literals. + * + * **Details** + * + * Allowed values are `"alt"`, `"ctrl"`, `"meta"`, and `"shift"`. + * + * @category models + * @since 4.0.0 + */ +export type ModifierKey = typeof ModifierKey.Type + +// ----------------------------------------------------------------------------- +// ComputerUse_20241022_Args +// ----------------------------------------------------------------------------- + +const ComputerUse_20241022_Args = Schema.Struct({ + /** + * The width of the display being controlled by the model in pixels. + */ + displayWidthPx: Schema.Int, + + /** + * The height of the display being controlled by the model in pixels. + */ + displayHeightPx: Schema.Int, + + /** + * The display number to control (only relevant for X11 environments). If + * specified, the tool will be provided a display number in the tool + * definition. + */ + displayNumber: Schema.optional(Schema.Int) +}) + +const ComputerUse_20251124_Args = Schema.Struct({ + ...ComputerUse_20241022_Args.fields, + enableZoom: Schema.optional(Schema.Boolean) +}) + +// ----------------------------------------------------------------------------- +// Computer Use 20241022 Actions +// ----------------------------------------------------------------------------- + +/** + * Schema for a computer-use action that presses a key or key combination, such + * as `"Return"`, `"ctrl+c"`, or `"ctrl+s"`. + * + * **When to use** + * + * Use when validating or constructing a computer-use action for keyboard + * shortcuts or non-text key presses. + * + * @see {@link TypeAction} for entering ordinary text strings + * @see {@link ComputerUseHoldKeyAction} for holding a key for a duration + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseKeyAction = Schema.Struct({ + action: Schema.Literal("key"), + /** + * The key to press. + */ + text: Schema.String +}) +/** + * Computer-use action payload for pressing a key or key combination. + * + * **When to use** + * + * Use when typing parsed computer-use key action payloads after schema + * validation, where provider-specific key-name validation is handled outside + * TypeScript. + * + * **Details** + * + * The payload uses `action: "key"` and stores the key or key combination to + * press in `text`, such as `"Return"`, `"ctrl+c"`, or `"ctrl+s"`. + * + * **Gotchas** + * + * `text` is typed as `string`; the paired schema does not validate + * provider-specific key names or key combinations. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseKeyAction = typeof ComputerUseKeyAction.Type + +/** + * Schema for a computer-use action that performs a left click. + * + * **When to use** + * + * Use to validate or construct an Anthropic computer-use payload for clicking + * once at the current mouse position or at a specific screen coordinate. + * + * **Details** + * + * The encoded payload uses `action: "left_click"`. The optional `coordinate` + * field supplies the `[x, y]` pixel position; when omitted, the action uses the + * current mouse position. + * + * **Gotchas** + * + * The coordinate schema only checks that the value is a two-number tuple. It + * does not validate that the point falls within the configured display + * dimensions. + * + * @see {@link ComputerUseDoubleClickAction} for performing a double click + * @see {@link ComputerUseMouseMoveAction} for moving the mouse without clicking + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseLeftClickAction = Schema.Struct({ + action: Schema.Literal("left_click"), + /** + * The `[x, y]` coordinate on the screen to left click (defaults to the current + * mouse position if omitted). + */ + coordinate: Schema.optionalKey(Coordinate) +}) +/** + * Computer-use action payload for performing a left click, optionally at a specific coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseLeftClickAction = typeof ComputerUseLeftClickAction.Type + +/** + * Schema for a computer-use action that moves the mouse cursor to a required + * `[x, y]` screen coordinate. + * + * **When to use** + * + * Use to validate or construct a mouse movement action for an Anthropic + * computer-use tool call. + * + * **Details** + * + * The encoded payload has action `"mouse_move"` and a required `coordinate` + * field containing the target `[x, y]` pixel position. + * + * **Gotchas** + * + * The coordinate schema only checks that the value is a two-number tuple. It + * does not validate that the point falls within the configured display + * dimensions. + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseMouseMoveAction = Schema.Struct({ + action: Schema.Literal("mouse_move"), + /** + * The `[x, y]` coordinate on the screen to move to. + */ + coordinate: Coordinate +}) +/** + * Computer-use action payload for moving the mouse cursor to a specific coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseMouseMoveAction = typeof ComputerUseMouseMoveAction.Type + +/** + * Schema for a computer-use action that requests a screenshot of the current display. + * + * **When to use** + * + * Use to validate or construct a computer-use tool action that asks the handler + * to capture the full current display. + * + * **Details** + * + * The payload contains only `action: "screenshot"` and does not include + * coordinates or other options. + * + * @see {@link ComputerUseZoomAction} for requesting a zoomed-in screenshot of a specific screen region with the 2025-11-24 computer-use tool + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseScreenshotAction = Schema.Struct({ + action: Schema.Literal("screenshot") +}) +/** + * Computer-use action payload for capturing the current display. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseScreenshotAction = typeof ComputerUseScreenshotAction.Type + +/** + * Schema for a computer-use action that enters text. + * + * **When to use** + * + * Use to validate or construct a computer-use action for entering ordinary text + * strings. + * + * **Details** + * + * The payload uses `action: "type"` and a `text` string containing the text to + * enter. + * + * @see {@link ComputerUseKeyAction} for key presses and keyboard shortcuts + * + * @category schemas + * @since 4.0.0 + */ +export const TypeAction = Schema.Struct({ + action: Schema.Literal("type"), + /** + * The text to type. + */ + text: Schema.String +}) +/** + * Computer-use action payload for typing a text string. + * + * **Details** + * + * The payload uses `action: "type"` and a `text` string containing the text to + * enter. + * + * @category models + * @since 4.0.0 + */ +export type TypeAction = typeof TypeAction.Type + +const ComputerUse_20241022_Actions = Schema.Union([ + ComputerUseKeyAction, + ComputerUseLeftClickAction, + ComputerUseMouseMoveAction, + ComputerUseScreenshotAction, + TypeAction +]) + +// ----------------------------------------------------------------------------- +// Computer Use 20250124 Actions +// ----------------------------------------------------------------------------- + +/** + * Schema for a computer-use action that performs a double click. + * + * **When to use** + * + * Use to validate or construct an Anthropic computer-use payload for double + * clicking at the current mouse position or at a specific screen coordinate. + * + * **Details** + * + * The encoded payload uses `action: "double_click"`. The optional + * `coordinate` field supplies the `[x, y]` pixel position; when omitted, the + * action uses the current mouse position. + * + * **Gotchas** + * + * The coordinate schema only checks that the value is a two-number tuple. It + * does not validate that the point falls within the configured display + * dimensions. + * + * @see {@link ComputerUseLeftClickAction} for performing a single left click + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseDoubleClickAction = Schema.Struct({ + action: Schema.Literal("double_click"), + /** + * The coordinate to double click (defaults to the current mouse position if + * omitted). + */ + coordinate: Schema.optionalKey(Coordinate) +}) +/** + * Computer-use action payload for performing a double click, optionally at a specific coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseDoubleClickAction = typeof ComputerUseDoubleClickAction.Type + +/** + * Keeps a key pressed for a specified duration during computer-use execution. + * + * **When to use** + * + * Use to keep a keyboard key depressed for a fixed number of seconds in a + * computer-use action sequence. + * + * **Details** + * + * The schema describes objects with `action: "hold_key"`, a `text` field + * containing the key to hold, and a `duration` field containing the number of + * seconds to hold it. + * + * **Gotchas** + * + * The schema only checks that `duration` is a number; it does not require a + * positive value. + * + * @see {@link ComputerUseKeyAction} for pressing a key or key combination without holding it + * @see {@link ComputerUseWaitAction} for pausing between actions without holding a key + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseHoldKeyAction = Schema.Struct({ + action: Schema.Literal("hold_key"), + /** + * The key to hold (e.g. `"shift"`, `"ctrl"`). + */ + text: Schema.String, + /** + * The number of seconds to hold the key. + */ + duration: Schema.Finite +}) +/** + * Computer-use action payload for holding a key for a specified duration. + * + * **When to use** + * + * Use to represent a key that should remain pressed for a measured interval. + * + * **Details** + * + * Set `action` to `"hold_key"`, `text` to the key to hold, and `duration` to + * the number of seconds to hold it. + * + * @see {@link ComputerUseKeyAction} for a single key press or key combination without a hold duration + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseHoldKeyAction = typeof ComputerUseHoldKeyAction.Type + +/** + * Schema for a computer-use action that drags with the left mouse button. + * + * **When to use** + * + * Use to validate or construct an Anthropic computer-use payload for dragging + * from one screen coordinate to another in a single action. + * + * **Details** + * + * The encoded payload uses `action: "left_click_drag"` and requires both + * `start_coordinate` and `coordinate` as `[x, y]` pixel positions. + * + * **Gotchas** + * + * The coordinate schema only checks that each value is a two-number tuple. It + * does not validate that either point falls within the configured display + * dimensions. + * + * @see {@link ComputerUseLeftMouseDownAction} for starting a manual drag sequence + * @see {@link ComputerUseLeftMouseUpAction} for ending a manual drag sequence + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseLeftClickDragAction = Schema.Struct({ + action: Schema.Literal("left_click_drag"), + /** + * The `[x, y]` coordinate to start dragging from. + */ + start_coordinate: Coordinate, + /** + * The `[x, y]` coordinate to drag to. + */ + coordinate: Coordinate +}) +/** + * Computer-use action payload for dragging from a start coordinate to an end coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseLeftClickDragAction = typeof ComputerUseLeftClickDragAction.Type + +/** + * Starts a left mouse button press without releasing it. + * + * **When to use** + * + * Use when constructing a manual click or drag sequence that should press and + * hold the left mouse button before a later release. + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseLeftMouseDownAction = Schema.Struct({ + action: Schema.Literal("left_mouse_down"), + /** + * The coordinate at which the left mouse button should be held down (defaults + * to the current mouse position if omitted). + */ + coordinate: Schema.optionalKey(Coordinate) +}) +/** + * Computer-use action payload for pressing and holding the left mouse button, optionally at a specific coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseLeftMouseDownAction = typeof ComputerUseLeftMouseDownAction.Type + +/** + * Releases the left mouse button. + * + * **When to use** + * + * Use when constructing a manual click or drag sequence that should release the + * left mouse button after it was previously held down. + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseLeftMouseUpAction = Schema.Struct({ + action: Schema.Literal("left_mouse_up"), + /** + * The coordinate at which the left mouse button should be released (defaults + * to the current mouse position if omitted). + */ + coordinate: Schema.optionalKey(Coordinate) +}) +/** + * Computer-use action payload for releasing the left mouse button, optionally at a specific coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseLeftMouseUpAction = typeof ComputerUseLeftMouseUpAction.Type + +/** + * Schema for a computer-use action that performs a middle click. + * + * **When to use** + * + * Use to validate or construct a middle-button click action for Anthropic + * computer use, optionally targeting a specific screen coordinate. + * + * **Details** + * + * The payload must use `action: "middle_click"`. When `coordinate` is omitted, + * the click occurs at the current mouse position. + * + * **Gotchas** + * + * This action is available in the 2025-01-24 computer-use action set and later; + * it is not part of `ComputerUse_20241022`. + * + * @see {@link ComputerUse_20250124} for the provider-defined tool version that first accepts this action + * @see {@link ComputerUseLeftClickAction} for primary-button clicks + * @see {@link ComputerUseRightClickAction} for secondary-button clicks + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseMiddleClickAction = Schema.Struct({ + action: Schema.Literal("middle_click"), + /** + * The coordinate to middle click (defaults to the current mouse position if + * omitted). + */ + coordinate: Schema.optionalKey(Coordinate) +}) +/** + * Computer-use action payload for performing a middle click, optionally at a specific coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseMiddleClickAction = typeof ComputerUseMiddleClickAction.Type + +/** + * Schema for a computer-use action that performs a right click, optionally at a + * specific screen coordinate. + * + * **When to use** + * + * Use to validate or construct the `right_click` action for an Anthropic + * computer-use tool call. + * + * **Details** + * + * The optional `coordinate` field is an `[x, y]` screen coordinate in pixels. + * When omitted, the right click is performed at the current mouse position. + * + * @see {@link ComputerUse_20250124} for the provider-defined computer-use tool version that introduced this action + * @see {@link ComputerUseLeftClickAction} for the corresponding left-click action + * @see {@link ComputerUseMiddleClickAction} for the corresponding middle-click action + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseRightClickAction = Schema.Struct({ + action: Schema.Literal("right_click"), + /** + * The coordinate to right click (defaults to the current mouse position if + * omitted). + */ + coordinate: Schema.optionalKey(Coordinate) +}) +/** + * Computer-use action payload for performing a right click, optionally at a specific coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseRightClickAction = typeof ComputerUseRightClickAction.Type + +/** + * Schema for a computer-use scroll action. + * + * **When to use** + * + * Use when validating or constructing Anthropic computer-use scroll payloads. + * + * **Details** + * + * The encoded payload uses `action: "scroll"`, an optional `coordinate`, + * `scroll_direction`, and `scroll_amount`. + * + * **Gotchas** + * + * `coordinate` only checks a two-number tuple, and `scroll_amount` is only + * `Schema.Int`. + * + * @see {@link ComputerUse_20250124} for the tool version that accepts this action + * @see {@link ScrollDirection} for the accepted direction literals + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseScrollAction = Schema.Struct({ + action: Schema.Literal("scroll"), + /** + * The coordinate to start scrolling from (defaults to the current mouse + * position if omitted). + */ + coordinate: Schema.optionalKey(Coordinate), + /** + * The direction to scroll. + */ + scroll_direction: ScrollDirection, + /** + * The amount to scroll (in pixels or scroll units). + */ + scroll_amount: Schema.Int +}) +/** + * Computer-use action payload for scrolling by a specified amount in a specified direction, optionally from a coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseScrollAction = typeof ComputerUseScrollAction.Type + +/** + * Schema for a computer-use triple-click action. + * + * **When to use** + * + * Use when validating or constructing Anthropic computer-use triple-click + * payloads at the current pointer position or an optional coordinate. + * + * **Details** + * + * The encoded payload uses `action: "triple_click"` and an optional + * `coordinate`. + * + * **Gotchas** + * + * `coordinate` only validates as a two-number tuple and does not check display + * bounds. + * + * @see {@link ComputerUse_20250124} for the tool version that accepts this action + * @see {@link ComputerUseDoubleClickAction} for the two-click variant + * @see {@link ComputerUseLeftClickAction} for a single left click + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseTripleClickAction = Schema.Struct({ + action: Schema.Literal("triple_click"), + /** + * The coordinate to triple click (defaults to the current mouse position if + * omitted). + */ + coordinate: Schema.optionalKey(Coordinate) +}) +/** + * Computer-use action payload for performing a triple click, optionally at a specific coordinate. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseTripleClickAction = typeof ComputerUseTripleClickAction.Type + +/** + * Schema for a computer-use wait action. + * + * **When to use** + * + * Use when validating or constructing Anthropic computer-use payloads that pause + * between actions. + * + * **Details** + * + * The encoded payload uses `action: "wait"` and a required `duration` in + * seconds. + * + * **Gotchas** + * + * `duration` is only `Schema.Finite`; it is not constrained to positive + * values. + * + * @see {@link ComputerUseHoldKeyAction} for another duration-based computer-use action + * @see {@link ComputerUse_20250124} for the tool version that accepts this action + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseWaitAction = Schema.Struct({ + action: Schema.Literal("wait"), + /** + * The number of seconds to wait. + */ + duration: Schema.Finite +}) +/** + * Computer-use action payload for pausing for a specified duration. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseWaitAction = typeof ComputerUseWaitAction.Type + +const ComputerUse_20250124_Actions = Schema.Union([ + ...ComputerUse_20241022_Actions.members, + ComputerUseDoubleClickAction, + ComputerUseHoldKeyAction, + ComputerUseLeftClickDragAction, + ComputerUseLeftMouseDownAction, + ComputerUseLeftMouseUpAction, + ComputerUseMiddleClickAction, + ComputerUseRightClickAction, + ComputerUseScrollAction, + ComputerUseTripleClickAction, + ComputerUseWaitAction +]) + +// ----------------------------------------------------------------------------- +// Computer Use 20251124 Actions +// ----------------------------------------------------------------------------- + +/** + * Zooms into a specific region of the screen at full resolution. + * + * **When to use** + * + * Use when building or validating the 2025-11-24 computer-use action for a + * zoom-enabled tool definition. + * + * **Details** + * + * The encoded payload uses `action: "zoom"` and a `region` tuple. + * + * **Gotchas** + * + * Requires `enableZoom: true` in the tool definition. `region` is only a + * four-number tuple and does not validate corner ordering or display bounds. + * + * @see {@link ComputerUse_20251124} for the tool version that accepts this action + * @see {@link ComputerUseScreenshotAction} for capturing the full screen instead + * + * @category schemas + * @since 4.0.0 + */ +export const ComputerUseZoomAction = Schema.Struct({ + action: Schema.Literal("zoom"), + /** + * Region to zoom into, defined as `[x1, y1, x2, y2]` coordinates where + * `(x1, y1)` is the top-left corner and `(x2, y2)` is the bottom-right corner. + */ + region: Region +}) +/** + * Computer-use action payload for zooming into a specific screen region. + * + * **Gotchas** + * + * The enclosing computer-use tool must be configured with `enableZoom: true`. + * `region` is only a four-number tuple and does not validate corner ordering or + * display bounds. + * + * @category models + * @since 4.0.0 + */ +export type ComputerUseZoomAction = typeof ComputerUseZoomAction.Type + +const ComputerUse_20251124_Actions = Schema.Union([ + ...ComputerUse_20250124_Actions.members, + ComputerUseZoomAction +]) + +// ----------------------------------------------------------------------------- +// Computer Use Tool Definitions +// ----------------------------------------------------------------------------- + +/** + * Defines the deprecated computer-use tool for Claude 3.5 Sonnet v2. + * + * **Details** + * + * Requires the "computer-use-2024-10-22" beta header. + * Basic actions only: screenshot, left_click, type, key, mouse_move. + * + * @category tools + * @since 4.0.0 + */ +export const ComputerUse_20241022 = Tool.providerDefined({ + id: "anthropic.computer_use_20241022", + customName: "AnthropicComputerUse", + providerName: "computer_use", + requiresHandler: true, + args: ComputerUse_20241022_Args, + parameters: ComputerUse_20241022_Actions, + success: Schema.String +}) + +/** + * Defines the computer-use tool for Claude 4 models and Claude Sonnet 3.7. + * + * **When to use** + * + * Use when you need Anthropic computer use for Claude 4 models or Claude + * Sonnet 3.7 with the 2025-01-24 action set. + * + * **Details** + * + * Requires the "computer-use-2025-01-24" beta header. + * Includes basic actions plus enhanced actions: scroll, left_click_drag, + * right_click, middle_click, double_click, triple_click, left_mouse_down, + * left_mouse_up, hold_key, wait. + * + * @see {@link ComputerUse_20241022} for the older basic action set + * @see {@link ComputerUse_20251124} for the newer zoom-capable version + * + * @category tools + * @since 4.0.0 + */ +export const ComputerUse_20250124 = Tool.providerDefined({ + id: "anthropic.computer_20250124", + customName: "AnthropicComputerUse", + providerName: "computer", + requiresHandler: true, + args: ComputerUse_20241022_Args, + parameters: ComputerUse_20250124_Actions, + success: Schema.String +}) + +/** + * Defines the computer-use tool for Claude Opus 4.5 only. + * + * **When to use** + * + * Use when you need Anthropic computer use for Claude Opus 4.5 with the + * 2025-11-24 action set and zoom-capable screen inspection. + * + * **Details** + * + * Requires the "computer-use-2025-11-24" beta header. + * Includes all actions from computer_20250124 plus the zoom action for + * detailed screen region inspection. + * + * **Gotchas** + * + * Zoom actions require `enableZoom: true` in args. + * + * @see {@link ComputerUse_20250124} for the previous action set without zoom + * @see {@link ComputerUseZoomAction} for the zoom action payload + * + * @category tools + * @since 4.0.0 + */ +export const ComputerUse_20251124 = Tool.providerDefined({ + id: "anthropic.computer_20251124", + customName: "AnthropicComputerUse", + providerName: "computer", + requiresHandler: true, + args: ComputerUse_20251124_Args, + parameters: ComputerUse_20251124_Actions, + success: Schema.String +}) + +// ============================================================================= +// Memory +// ============================================================================= + +// ----------------------------------------------------------------------------- +// Common Types +// ----------------------------------------------------------------------------- + +/** + * Defines a `[start, end]` line range for viewing file contents. + * + * **When to use** + * + * Use when constructing or validating `view_range` for memory or text editor + * view commands. + * + * **Details** + * + * Lines are 1-indexed. Use `-1` for end to read to the end of the file. For + * example, `[1, 50]` views lines 1-50 and `[100, -1]` views from line 100 to + * the end of the file. + * + * @see {@link MemoryViewCommand} for memory view payloads that use this range + * @see {@link TextEditorViewCommand} for text editor view payloads that use this range + * + * @category schemas + * @since 4.0.0 + */ +export const ViewRange = Schema.Tuple([Schema.Int, Schema.Int]) +/** + * A `[start, end]` 1-indexed line range for viewing file contents, using `-1` as the end value to read through the end of the file. + * + * **When to use** + * + * Use when typing `view_range` for memory or text editor view commands. + * + * @category models + * @since 4.0.0 + */ +export type ViewRange = typeof ViewRange.Type + +// ----------------------------------------------------------------------------- +// Memory 20250818 Commands +// ----------------------------------------------------------------------------- + +/** + * Schema for the memory tool command that creates a new file at a path. + * + * **Details** + * + * The payload contains `command: "create"`, a `path` string, and the + * `file_text` content to write to the file. + * + * @category schemas + * @since 4.0.0 + */ +export const MemoryCreateCommand = Schema.Struct({ + command: Schema.Literal("create"), + /** + * The path to the file that should be created. + */ + path: Schema.String, + /** + * The content to write to the file. + */ + file_text: Schema.String +}) +/** + * Memory tool command payload for creating a new file at a path. + * + * @category models + * @since 4.0.0 + */ +export type MemoryCreateCommand = typeof MemoryCreateCommand.Type + +/** + * Schema for a memory command that deletes a file or directory. + * + * @category schemas + * @since 4.0.0 + */ +export const MemoryDeleteCommand = Schema.Struct({ + command: Schema.Literal("delete"), + /** + * The path to the file or directory to delete. + */ + path: Schema.String +}) +/** + * Memory tool command payload for deleting a file or directory at a path. + * + * @category models + * @since 4.0.0 + */ +export type MemoryDeleteCommand = typeof MemoryDeleteCommand.Type + +/** + * Schema for the memory `insert` command. + * + * **When to use** + * + * Use when validating or constructing `insert` payloads for `Memory_20250818`. + * + * **Details** + * + * The payload is discriminated by `command: "insert"` and requires `path`, + * `insert_line`, and `insert_text`. + * + * @see {@link Memory_20250818} for the provider-defined tool that consumes this command + * @see {@link MemoryStrReplaceCommand} for replacing existing text instead + * + * @category schemas + * @since 4.0.0 + */ +export const MemoryInsertCommand = Schema.Struct({ + command: Schema.Literal("insert"), + /** + * The path to the file to insert text into. + */ + path: Schema.String, + /** + * The line at which the text should be inserted. + */ + insert_line: Schema.Int, + /** + * The text to insert. + */ + insert_text: Schema.String +}) +/** + * Memory tool command payload for inserting text at a specific line in a file. + * + * @category models + * @since 4.0.0 + */ +export type MemoryInsertCommand = typeof MemoryInsertCommand.Type + +/** + * Schema for the memory command that renames or moves a file or directory. + * + * **Details** + * + * The payload uses `command: "rename"` and requires `old_path` as the current + * path plus `new_path` as the new destination path. + * + * @category schemas + * @since 4.0.0 + */ +export const MemoryRenameCommand = Schema.Struct({ + command: Schema.Literal("rename"), + /** + * The old path to the file or directory. + */ + old_path: Schema.String, + /** + * The new path to the file or directory. + */ + new_path: Schema.String +}) +/** + * Memory tool command payload for renaming or moving a file or directory. + * + * @category models + * @since 4.0.0 + */ +export type MemoryRenameCommand = typeof MemoryRenameCommand.Type + +/** + * Schema for the memory `str_replace` command. + * + * **When to use** + * + * Use when validating or constructing `str_replace` payloads for + * `Memory_20250818`. + * + * **Details** + * + * The payload is discriminated by `command: "str_replace"` and requires `path`, + * `old_str`, and `new_str`. + * + * @see {@link Memory_20250818} for the provider-defined tool that consumes this command + * + * @category schemas + * @since 4.0.0 + */ +export const MemoryStrReplaceCommand = Schema.Struct({ + command: Schema.Literal("str_replace"), + /** + * The path to the file in which the replacement should occur. + */ + path: Schema.String, + /** + * The text to replace. + */ + old_str: Schema.String, + /** + * The replacement text. + */ + new_str: Schema.String +}) +/** + * Memory tool command payload for replacing text in a file. + * + * @category models + * @since 4.0.0 + */ +export type MemoryStrReplaceCommand = typeof MemoryStrReplaceCommand.Type + +/** + * Shows directory contents or file contents with optional line ranges. + * + * **Details** + * + * When used on a file, returns file contents optionally limited by `view_range`. + * When used on a directory, lists contents. + * + * @category schemas + * @since 4.0.0 + */ +export const MemoryViewCommand = Schema.Struct({ + command: Schema.Literal("view"), + /** + * The path to the file or directory to view. + */ + path: Schema.String, + /** + * The specific lines to view. + */ + view_range: Schema.optionalKey(ViewRange) +}) +/** + * Memory tool command payload for viewing a file or directory, optionally with a file line range. + * + * @category models + * @since 4.0.0 + */ +export type MemoryViewCommand = typeof MemoryViewCommand.Type + +const Memory_20250818_Commands = Schema.Union([ + MemoryCreateCommand, + MemoryDeleteCommand, + MemoryInsertCommand, + MemoryRenameCommand, + MemoryStrReplaceCommand, + MemoryViewCommand +]) + +// ----------------------------------------------------------------------------- +// Memory Tool Definitions +// ----------------------------------------------------------------------------- + +/** + * Defines the memory tool for persistent file operations across conversations. + * + * **Details** + * + * Provides commands for creating, viewing, editing, renaming, and deleting + * files within the model's memory space. + * + * @category tools + * @since 4.0.0 + */ +export const Memory_20250818 = Tool.providerDefined({ + id: "anthropic.memory_20250818", + customName: "AnthropicMemory", + providerName: "memory", + requiresHandler: true, + parameters: Memory_20250818_Commands, + success: Schema.String +}) + +// ============================================================================= +// Text Editor +// ============================================================================= + +// ----------------------------------------------------------------------------- +// Text Editor Commands +// ----------------------------------------------------------------------------- + +/** + * Reads the contents of a file or lists directory contents. + * + * **When to use** + * + * Use when validating or constructing the standalone Anthropic Text Editor + * `view` command. + * + * **Details** + * + * When used on a file, returns the file contents, optionally limited to a line + * range. When used on a directory, lists all files and subdirectories. + * `view_range` is a 1-indexed `[start, end]` tuple where `-1` means through + * the end of the file. + * + * @see {@link CodeExecutionTextEditorView} for the code-execution variant without `view_range` + * + * @category schemas + * @since 4.0.0 + */ +export const TextEditorViewCommand = Schema.Struct({ + command: Schema.Literal("view"), + /** + * Absolute or relative path to the file or directory to view. + */ + path: Schema.String, + /** + * Optional line range to view (only applies to files, not directories). + * Lines are 1-indexed. Use -1 for end to read to end of file. + */ + view_range: Schema.optionalKey(ViewRange) +}) +/** + * Text editor command payload for viewing file contents or listing directory contents. + * + * **Details** + * + * `view_range` is a 1-indexed `[start, end]` tuple where `-1` means through + * the end of the file. + * + * @category models + * @since 4.0.0 + */ +export type TextEditorViewCommand = typeof TextEditorViewCommand.Type + +/** + * Create a new file with specified content. + * + * **When to use** + * + * Use when validating or constructing an Anthropic text editor `create` + * command. + * + * **Details** + * + * The payload is discriminated by `command: "create"` and requires both `path` + * and `file_text`. + * + * **Gotchas** + * + * Fails if the file already exists. Parent directories must exist. + * + * @category schemas + * @since 4.0.0 + */ +export const TextEditorCreateCommand = Schema.Struct({ + command: Schema.Literal("create"), + /** + * Path where the file should be created. + */ + path: Schema.String, + /** + * The content to write to the new file. + */ + file_text: Schema.String +}) +/** + * Text editor command payload for creating a new file with the specified content. + * + * **When to use** + * + * Use when typing parsed text-editor create command payloads after schema + * validation and before dispatching to Anthropic tool handlers. + * + * **Gotchas** + * + * The command fails if the file already exists or if parent directories are missing. + * + * @category models + * @since 4.0.0 + */ +export type TextEditorCreateCommand = typeof TextEditorCreateCommand.Type + +/** + * Replaces a specific string in a file with a new string. + * + * **When to use** + * + * Use when validating or constructing standalone Anthropic text editor + * `str_replace` commands. + * + * **Details** + * + * The payload uses `command: "str_replace"`, `path`, `old_str`, and `new_str`. + * `new_str` may be empty to delete text. + * + * **Gotchas** + * + * The `old_str` must match exactly (including whitespace and indentation) + * and must be unique in the file. + * + * @see {@link TextEditorViewCommand} for reading contents before choosing `old_str` + * @see {@link CodeExecutionTextEditorStrReplace} for the code-execution variant + * + * @category schemas + * @since 4.0.0 + */ +export const TextEditorStrReplaceCommand = Schema.Struct({ + command: Schema.Literal("str_replace"), + /** + * Path to the file to modify. + */ + path: Schema.String, + /** + * The exact string to find and replace (must be unique in the file). + */ + old_str: Schema.String, + /** + * The string to replace old_str with (can be empty to delete). + */ + new_str: Schema.String +}) +/** + * Text editor command payload for replacing one exact, unique string in a file. + * + * **When to use** + * + * Use when typing parsed text-editor replace command payloads that must carry + * one exact `old_str` match. + * + * **Gotchas** + * + * The `old_str` must match exactly, including whitespace and indentation, and + * must be unique in the file. + * + * @category models + * @since 4.0.0 + */ +export type TextEditorStrReplaceCommand = typeof TextEditorStrReplaceCommand.Type + +/** + * Inserts text at a specific line number in a file. + * + * **Details** + * + * Inserts the new text after the specified line number. Use `0` to insert at + * the beginning of the file; other values are 1-indexed. + * + * @category schemas + * @since 4.0.0 + */ +export const TextEditorInsertCommand = Schema.Struct({ + command: Schema.Literal("insert"), + /** + * Path to the file to modify. + */ + path: Schema.String, + /** + * The line number after which to insert (0 = beginning, 1-indexed). + */ + insert_line: Schema.Int, + /** + * The text to insert. + */ + new_str: Schema.String +}) +/** + * Text editor command payload for inserting text after a specific line number in a file. + * + * @category models + * @since 4.0.0 + */ +export type TextEditorInsertCommand = typeof TextEditorInsertCommand.Type + +/** + * Undoes the last edit made to a file. + * + * **Details** + * + * Reverts the most recent `str_replace`, `insert`, or `create` operation on the + * file. + * + * **Gotchas** + * + * This command is available in `text_editor_20241022` and + * `text_editor_20250124`, but not in `text_editor_20250429` or + * `text_editor_20250728`. + * + * @category schemas + * @since 4.0.0 + */ +export const TextEditorUndoEditCommand = Schema.Struct({ + command: Schema.Literal("undo_edit"), + /** + * Path to the file to undo the last edit on. + */ + path: Schema.String +}) +/** + * Text editor command payload for undoing the most recent edit to a file. + * + * **Gotchas** + * + * Available for `text_editor_20241022` and `text_editor_20250124`, but not for + * `text_editor_20250429` or `text_editor_20250728`. + * + * @category models + * @since 4.0.0 + */ +export type TextEditorUndoEditCommand = typeof TextEditorUndoEditCommand.Type + +const TextEditor_StrReplaceEditor_Commands = Schema.Union([ + TextEditorViewCommand, + TextEditorCreateCommand, + TextEditorStrReplaceCommand, + TextEditorInsertCommand, + TextEditorUndoEditCommand +]) + +const TextEditor_StrReplaceBasedEdit_Commands = Schema.Union([ + TextEditorViewCommand, + TextEditorCreateCommand, + TextEditorStrReplaceCommand, + TextEditorInsertCommand +]) + +// ----------------------------------------------------------------------------- +// Text Editor Args +// ----------------------------------------------------------------------------- + +const TextEditor_StrReplaceBasedEdit_Args = Schema.Struct({ + /** + * Maximum number of characters to return when viewing large files. + * When a file exceeds this limit, it will be truncated. + */ + max_characters: Schema.optional(Schema.Int) +}) + +// ----------------------------------------------------------------------------- +// Text Editor Tool Definitions +// ----------------------------------------------------------------------------- + +/** + * Defines the deprecated text editor tool for Claude 3.5 Sonnet. + * + * **When to use** + * + * Use when you need the 2024-10-22 `str_replace_editor` compatibility path for + * Claude 3.5 Sonnet. + * + * **Details** + * + * Requires the "computer-use-2024-10-22" beta header and supports `view`, + * `create`, `str_replace`, `insert`, and `undo_edit` commands. + * + * @see {@link TextEditor_20250124} for the newer `str_replace_editor` version + * @see {@link TextEditor_20250728} for the Claude 4 `str_replace_based_edit_tool` line + * + * @category tools + * @since 4.0.0 + */ +export const TextEditor_20241022 = Tool.providerDefined({ + id: "anthropic.text_editor_20241022", + customName: "AnthropicTextEditor", + providerName: "str_replace_editor", + requiresHandler: true, + parameters: TextEditor_StrReplaceEditor_Commands, + success: Schema.String +}) + +/** + * Defines the text editor tool for deprecated Claude Sonnet 3.7. + * + * **When to use** + * + * Use when you need the 2025-01-24 Claude Sonnet 3.7 text editor tool using + * `str_replace_editor`. + * + * **Details** + * + * Requires the "computer-use-2025-01-24" beta header, requires a handler, and + * supports `view`, `create`, `str_replace`, `insert`, and `undo_edit` commands. + * + * @see {@link TextEditor_20241022} for the older `str_replace_editor` version + * @see {@link TextEditor_20250429} for the Claude 4 `str_replace_based_edit_tool` line + * + * @category tools + * @since 4.0.0 + */ +export const TextEditor_20250124 = Tool.providerDefined({ + id: "anthropic.text_editor_20250124", + customName: "AnthropicTextEditor", + providerName: "str_replace_editor", + requiresHandler: true, + parameters: TextEditor_StrReplaceEditor_Commands, + success: Schema.String +}) + +/** + * Defines the text editor tool for Claude 4 models using Anthropic's `str_replace_based_edit_tool`. + * + * **When to use** + * + * Use when you need the 2025-04-29 Claude 4 `str_replace_based_edit_tool` + * version. + * + * **Details** + * + * Requires the "computer-use-2025-01-24" beta header. + * + * **Gotchas** + * + * This version does not support the `undo_edit` command. + * + * @see {@link TextEditor_20250124} for the previous `str_replace_editor` version + * @see {@link TextEditor_20250728} for the later Claude 4 text editor version + * + * @category tools + * @since 4.0.0 + */ +export const TextEditor_20250429 = Tool.providerDefined({ + id: "anthropic.text_editor_20250429", + customName: "AnthropicTextEditor", + providerName: "str_replace_based_edit_tool", + requiresHandler: true, + args: TextEditor_StrReplaceBasedEdit_Args, + parameters: TextEditor_StrReplaceBasedEdit_Commands, + success: Schema.String +}) + +/** + * Defines the text editor tool for Claude 4 models. + * + * **Details** + * + * Uses Anthropic's `str_replace_based_edit_tool`. `max_characters` can limit + * file-view output for this version. + * + * **Gotchas** + * + * This version does not support the `undo_edit` command. + * + * @category tools + * @since 4.0.0 + */ +export const TextEditor_20250728 = Tool.providerDefined({ + id: "anthropic.text_editor_20250728", + customName: "AnthropicTextEditor", + providerName: "str_replace_based_edit_tool", + requiresHandler: true, + args: TextEditor_StrReplaceBasedEdit_Args, + parameters: TextEditor_StrReplaceBasedEdit_Commands, + success: Schema.String +}) + +// ============================================================================= +// Web Search +// ============================================================================= + +// ----------------------------------------------------------------------------- +// Web Search Types +// ----------------------------------------------------------------------------- + +/** + * Describes user location for localizing search results. + * + * **When to use** + * + * Use when you need to localize search results for location-dependent queries + * like weather, local businesses, or events. + * + * **Details** + * + * The schema uses `type: "approximate"` plus optional `city`, `region`, + * `country`, and `timezone`. `country` is an ISO 3166-1 alpha-2 code, and + * `timezone` is an IANA time zone identifier. + * + * @see {@link WebSearch_20250305_Args} for the argument schema that consumes this location + * + * @category schemas + * @since 4.0.0 + */ +export const WebSearchUserLocation = Schema.Struct({ + /** + * Location type - currently only "approximate" is supported. + */ + type: Schema.Literal("approximate"), + /** + * City name. + */ + city: Schema.optional(Schema.String), + /** + * Region/state/province name. + */ + region: Schema.optional(Schema.String), + /** + * ISO 3166-1 alpha-2 country code. + */ + country: Schema.optional(Schema.String), + /** + * IANA timezone identifier. + */ + timezone: Schema.optional(Schema.String) +}) + +// ----------------------------------------------------------------------------- +// Web Search Args +// ----------------------------------------------------------------------------- + +/** + * Defines configuration arguments for the web search tool. + * + * **When to use** + * + * Use when you need to configure `WebSearch_20250305` with search limits, + * domain filters, or user location. + * + * **Details** + * + * The payload can set `maxUses`, `allowedDomains`, `blockedDomains`, and + * `userLocation`. + * + * **Gotchas** + * + * `allowedDomains` and `blockedDomains` are mutually exclusive. + * + * @see {@link WebSearch_20250305} for the provider-defined tool that consumes these arguments + * @see {@link WebSearchUserLocation} for localizing search results + * + * @category schemas + * @since 4.0.0 + */ +export const WebSearch_20250305_Args = Schema.Struct({ + /** + * Maximum number of searches allowed per API request. + */ + maxUses: Schema.optional(Schema.Int), + /** + * Restrict search results to only these domains. + * + * Cannot be used together with `blockedDomains`. + */ + allowedDomains: Schema.optional(Schema.Array(Schema.String)), + /** + * Exclude results from these domains. + * + * Cannot be used together with `allowedDomains`. + */ + blockedDomains: Schema.optional(Schema.Array(Schema.String)), + /** + * User location for localizing search results. + */ + userLocation: Schema.optional(WebSearchUserLocation) +}) +/** + * Configuration arguments for the Anthropic web search tool, including usage limits, domain filters, and optional user location. + * + * **Gotchas** + * + * `allowedDomains` and `blockedDomains` are mutually exclusive. + * + * @category models + * @since 4.0.0 + */ +export type WebSearch_20250305_Args = typeof WebSearch_20250305_Args.Type + +// ----------------------------------------------------------------------------- +// Web Search Parameters +// ----------------------------------------------------------------------------- + +/** + * Schema for Claude-supplied web search tool parameters. + * + * **Details** + * + * The payload contains the generated `query` string and is consumed by + * `WebSearch_20250305`. + * + * @see {@link WebSearch_20250305} for the provider-defined tool that consumes this payload + * + * @category schemas + * @since 4.0.0 + */ +export const WebSearchParameters = Schema.Struct({ + /** + * The search query generated by Claude. + */ + query: Schema.String +}) +/** + * Type of the parameters Claude supplies when invoking the Anthropic web search tool. + * + * **Details** + * + * Contains the generated search query used by `WebSearch_20250305`. + * + * @see {@link WebSearch_20250305} for the provider-defined tool that consumes this payload + * + * @category models + * @since 4.0.0 + */ +export type WebSearchParameters = typeof WebSearchParameters.Type + +// ----------------------------------------------------------------------------- +// Web Search Tool Definitions +// ----------------------------------------------------------------------------- + +/** + * Defines the web search tool for Claude models. + * + * **When to use** + * + * Use when you want Claude to search the web for real-time information. + * + * **Details** + * + * Enables Claude to search the web for real-time information. This is a + * server-side tool executed by Anthropic's infrastructure. + * Generally available (no beta header required). + * + * @see {@link WebFetch_20250910} for retrieving known URLs after discovery + * + * @category tools + * @since 4.0.0 + */ +export const WebSearch_20250305 = Tool.providerDefined({ + id: "anthropic.web_search_20250305", + customName: "AnthropicWebSearch", + providerName: "web_search", + args: WebSearch_20250305_Args, + parameters: WebSearchParameters, + success: Schema.Array(Generated.BetaResponseWebSearchResultBlock), + failure: Generated.BetaResponseWebSearchToolResultError +}) + +// ============================================================================= +// Web Fetch +// ============================================================================= + +// ----------------------------------------------------------------------------- +// Web Fetch Types +// ----------------------------------------------------------------------------- + +/** + * Defines citation configuration for web fetch. + * + * **When to use** + * + * Use when you need to enable or disable citations on web fetch results. + * + * **Details** + * + * The payload contains the `enabled` flag. `citations` is optional on + * `WebFetch_20250910_Args`, and citations are disabled by default. + * + * @see {@link WebFetch_20250910_Args} for the argument schema that consumes this configuration + * + * @category schemas + * @since 4.0.0 + */ +export const WebFetchCitationsConfig = Schema.Struct({ + /** + * Enable citations for fetched content. + */ + enabled: Schema.Boolean +}) +/** + * Configuration payload for enabling or disabling citations on web fetch results. + * + * **When to use** + * + * Use when typing parsed web-fetch citation configuration shared between + * request arguments and handler code. + * + * **Details** + * + * The payload contains the `enabled` flag. `citations` is optional on + * `WebFetch_20250910_Args`, and citations are disabled by default. + * + * @see {@link WebFetch_20250910_Args} for the argument schema that consumes this configuration + * + * @category models + * @since 4.0.0 + */ +export type WebFetchCitationsConfig = typeof WebFetchCitationsConfig.Type + +// ----------------------------------------------------------------------------- +// Web Fetch Args +// ----------------------------------------------------------------------------- + +/** + * Defines configuration arguments for the web fetch tool. + * + * **When to use** + * + * Use when you need to configure `WebFetch_20250910` with usage limits, domain + * filters, citations, or content token limits. + * + * **Details** + * + * The payload can set `maxUses`, domain filters, `citations`, and + * `maxContentTokens`, which map to Anthropic web fetch request fields. + * + * **Gotchas** + * + * `allowedDomains` and `blockedDomains` are mutually exclusive. + * `maxContentTokens` is approximate and does not apply to binary content such + * as PDFs. + * + * @see {@link WebFetch_20250910} for the provider-defined tool that consumes these arguments + * @see {@link WebFetchCitationsConfig} for configuring citations + * + * @category schemas + * @since 4.0.0 + */ +export const WebFetch_20250910_Args = Schema.Struct({ + /** + * Maximum number of fetches allowed per API request. + */ + maxUses: Schema.optional(Schema.Int), + /** + * Restrict fetches to only these domains. + * + * Cannot be used together with `blockedDomains`. + */ + allowedDomains: Schema.optional(Schema.Array(Schema.String)), + /** + * Exclude fetches from these domains. + * + * Cannot be used together with `allowedDomains`. + */ + blockedDomains: Schema.optional(Schema.Array(Schema.String)), + /** + * Enable citations for fetched content. + */ + citations: Schema.optional(WebFetchCitationsConfig), + /** + * Maximum content length in tokens. + */ + maxContentTokens: Schema.optional(Schema.Int) +}) +/** + * Configuration arguments for the Anthropic web fetch tool, including usage limits, domain filters, citation settings, and token limits. + * + * **When to use** + * + * Use when typing parsed web-fetch tool configuration shared by the + * provider-defined tool and request-building code. + * + * **Gotchas** + * + * `allowedDomains` and `blockedDomains` are mutually exclusive. + * `maxContentTokens` is approximate and does not apply to binary content such + * as PDFs. + * + * @category models + * @since 4.0.0 + */ +export type WebFetch_20250910_Args = typeof WebFetch_20250910_Args.Type + +// ----------------------------------------------------------------------------- +// Web Fetch Parameters +// ----------------------------------------------------------------------------- + +/** + * Schema for Claude-supplied web fetch parameters. + * + * **When to use** + * + * Use when validating or constructing the `url` payload consumed by + * `WebFetch_20250910`. + * + * **Details** + * + * The payload contains the single `url` parameter for Anthropic web fetch. + * + * **Gotchas** + * + * The URL must be user-provided or from prior search/fetch results. Maximum URL + * length is 250 characters. + * + * @see {@link WebFetch_20250910} for the provider-defined tool that consumes this payload + * + * @category schemas + * @since 4.0.0 + */ +export const WebFetchParameters = Schema.Struct({ + /** + * URL to fetch. Must be a URL provided by the user or from prior search/fetch + * results. Maximum URL length: 250 characters. + */ + url: Schema.String +}) +/** + * Type of the parameters Claude supplies when invoking the Anthropic web fetch tool. + * + * **When to use** + * + * Use when typing Claude-supplied web-fetch tool parameters after schema + * validation, before enforcing URL provenance or length constraints. + * + * **Details** + * + * The payload contains the single `url` parameter for Anthropic web fetch. + * + * **Gotchas** + * + * The URL must be user-provided or from prior search/fetch results. Maximum URL + * length is 250 characters. + * + * @category models + * @since 4.0.0 + */ +export type WebFetchParameters = typeof WebFetchParameters.Type + +// ----------------------------------------------------------------------------- +// Web Fetch Tool Definitions +// ----------------------------------------------------------------------------- + +/** + * Defines the web fetch tool for Claude models. + * + * **When to use** + * + * Use when you want Claude to retrieve the content of a specific web page or + * PDF. + * + * **Details** + * + * Allows Claude to retrieve full content from web pages and PDF documents. + * This is a server-side tool executed by Anthropic's infrastructure. Selecting + * this tool adds the "web-fetch-2025-09-10" beta header. + * + * @see {@link WebSearch_20250305} for discovering URLs before fetching specific content + * + * @category tools + * @since 4.0.0 + */ +export const WebFetch_20250910 = Tool.providerDefined({ + id: "anthropic.web_fetch_20250910", + customName: "AnthropicWebFetch", + providerName: "web_fetch", + args: WebFetch_20250910_Args, + parameters: WebFetchParameters, + success: Generated.BetaResponseWebFetchResultBlock, + failure: Generated.BetaResponseWebFetchToolResultError +}) + +// ============================================================================= +// Tool Search +// ============================================================================= + +// ----------------------------------------------------------------------------- +// Tool Search Parameters +// ----------------------------------------------------------------------------- + +/** + * Schema for regex-based tool search input parameters. + * + * **Details** + * + * Claude constructs regex patterns using Python's `re.search()` syntax. + * Maximum query length: 200 characters. + * + * @category schemas + * @since 4.0.0 + */ +export const ToolSearchRegexParameters = Schema.Struct({ + /** + * Python regex pattern to search for tools. + */ + query: Schema.String +}) +/** + * Type of the parameters Claude supplies when invoking regex-based Anthropic tool search. + * + * **Details** + * + * Claude constructs regex patterns using Python's `re.search()` syntax. + * Maximum query length: 200 characters. + * + * @category models + * @since 4.0.0 + */ +export type ToolSearchRegexParameters = typeof ToolSearchRegexParameters.Type + +/** + * Defines input parameters for BM25/natural language tool search. + * + * **When to use** + * + * Use when validating or constructing the natural-language query payload for + * `ToolSearchBM25_20251119`. + * + * **Details** + * + * The payload contains Claude's natural-language `query`. BM25 searches tool + * names, descriptions, argument names, and argument descriptions. + * + * @see {@link ToolSearchBM25_20251119} for the provider-defined tool that consumes these parameters + * + * @category schemas + * @since 4.0.0 + */ +export const ToolSearchBM25Parameters = Schema.Struct({ + /** + * Natural language query to search for tools. + */ + query: Schema.String +}) +/** + * Type of the parameters Claude supplies when invoking BM25 natural-language Anthropic tool search. + * + * @category models + * @since 4.0.0 + */ +export type ToolSearchBM25Parameters = typeof ToolSearchBM25Parameters.Type + +// ----------------------------------------------------------------------------- +// Tool Search Tool Definitions +// ----------------------------------------------------------------------------- + +/** + * Defines regex-based tool search for Claude models. + * + * **Details** + * + * Claude constructs regex patterns using Python's `re.search()` syntax to + * find tools. The regex is matched against tool names, descriptions, + * argument names, and argument descriptions. + * Requires the "advanced-tool-use-2025-11-20" beta header. + * + * @category tools + * @since 4.0.0 + */ +export const ToolSearchRegex_20251119 = Tool.providerDefined({ + id: "anthropic.tool_search_tool_regex_20251119", + customName: "AnthropicToolSearchRegex", + providerName: "tool_search_tool_regex", + parameters: ToolSearchRegexParameters, + success: Schema.Array(Generated.BetaRequestToolReferenceBlock), + failure: Generated.BetaResponseToolSearchToolResultError +}) + +/** + * Defines BM25/natural language tool search for Claude models. + * + * **When to use** + * + * Use when you want Claude to find relevant tools from a natural-language query + * instead of a regex pattern. + * + * **Details** + * + * Claude uses natural language queries to search for tools using the + * BM25 algorithm. The search is performed against tool names, descriptions, + * argument names, and argument descriptions. + * Requires the "advanced-tool-use-2025-11-20" beta header. + * + * @see {@link ToolSearchRegex_20251119} for the regex-pattern alternative + * + * @category tools + * @since 4.0.0 + */ +export const ToolSearchBM25_20251119 = Tool.providerDefined({ + id: "anthropic.tool_search_tool_bm25_20251119", + customName: "AnthropicToolSearchBM25", + providerName: "tool_search_tool_bm25", + parameters: ToolSearchBM25Parameters, + success: Schema.Array(Generated.BetaRequestToolReferenceBlock), + failure: Generated.BetaResponseToolSearchToolResultError +}) diff --git a/packages/effect-ai-anthropic/src/Generated.ts b/packages/effect-ai-anthropic/src/Generated.ts new file mode 100644 index 0000000..319aeb2 --- /dev/null +++ b/packages/effect-ai-anthropic/src/Generated.ts @@ -0,0 +1,12592 @@ +/** + * @since 4.0.0 + */ + +import * as Data from "effect/Data" +import * as Effect from "effect/Effect" +import type { SchemaError } from "effect/Schema" +import * as Schema from "effect/Schema" +import * as Stream from "effect/Stream" +import * as HttpClient from "effect/unstable/http/HttpClient" +import * as HttpClientError from "effect/unstable/http/HttpClientError" +import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +// non-recursive definitions +export type APIError = { readonly "message": string; readonly "type": "api_error" } +export const APIError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Internal server error" }), + "type": Schema.Literal("api_error").annotate({ "title": "Type", "default": "api_error" }) +}).annotate({ "title": "APIError" }) +export type AuthenticationError = { readonly "message": string; readonly "type": "authentication_error" } +export const AuthenticationError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Authentication error" }), + "type": Schema.Literal("authentication_error").annotate({ "title": "Type", "default": "authentication_error" }) +}).annotate({ "title": "AuthenticationError" }) +export type Base64ImageSource = { + readonly "data": string + readonly "media_type": "image/jpeg" | "image/png" | "image/gif" | "image/webp" + readonly "type": "base64" +} +export const Base64ImageSource = Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data", "format": "byte" }), + "media_type": Schema.Literals(["image/jpeg", "image/png", "image/gif", "image/webp"]).annotate({ + "title": "Media Type" + }), + "type": Schema.Literal("base64").annotate({ "title": "Type" }) +}).annotate({ "title": "Base64ImageSource" }) +export type Base64PDFSource = { + readonly "data": string + readonly "media_type": "application/pdf" + readonly "type": "base64" +} +export const Base64PDFSource = Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data", "format": "byte" }), + "media_type": Schema.Literal("application/pdf").annotate({ "title": "Media Type" }), + "type": Schema.Literal("base64").annotate({ "title": "Type" }) +}).annotate({ "title": "Base64PDFSource" }) +export type BashCodeExecutionToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "too_many_requests" + | "execution_time_exceeded" + | "output_file_too_large" +export const BashCodeExecutionToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "too_many_requests", + "execution_time_exceeded", + "output_file_too_large" +]).annotate({ "title": "BashCodeExecutionToolResultErrorCode" }) +export type BetaAPIError = { readonly "message": string; readonly "type": "api_error" } +export const BetaAPIError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Internal server error" }), + "type": Schema.Literal("api_error").annotate({ "title": "Type", "default": "api_error" }) +}).annotate({ "title": "APIError" }) +export type BetaAllThinkingTurns = { readonly "type": "all" } +export const BetaAllThinkingTurns = Schema.Struct({ "type": Schema.Literal("all").annotate({ "title": "Type" }) }) + .annotate({ "title": "AllThinkingTurns" }) +export type BetaAuthenticationError = { readonly "message": string; readonly "type": "authentication_error" } +export const BetaAuthenticationError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Authentication error" }), + "type": Schema.Literal("authentication_error").annotate({ "title": "Type", "default": "authentication_error" }) +}).annotate({ "title": "AuthenticationError" }) +export type BetaBase64ImageSource = { + readonly "data": string + readonly "media_type": "image/jpeg" | "image/png" | "image/gif" | "image/webp" + readonly "type": "base64" +} +export const BetaBase64ImageSource = Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data", "format": "byte" }), + "media_type": Schema.Literals(["image/jpeg", "image/png", "image/gif", "image/webp"]).annotate({ + "title": "Media Type" + }), + "type": Schema.Literal("base64").annotate({ "title": "Type" }) +}).annotate({ "title": "Base64ImageSource" }) +export type BetaBase64PDFSource = { + readonly "data": string + readonly "media_type": "application/pdf" + readonly "type": "base64" +} +export const BetaBase64PDFSource = Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data", "format": "byte" }), + "media_type": Schema.Literal("application/pdf").annotate({ "title": "Media Type" }), + "type": Schema.Literal("base64").annotate({ "title": "Type" }) +}).annotate({ "title": "Base64PDFSource" }) +export type BetaBashCodeExecutionToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "too_many_requests" + | "execution_time_exceeded" + | "output_file_too_large" +export const BetaBashCodeExecutionToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "too_many_requests", + "execution_time_exceeded", + "output_file_too_large" +]).annotate({ "title": "BashCodeExecutionToolResultErrorCode" }) +export type BetaBillingError = { readonly "message": string; readonly "type": "billing_error" } +export const BetaBillingError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Billing error" }), + "type": Schema.Literal("billing_error").annotate({ "title": "Type", "default": "billing_error" }) +}).annotate({ "title": "BillingError" }) +export type BetaBody_create_skill_v1_skills_post = { + readonly "display_title"?: string | null + readonly "files"?: ReadonlyArray | null +} +export const BetaBody_create_skill_v1_skills_post = Schema.Struct({ + "display_title": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Display Title", + "description": + "Display title for the skill.\n\nThis is a human-readable label that is not included in the prompt sent to the model." + }) + ), + "files": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String.annotate({ "format": "binary" })), Schema.Null]).annotate({ + "title": "Files", + "description": + "Files to upload for the skill.\n\nAll files must be in the same top-level directory and must include a SKILL.md file at the root of that directory." + }) + ) +}).annotate({ "title": "Body_create_skill_v1_skills_post" }) +export type BetaBody_create_skill_version_v1_skills__skill_id__versions_post = { + readonly "files"?: ReadonlyArray | null +} +export const BetaBody_create_skill_version_v1_skills__skill_id__versions_post = Schema.Struct({ + "files": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String.annotate({ "format": "binary" })), Schema.Null]).annotate({ + "title": "Files", + "description": + "Files to upload for the skill.\n\nAll files must be in the same top-level directory and must include a SKILL.md file at the root of that directory." + }) + ) +}).annotate({ "title": "Body_create_skill_version_v1_skills__skill_id__versions_post" }) +export type BetaCacheControlEphemeral = { readonly "ttl"?: "5m" | "1h"; readonly "type": "ephemeral" } +export const BetaCacheControlEphemeral = Schema.Struct({ + "ttl": Schema.optionalKey( + Schema.Literals(["5m", "1h"]).annotate({ + "title": "Ttl", + "description": + "The time-to-live for the cache control breakpoint.\n\nThis may be one the following values:\n- `5m`: 5 minutes\n- `1h`: 1 hour\n\nDefaults to `5m`." + }) + ), + "type": Schema.Literal("ephemeral").annotate({ "title": "Type" }) +}).annotate({ "title": "CacheControlEphemeral" }) +export type BetaCacheCreation = { + readonly "ephemeral_1h_input_tokens": number + readonly "ephemeral_5m_input_tokens": number +} +export const BetaCacheCreation = Schema.Struct({ + "ephemeral_1h_input_tokens": Schema.Number.annotate({ + "title": "Ephemeral 1H Input Tokens", + "description": "The number of input tokens used to create the 1 hour cache entry.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "ephemeral_5m_input_tokens": Schema.Number.annotate({ + "title": "Ephemeral 5M Input Tokens", + "description": "The number of input tokens used to create the 5 minute cache entry.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) +}).annotate({ "title": "CacheCreation" }) +export type BetaCanceledResult = { readonly "type": "canceled" } +export const BetaCanceledResult = Schema.Struct({ + "type": Schema.Literal("canceled").annotate({ "title": "Type", "default": "canceled" }) +}).annotate({ "title": "CanceledResult" }) +export type BetaCodeExecutionToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "too_many_requests" + | "execution_time_exceeded" +export const BetaCodeExecutionToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "too_many_requests", + "execution_time_exceeded" +]).annotate({ "title": "CodeExecutionToolResultErrorCode" }) +export type BetaCompactionContentBlockDelta = { readonly "content": string | null; readonly "type": "compaction_delta" } +export const BetaCompactionContentBlockDelta = Schema.Struct({ + "content": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Content" }), + "type": Schema.Literal("compaction_delta").annotate({ "title": "Type", "default": "compaction_delta" }) +}).annotate({ "title": "CompactionContentBlockDelta" }) +export type BetaContentBlockStopEvent = { readonly "index": number; readonly "type": "content_block_stop" } +export const BetaContentBlockStopEvent = Schema.Struct({ + "index": Schema.Number.annotate({ "title": "Index" }).check(Schema.isInt()), + "type": Schema.Literal("content_block_stop").annotate({ "title": "Type", "default": "content_block_stop" }) +}).annotate({ "title": "ContentBlockStopEvent" }) +export type BetaContextManagementResponse = { readonly "original_input_tokens": number } +export const BetaContextManagementResponse = Schema.Struct({ + "original_input_tokens": Schema.Number.annotate({ + "title": "Original Input Tokens", + "description": "The original token count before context management was applied" + }).check(Schema.isInt()) +}).annotate({ "title": "ContextManagementResponse" }) +export type BetaCreateSkillResponse = { + readonly "created_at": string + readonly "display_title": string | null + readonly "id": string + readonly "latest_version": string | null + readonly "source": string + readonly "type": string + readonly "updated_at": string +} +export const BetaCreateSkillResponse = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill was created." + }), + "display_title": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Display Title", + "description": + "Display title for the skill.\n\nThis is a human-readable label that is not included in the prompt sent to the model." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill.\n\nThe format and length of IDs may change over time." + }), + "latest_version": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Latest Version", + "description": + "The latest version identifier for the skill.\n\nThis represents the most recent version of the skill that has been created." + }), + "source": Schema.String.annotate({ + "title": "Source", + "description": + "Source of the skill.\n\nThis may be one of the following values:\n* `\"custom\"`: the skill was created by a user\n* `\"anthropic\"`: the skill was created by Anthropic" + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skills, this is always `\"skill\"`.", + "default": "skill" + }), + "updated_at": Schema.String.annotate({ + "title": "Updated At", + "description": "ISO 8601 timestamp of when the skill was last updated." + }) +}).annotate({ "title": "CreateSkillResponse" }) +export type BetaCreateSkillVersionResponse = { + readonly "created_at": string + readonly "description": string + readonly "directory": string + readonly "id": string + readonly "name": string + readonly "skill_id": string + readonly "type": string + readonly "version": string +} +export const BetaCreateSkillVersionResponse = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill version was created." + }), + "description": Schema.String.annotate({ + "title": "Description", + "description": "Description of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "directory": Schema.String.annotate({ + "title": "Directory", + "description": + "Directory name of the skill version.\n\nThis is the top-level directory name that was extracted from the uploaded files." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill version.\n\nThe format and length of IDs may change over time." + }), + "name": Schema.String.annotate({ + "title": "Name", + "description": + "Human-readable name of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "skill_id": Schema.String.annotate({ + "title": "Skill Id", + "description": "Identifier for the skill that this version belongs to." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skill Versions, this is always `\"skill_version\"`.", + "default": "skill_version" + }), + "version": Schema.String.annotate({ + "title": "Version", + "description": + "Version identifier for the skill.\n\nEach version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\")." + }) +}).annotate({ "title": "CreateSkillVersionResponse" }) +export type BetaDeleteMessageBatchResponse = { readonly "id": string; readonly "type": "message_batch_deleted" } +export const BetaDeleteMessageBatchResponse = Schema.Struct({ + "id": Schema.String.annotate({ "title": "Id", "description": "ID of the Message Batch." }), + "type": Schema.Literal("message_batch_deleted").annotate({ + "title": "Type", + "description": "Deleted object type.\n\nFor Message Batches, this is always `\"message_batch_deleted\"`.", + "default": "message_batch_deleted" + }) +}).annotate({ "title": "DeleteMessageBatchResponse" }) +export type BetaDeleteSkillResponse = { readonly "id": string; readonly "type": string } +export const BetaDeleteSkillResponse = Schema.Struct({ + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill.\n\nThe format and length of IDs may change over time." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Deleted object type.\n\nFor Skills, this is always `\"skill_deleted\"`.", + "default": "skill_deleted" + }) +}).annotate({ "title": "DeleteSkillResponse" }) +export type BetaDeleteSkillVersionResponse = { readonly "id": string; readonly "type": string } +export const BetaDeleteSkillVersionResponse = Schema.Struct({ + "id": Schema.String.annotate({ + "title": "Id", + "description": + "Version identifier for the skill.\n\nEach version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\")." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Deleted object type.\n\nFor Skill Versions, this is always `\"skill_version_deleted\"`.", + "default": "skill_version_deleted" + }) +}).annotate({ "title": "DeleteSkillVersionResponse" }) +export type BetaDirectCaller = { readonly "type": "direct" } +export const BetaDirectCaller = Schema.Struct({ "type": Schema.Literal("direct").annotate({ "title": "Type" }) }) + .annotate({ "title": "DirectCaller", "description": "Tool invocation directly from the model." }) +export type BetaEffortLevel = "low" | "medium" | "high" | "max" +export const BetaEffortLevel = Schema.Literals(["low", "medium", "high", "max"]).annotate({ + "title": "EffortLevel", + "description": "All possible effort levels." +}) +export type BetaExpiredResult = { readonly "type": "expired" } +export const BetaExpiredResult = Schema.Struct({ + "type": Schema.Literal("expired").annotate({ "title": "Type", "default": "expired" }) +}).annotate({ "title": "ExpiredResult" }) +export type BetaFileDeleteResponse = { readonly "id": string; readonly "type"?: "file_deleted" } +export const BetaFileDeleteResponse = Schema.Struct({ + "id": Schema.String.annotate({ "title": "Id", "description": "ID of the deleted file." }), + "type": Schema.optionalKey( + Schema.Literal("file_deleted").annotate({ + "title": "Type", + "description": "Deleted object type.\n\nFor file deletion, this is always `\"file_deleted\"`.", + "default": "file_deleted" + }) + ) +}).annotate({ "title": "FileDeleteResponse" }) +export type BetaFileDocumentSource = { readonly "file_id": string; readonly "type": "file" } +export const BetaFileDocumentSource = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("file").annotate({ "title": "Type" }) +}).annotate({ "title": "FileDocumentSource" }) +export type BetaFileImageSource = { readonly "file_id": string; readonly "type": "file" } +export const BetaFileImageSource = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("file").annotate({ "title": "Type" }) +}).annotate({ "title": "FileImageSource" }) +export type BetaFileMetadataSchema = { + readonly "created_at": string + readonly "downloadable"?: boolean + readonly "filename": string + readonly "id": string + readonly "mime_type": string + readonly "size_bytes": number + readonly "type": "file" +} +export const BetaFileMetadataSchema = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "RFC 3339 datetime string representing when the file was created.", + "format": "date-time" + }), + "downloadable": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Downloadable", + "description": "Whether the file can be downloaded.", + "default": false + }) + ), + "filename": Schema.String.annotate({ "title": "Filename", "description": "Original filename of the uploaded file." }) + .check(Schema.isMinLength(1)).check(Schema.isMaxLength(500)), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique object identifier.\n\nThe format and length of IDs may change over time." + }), + "mime_type": Schema.String.annotate({ "title": "Mime Type", "description": "MIME type of the file." }).check( + Schema.isMinLength(1) + ).check(Schema.isMaxLength(255)), + "size_bytes": Schema.Number.annotate({ "title": "Size Bytes", "description": "Size of the file in bytes." }).check( + Schema.isInt() + ).check(Schema.isGreaterThanOrEqualTo(0)), + "type": Schema.Literal("file").annotate({ + "title": "Type", + "description": "Object type.\n\nFor files, this is always `\"file\"`." + }) +}).annotate({ "title": "FileMetadataSchema" }) +export type BetaGatewayTimeoutError = { readonly "message": string; readonly "type": "timeout_error" } +export const BetaGatewayTimeoutError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Request timeout" }), + "type": Schema.Literal("timeout_error").annotate({ "title": "Type", "default": "timeout_error" }) +}).annotate({ "title": "GatewayTimeoutError" }) +export type BetaGetSkillResponse = { + readonly "created_at": string + readonly "display_title": string | null + readonly "id": string + readonly "latest_version": string | null + readonly "source": string + readonly "type": string + readonly "updated_at": string +} +export const BetaGetSkillResponse = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill was created." + }), + "display_title": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Display Title", + "description": + "Display title for the skill.\n\nThis is a human-readable label that is not included in the prompt sent to the model." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill.\n\nThe format and length of IDs may change over time." + }), + "latest_version": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Latest Version", + "description": + "The latest version identifier for the skill.\n\nThis represents the most recent version of the skill that has been created." + }), + "source": Schema.String.annotate({ + "title": "Source", + "description": + "Source of the skill.\n\nThis may be one of the following values:\n* `\"custom\"`: the skill was created by a user\n* `\"anthropic\"`: the skill was created by Anthropic" + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skills, this is always `\"skill\"`.", + "default": "skill" + }), + "updated_at": Schema.String.annotate({ + "title": "Updated At", + "description": "ISO 8601 timestamp of when the skill was last updated." + }) +}).annotate({ "title": "GetSkillResponse" }) +export type BetaGetSkillVersionResponse = { + readonly "created_at": string + readonly "description": string + readonly "directory": string + readonly "id": string + readonly "name": string + readonly "skill_id": string + readonly "type": string + readonly "version": string +} +export const BetaGetSkillVersionResponse = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill version was created." + }), + "description": Schema.String.annotate({ + "title": "Description", + "description": "Description of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "directory": Schema.String.annotate({ + "title": "Directory", + "description": + "Directory name of the skill version.\n\nThis is the top-level directory name that was extracted from the uploaded files." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill version.\n\nThe format and length of IDs may change over time." + }), + "name": Schema.String.annotate({ + "title": "Name", + "description": + "Human-readable name of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "skill_id": Schema.String.annotate({ + "title": "Skill Id", + "description": "Identifier for the skill that this version belongs to." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skill Versions, this is always `\"skill_version\"`.", + "default": "skill_version" + }), + "version": Schema.String.annotate({ + "title": "Version", + "description": + "Version identifier for the skill.\n\nEach version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\")." + }) +}).annotate({ "title": "GetSkillVersionResponse" }) +export type BetaInputJsonContentBlockDelta = { readonly "partial_json": string; readonly "type": "input_json_delta" } +export const BetaInputJsonContentBlockDelta = Schema.Struct({ + "partial_json": Schema.String.annotate({ "title": "Partial Json" }), + "type": Schema.Literal("input_json_delta").annotate({ "title": "Type", "default": "input_json_delta" }) +}).annotate({ "title": "InputJsonContentBlockDelta" }) +export type BetaInputTokensClearAtLeast = { readonly "type": "input_tokens"; readonly "value": number } +export const BetaInputTokensClearAtLeast = Schema.Struct({ + "type": Schema.Literal("input_tokens").annotate({ "title": "Type" }), + "value": Schema.Number.annotate({ "title": "Value" }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) +}).annotate({ "title": "InputTokensClearAtLeast" }) +export type BetaInputTokensTrigger = { readonly "type": "input_tokens"; readonly "value": number } +export const BetaInputTokensTrigger = Schema.Struct({ + "type": Schema.Literal("input_tokens").annotate({ "title": "Type" }), + "value": Schema.Number.annotate({ "title": "Value" }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)) +}).annotate({ "title": "InputTokensTrigger" }) +export type BetaInvalidRequestError = { readonly "message": string; readonly "type": "invalid_request_error" } +export const BetaInvalidRequestError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Invalid request" }), + "type": Schema.Literal("invalid_request_error").annotate({ "title": "Type", "default": "invalid_request_error" }) +}).annotate({ "title": "InvalidRequestError" }) +export type BetaJsonOutputFormat = { + readonly "schema": { readonly [x: string]: Schema.Json } + readonly "type": "json_schema" +} +export const BetaJsonOutputFormat = Schema.Struct({ + "schema": Schema.Record(Schema.String, Schema.Json).annotate({ + "title": "Schema", + "description": "The JSON schema of the format" + }), + "type": Schema.Literal("json_schema").annotate({ "title": "Type" }) +}).annotate({ "title": "JsonOutputFormat" }) +export type BetaJsonValue = unknown +export const BetaJsonValue = Schema.Unknown +export type BetaMCPToolConfig = { readonly "defer_loading"?: boolean; readonly "enabled"?: boolean } +export const BetaMCPToolConfig = Schema.Struct({ + "defer_loading": Schema.optionalKey(Schema.Boolean.annotate({ "title": "Defer Loading" })), + "enabled": Schema.optionalKey(Schema.Boolean.annotate({ "title": "Enabled" })) +}).annotate({ "title": "MCPToolConfig", "description": "Configuration for a specific tool in an MCP toolset." }) +export type BetaMessageBatch = { + readonly "archived_at": string | null + readonly "cancel_initiated_at": string | null + readonly "created_at": string + readonly "ended_at": string | null + readonly "expires_at": string + readonly "id": string + readonly "processing_status": "in_progress" | "canceling" | "ended" + readonly "request_counts": { + readonly "canceled": number + readonly "errored": number + readonly "expired": number + readonly "processing": number + readonly "succeeded": number + } + readonly "results_url": string | null + readonly "type": "message_batch" +} +export const BetaMessageBatch = Schema.Struct({ + "archived_at": Schema.Union([Schema.String.annotate({ "format": "date-time" }), Schema.Null]).annotate({ + "title": "Archived At", + "description": + "RFC 3339 datetime string representing the time at which the Message Batch was archived and its results became unavailable." + }), + "cancel_initiated_at": Schema.Union([Schema.String.annotate({ "format": "date-time" }), Schema.Null]).annotate({ + "title": "Cancel Initiated At", + "description": + "RFC 3339 datetime string representing the time at which cancellation was initiated for the Message Batch. Specified only if cancellation was initiated." + }), + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "RFC 3339 datetime string representing the time at which the Message Batch was created.", + "format": "date-time" + }), + "ended_at": Schema.Union([Schema.String.annotate({ "format": "date-time" }), Schema.Null]).annotate({ + "title": "Ended At", + "description": + "RFC 3339 datetime string representing the time at which processing for the Message Batch ended. Specified only once processing ends.\n\nProcessing ends when every request in a Message Batch has either succeeded, errored, canceled, or expired." + }), + "expires_at": Schema.String.annotate({ + "title": "Expires At", + "description": + "RFC 3339 datetime string representing the time at which the Message Batch will expire and end processing, which is 24 hours after creation.", + "format": "date-time" + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique object identifier.\n\nThe format and length of IDs may change over time." + }), + "processing_status": Schema.Literals(["in_progress", "canceling", "ended"]).annotate({ + "title": "Processing Status", + "description": "Processing status of the Message Batch." + }), + "request_counts": Schema.Struct({ + "canceled": Schema.Number.annotate({ + "title": "Canceled", + "description": + "Number of requests in the Message Batch that have been canceled.\n\nThis is zero until processing of the entire Message Batch has ended.", + "default": 0 + }).check(Schema.isInt()), + "errored": Schema.Number.annotate({ + "title": "Errored", + "description": + "Number of requests in the Message Batch that encountered an error.\n\nThis is zero until processing of the entire Message Batch has ended.", + "default": 0 + }).check(Schema.isInt()), + "expired": Schema.Number.annotate({ + "title": "Expired", + "description": + "Number of requests in the Message Batch that have expired.\n\nThis is zero until processing of the entire Message Batch has ended.", + "default": 0 + }).check(Schema.isInt()), + "processing": Schema.Number.annotate({ + "title": "Processing", + "description": "Number of requests in the Message Batch that are processing.", + "default": 0 + }).check(Schema.isInt()), + "succeeded": Schema.Number.annotate({ + "title": "Succeeded", + "description": + "Number of requests in the Message Batch that have completed successfully.\n\nThis is zero until processing of the entire Message Batch has ended.", + "default": 0 + }).check(Schema.isInt()) + }).annotate({ + "title": "RequestCounts", + "description": + "Tallies requests within the Message Batch, categorized by their status.\n\nRequests start as `processing` and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch." + }), + "results_url": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Results Url", + "description": + "URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only once processing ends.\n\nResults in the file are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests." + }), + "type": Schema.Literal("message_batch").annotate({ + "title": "Type", + "description": "Object type.\n\nFor Message Batches, this is always `\"message_batch\"`.", + "default": "message_batch" + }) +}).annotate({ "title": "MessageBatch" }) +export type BetaMessageStopEvent = { readonly "type": "message_stop" } +export const BetaMessageStopEvent = Schema.Struct({ + "type": Schema.Literal("message_stop").annotate({ "title": "Type", "default": "message_stop" }) +}).annotate({ "title": "MessageStopEvent" }) +export type BetaModelInfo = { + readonly "created_at": string + readonly "display_name": string + readonly "id": string + readonly "type": "model" +} +export const BetaModelInfo = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": + "RFC 3339 datetime string representing the time at which the model was released. May be set to an epoch value if the release date is unknown.", + "format": "date-time" + }), + "display_name": Schema.String.annotate({ + "title": "Display Name", + "description": "A human-readable name for the model." + }), + "id": Schema.String.annotate({ "title": "Id", "description": "Unique model identifier." }), + "type": Schema.Literal("model").annotate({ + "title": "Type", + "description": "Object type.\n\nFor Models, this is always `\"model\"`.", + "default": "model" + }) +}).annotate({ "title": "ModelInfo" }) +export type BetaNotFoundError = { readonly "message": string; readonly "type": "not_found_error" } +export const BetaNotFoundError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Not found" }), + "type": Schema.Literal("not_found_error").annotate({ "title": "Type", "default": "not_found_error" }) +}).annotate({ "title": "NotFoundError" }) +export type BetaOverloadedError = { readonly "message": string; readonly "type": "overloaded_error" } +export const BetaOverloadedError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Overloaded" }), + "type": Schema.Literal("overloaded_error").annotate({ "title": "Type", "default": "overloaded_error" }) +}).annotate({ "title": "OverloadedError" }) +export type BetaPermissionError = { readonly "message": string; readonly "type": "permission_error" } +export const BetaPermissionError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Permission denied" }), + "type": Schema.Literal("permission_error").annotate({ "title": "Type", "default": "permission_error" }) +}).annotate({ "title": "PermissionError" }) +export type BetaPlainTextSource = { + readonly "data": string + readonly "media_type": "text/plain" + readonly "type": "text" +} +export const BetaPlainTextSource = Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data" }), + "media_type": Schema.Literal("text/plain").annotate({ "title": "Media Type" }), + "type": Schema.Literal("text").annotate({ "title": "Type" }) +}).annotate({ "title": "PlainTextSource" }) +export type BetaRateLimitError = { readonly "message": string; readonly "type": "rate_limit_error" } +export const BetaRateLimitError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Rate limited" }), + "type": Schema.Literal("rate_limit_error").annotate({ "title": "Type", "default": "rate_limit_error" }) +}).annotate({ "title": "RateLimitError" }) +export type BetaRequestBashCodeExecutionOutputBlock = { + readonly "file_id": string + readonly "type": "bash_code_execution_output" +} +export const BetaRequestBashCodeExecutionOutputBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("bash_code_execution_output").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestBashCodeExecutionOutputBlock" }) +export type BetaRequestCharLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_char_index": number + readonly "start_char_index": number + readonly "type": "char_location" +} +export const BetaRequestCharLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([ + Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), + Schema.Null + ]).annotate({ "title": "Document Title" }), + "end_char_index": Schema.Number.annotate({ "title": "End Char Index" }).check(Schema.isInt()), + "start_char_index": Schema.Number.annotate({ "title": "Start Char Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "type": Schema.Literal("char_location").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestCharLocationCitation" }) +export type BetaRequestCitationsConfig = { readonly "enabled"?: boolean } +export const BetaRequestCitationsConfig = Schema.Struct({ + "enabled": Schema.optionalKey(Schema.Boolean.annotate({ "title": "Enabled" })) +}).annotate({ "title": "RequestCitationsConfig" }) +export type BetaRequestCodeExecutionOutputBlock = { + readonly "file_id": string + readonly "type": "code_execution_output" +} +export const BetaRequestCodeExecutionOutputBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("code_execution_output").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestCodeExecutionOutputBlock" }) +export type BetaRequestContentBlockLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_block_index": number + readonly "start_block_index": number + readonly "type": "content_block_location" +} +export const BetaRequestContentBlockLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([ + Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), + Schema.Null + ]).annotate({ "title": "Document Title" }), + "end_block_index": Schema.Number.annotate({ "title": "End Block Index" }).check(Schema.isInt()), + "start_block_index": Schema.Number.annotate({ "title": "Start Block Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "type": Schema.Literal("content_block_location").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestContentBlockLocationCitation" }) +export type BetaRequestMCPServerToolConfiguration = { + readonly "allowed_tools"?: ReadonlyArray | null + readonly "enabled"?: boolean | null +} +export const BetaRequestMCPServerToolConfiguration = Schema.Struct({ + "allowed_tools": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ "title": "Allowed Tools" }) + ), + "enabled": Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null]).annotate({ "title": "Enabled" })) +}).annotate({ "title": "RequestMCPServerToolConfiguration" }) +export type BetaRequestPageLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_page_number": number + readonly "start_page_number": number + readonly "type": "page_location" +} +export const BetaRequestPageLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([ + Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), + Schema.Null + ]).annotate({ "title": "Document Title" }), + "end_page_number": Schema.Number.annotate({ "title": "End Page Number" }).check(Schema.isInt()), + "start_page_number": Schema.Number.annotate({ "title": "Start Page Number" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(1) + ), + "type": Schema.Literal("page_location").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestPageLocationCitation" }) +export type BetaRequestSearchResultLocationCitation = { + readonly "cited_text": string + readonly "end_block_index": number + readonly "search_result_index": number + readonly "source": string + readonly "start_block_index": number + readonly "title": string | null + readonly "type": "search_result_location" +} +export const BetaRequestSearchResultLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "end_block_index": Schema.Number.annotate({ "title": "End Block Index" }).check(Schema.isInt()), + "search_result_index": Schema.Number.annotate({ "title": "Search Result Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "source": Schema.String.annotate({ "title": "Source" }), + "start_block_index": Schema.Number.annotate({ "title": "Start Block Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Title" }), + "type": Schema.Literal("search_result_location").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestSearchResultLocationCitation" }) +export type BetaRequestTextEditorCodeExecutionCreateResultBlock = { + readonly "is_file_update": boolean + readonly "type": "text_editor_code_execution_create_result" +} +export const BetaRequestTextEditorCodeExecutionCreateResultBlock = Schema.Struct({ + "is_file_update": Schema.Boolean.annotate({ "title": "Is File Update" }), + "type": Schema.Literal("text_editor_code_execution_create_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionCreateResultBlock" }) +export type BetaRequestTextEditorCodeExecutionStrReplaceResultBlock = { + readonly "lines"?: ReadonlyArray | null + readonly "new_lines"?: number | null + readonly "new_start"?: number | null + readonly "old_lines"?: number | null + readonly "old_start"?: number | null + readonly "type": "text_editor_code_execution_str_replace_result" +} +export const BetaRequestTextEditorCodeExecutionStrReplaceResultBlock = Schema.Struct({ + "lines": Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ "title": "Lines" })), + "new_lines": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "New Lines" }) + ), + "new_start": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "New Start" }) + ), + "old_lines": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Old Lines" }) + ), + "old_start": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Old Start" }) + ), + "type": Schema.Literal("text_editor_code_execution_str_replace_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionStrReplaceResultBlock" }) +export type BetaRequestTextEditorCodeExecutionViewResultBlock = { + readonly "content": string + readonly "file_type": "text" | "image" | "pdf" + readonly "num_lines"?: number | null + readonly "start_line"?: number | null + readonly "total_lines"?: number | null + readonly "type": "text_editor_code_execution_view_result" +} +export const BetaRequestTextEditorCodeExecutionViewResultBlock = Schema.Struct({ + "content": Schema.String.annotate({ "title": "Content" }), + "file_type": Schema.Literals(["text", "image", "pdf"]).annotate({ "title": "File Type" }), + "num_lines": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Num Lines" }) + ), + "start_line": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Start Line" }) + ), + "total_lines": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Total Lines" }) + ), + "type": Schema.Literal("text_editor_code_execution_view_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionViewResultBlock" }) +export type BetaRequestWebSearchResultBlock = { + readonly "encrypted_content": string + readonly "page_age"?: string | null + readonly "title": string + readonly "type": "web_search_result" + readonly "url": string +} +export const BetaRequestWebSearchResultBlock = Schema.Struct({ + "encrypted_content": Schema.String.annotate({ "title": "Encrypted Content" }), + "page_age": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Page Age" })), + "title": Schema.String.annotate({ "title": "Title" }), + "type": Schema.Literal("web_search_result").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "RequestWebSearchResultBlock" }) +export type BetaRequestWebSearchResultLocationCitation = { + readonly "cited_text": string + readonly "encrypted_index": string + readonly "title": string | null + readonly "type": "web_search_result_location" + readonly "url": string +} +export const BetaRequestWebSearchResultLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "encrypted_index": Schema.String.annotate({ "title": "Encrypted Index" }), + "title": Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(512)), Schema.Null]) + .annotate({ "title": "Title" }), + "type": Schema.Literal("web_search_result_location").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url" }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(2048)) +}).annotate({ "title": "RequestWebSearchResultLocationCitation" }) +export type BetaResponseBashCodeExecutionOutputBlock = { + readonly "file_id": string + readonly "type": "bash_code_execution_output" +} +export const BetaResponseBashCodeExecutionOutputBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("bash_code_execution_output").annotate({ + "title": "Type", + "default": "bash_code_execution_output" + }) +}).annotate({ "title": "ResponseBashCodeExecutionOutputBlock" }) +export type BetaResponseCharLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_char_index": number + readonly "file_id": string | null + readonly "start_char_index": number + readonly "type": "char_location" +} +export const BetaResponseCharLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Document Title" }), + "end_char_index": Schema.Number.annotate({ "title": "End Char Index" }).check(Schema.isInt()), + "file_id": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "File Id", "default": null }), + "start_char_index": Schema.Number.annotate({ "title": "Start Char Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "type": Schema.Literal("char_location").annotate({ "title": "Type", "default": "char_location" }) +}).annotate({ "title": "ResponseCharLocationCitation" }) +export type BetaResponseCitationsConfig = { readonly "enabled": boolean } +export const BetaResponseCitationsConfig = Schema.Struct({ + "enabled": Schema.Boolean.annotate({ "title": "Enabled", "default": false }) +}).annotate({ "title": "ResponseCitationsConfig" }) +export type BetaResponseClearThinking20251015Edit = { + readonly "cleared_input_tokens": number + readonly "cleared_thinking_turns": number + readonly "type": "clear_thinking_20251015" +} +export const BetaResponseClearThinking20251015Edit = Schema.Struct({ + "cleared_input_tokens": Schema.Number.annotate({ + "title": "Cleared Input Tokens", + "description": "Number of input tokens cleared by this edit." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "cleared_thinking_turns": Schema.Number.annotate({ + "title": "Cleared Thinking Turns", + "description": "Number of thinking turns that were cleared." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "type": Schema.Literal("clear_thinking_20251015").annotate({ + "title": "Type", + "description": "The type of context management edit applied.", + "default": "clear_thinking_20251015" + }) +}).annotate({ "title": "ResponseClearThinking20251015Edit" }) +export type BetaResponseClearToolUses20250919Edit = { + readonly "cleared_input_tokens": number + readonly "cleared_tool_uses": number + readonly "type": "clear_tool_uses_20250919" +} +export const BetaResponseClearToolUses20250919Edit = Schema.Struct({ + "cleared_input_tokens": Schema.Number.annotate({ + "title": "Cleared Input Tokens", + "description": "Number of input tokens cleared by this edit." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "cleared_tool_uses": Schema.Number.annotate({ + "title": "Cleared Tool Uses", + "description": "Number of tool uses that were cleared." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "type": Schema.Literal("clear_tool_uses_20250919").annotate({ + "title": "Type", + "description": "The type of context management edit applied.", + "default": "clear_tool_uses_20250919" + }) +}).annotate({ "title": "ResponseClearToolUses20250919Edit" }) +export type BetaResponseCodeExecutionOutputBlock = { + readonly "file_id": string + readonly "type": "code_execution_output" +} +export const BetaResponseCodeExecutionOutputBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("code_execution_output").annotate({ "title": "Type", "default": "code_execution_output" }) +}).annotate({ "title": "ResponseCodeExecutionOutputBlock" }) +export type BetaResponseCompactionBlock = { readonly "content": string | null; readonly "type": "compaction" } +export const BetaResponseCompactionBlock = Schema.Struct({ + "content": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Content", + "description": "Summary of compacted content, or null if compaction failed" + }), + "type": Schema.Literal("compaction").annotate({ "title": "Type", "default": "compaction" }) +}).annotate({ + "title": "ResponseCompactionBlock", + "description": + "A compaction block returned when autocompact is triggered.\n\nWhen content is None, it indicates the compaction failed to produce a valid\nsummary (e.g., malformed output from the model). Clients may round-trip\ncompaction blocks with null content; the server treats them as no-ops." +}) +export type BetaResponseContainerUploadBlock = { readonly "file_id": string; readonly "type": "container_upload" } +export const BetaResponseContainerUploadBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("container_upload").annotate({ "title": "Type", "default": "container_upload" }) +}).annotate({ + "title": "ResponseContainerUploadBlock", + "description": "Response model for a file uploaded to the container." +}) +export type BetaResponseContentBlockLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_block_index": number + readonly "file_id": string | null + readonly "start_block_index": number + readonly "type": "content_block_location" +} +export const BetaResponseContentBlockLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Document Title" }), + "end_block_index": Schema.Number.annotate({ "title": "End Block Index" }).check(Schema.isInt()), + "file_id": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "File Id", "default": null }), + "start_block_index": Schema.Number.annotate({ "title": "Start Block Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "type": Schema.Literal("content_block_location").annotate({ "title": "Type", "default": "content_block_location" }) +}).annotate({ "title": "ResponseContentBlockLocationCitation" }) +export type BetaResponseMCPToolUseBlock = { + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": string + readonly "server_name": string + readonly "type": "mcp_tool_use" +} +export const BetaResponseMCPToolUseBlock = Schema.Struct({ + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.String.annotate({ "title": "Name", "description": "The name of the MCP tool" }), + "server_name": Schema.String.annotate({ "title": "Server Name", "description": "The name of the MCP server" }), + "type": Schema.Literal("mcp_tool_use").annotate({ "title": "Type", "default": "mcp_tool_use" }) +}).annotate({ "title": "ResponseMCPToolUseBlock" }) +export type BetaResponsePageLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_page_number": number + readonly "file_id": string | null + readonly "start_page_number": number + readonly "type": "page_location" +} +export const BetaResponsePageLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Document Title" }), + "end_page_number": Schema.Number.annotate({ "title": "End Page Number" }).check(Schema.isInt()), + "file_id": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "File Id", "default": null }), + "start_page_number": Schema.Number.annotate({ "title": "Start Page Number" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(1) + ), + "type": Schema.Literal("page_location").annotate({ "title": "Type", "default": "page_location" }) +}).annotate({ "title": "ResponsePageLocationCitation" }) +export type BetaResponseRedactedThinkingBlock = { readonly "data": string; readonly "type": "redacted_thinking" } +export const BetaResponseRedactedThinkingBlock = Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data" }), + "type": Schema.Literal("redacted_thinking").annotate({ "title": "Type", "default": "redacted_thinking" }) +}).annotate({ "title": "ResponseRedactedThinkingBlock" }) +export type BetaResponseSearchResultLocationCitation = { + readonly "cited_text": string + readonly "end_block_index": number + readonly "search_result_index": number + readonly "source": string + readonly "start_block_index": number + readonly "title": string | null + readonly "type": "search_result_location" +} +export const BetaResponseSearchResultLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "end_block_index": Schema.Number.annotate({ "title": "End Block Index" }).check(Schema.isInt()), + "search_result_index": Schema.Number.annotate({ "title": "Search Result Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "source": Schema.String.annotate({ "title": "Source" }), + "start_block_index": Schema.Number.annotate({ "title": "Start Block Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Title" }), + "type": Schema.Literal("search_result_location").annotate({ "title": "Type", "default": "search_result_location" }) +}).annotate({ "title": "ResponseSearchResultLocationCitation" }) +export type BetaResponseTextEditorCodeExecutionCreateResultBlock = { + readonly "is_file_update": boolean + readonly "type": "text_editor_code_execution_create_result" +} +export const BetaResponseTextEditorCodeExecutionCreateResultBlock = Schema.Struct({ + "is_file_update": Schema.Boolean.annotate({ "title": "Is File Update" }), + "type": Schema.Literal("text_editor_code_execution_create_result").annotate({ + "title": "Type", + "default": "text_editor_code_execution_create_result" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionCreateResultBlock" }) +export type BetaResponseTextEditorCodeExecutionStrReplaceResultBlock = { + readonly "lines": ReadonlyArray | null + readonly "new_lines": number | null + readonly "new_start": number | null + readonly "old_lines": number | null + readonly "old_start": number | null + readonly "type": "text_editor_code_execution_str_replace_result" +} +export const BetaResponseTextEditorCodeExecutionStrReplaceResultBlock = Schema.Struct({ + "lines": Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ "title": "Lines", "default": null }), + "new_lines": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "New Lines", + "default": null + }), + "new_start": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "New Start", + "default": null + }), + "old_lines": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Old Lines", + "default": null + }), + "old_start": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Old Start", + "default": null + }), + "type": Schema.Literal("text_editor_code_execution_str_replace_result").annotate({ + "title": "Type", + "default": "text_editor_code_execution_str_replace_result" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionStrReplaceResultBlock" }) +export type BetaResponseTextEditorCodeExecutionViewResultBlock = { + readonly "content": string + readonly "file_type": "text" | "image" | "pdf" + readonly "num_lines": number | null + readonly "start_line": number | null + readonly "total_lines": number | null + readonly "type": "text_editor_code_execution_view_result" +} +export const BetaResponseTextEditorCodeExecutionViewResultBlock = Schema.Struct({ + "content": Schema.String.annotate({ "title": "Content" }), + "file_type": Schema.Literals(["text", "image", "pdf"]).annotate({ "title": "File Type" }), + "num_lines": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Num Lines", + "default": null + }), + "start_line": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Start Line", + "default": null + }), + "total_lines": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Total Lines", + "default": null + }), + "type": Schema.Literal("text_editor_code_execution_view_result").annotate({ + "title": "Type", + "default": "text_editor_code_execution_view_result" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionViewResultBlock" }) +export type BetaResponseThinkingBlock = { + readonly "signature": string + readonly "thinking": string + readonly "type": "thinking" +} +export const BetaResponseThinkingBlock = Schema.Struct({ + "signature": Schema.String.annotate({ "title": "Signature" }), + "thinking": Schema.String.annotate({ "title": "Thinking" }), + "type": Schema.Literal("thinking").annotate({ "title": "Type", "default": "thinking" }) +}).annotate({ "title": "ResponseThinkingBlock" }) +export type BetaResponseToolReferenceBlock = { readonly "tool_name": string; readonly "type": "tool_reference" } +export const BetaResponseToolReferenceBlock = Schema.Struct({ + "tool_name": Schema.String.annotate({ "title": "Tool Name" }).check(Schema.isMinLength(1)).check( + Schema.isMaxLength(256) + ).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]{1,256}$"))), + "type": Schema.Literal("tool_reference").annotate({ "title": "Type", "default": "tool_reference" }) +}).annotate({ "title": "ResponseToolReferenceBlock" }) +export type BetaResponseWebSearchResultBlock = { + readonly "encrypted_content": string + readonly "page_age": string | null + readonly "title": string + readonly "type": "web_search_result" + readonly "url": string +} +export const BetaResponseWebSearchResultBlock = Schema.Struct({ + "encrypted_content": Schema.String.annotate({ "title": "Encrypted Content" }), + "page_age": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Page Age", "default": null }), + "title": Schema.String.annotate({ "title": "Title" }), + "type": Schema.Literal("web_search_result").annotate({ "title": "Type", "default": "web_search_result" }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "ResponseWebSearchResultBlock" }) +export type BetaResponseWebSearchResultLocationCitation = { + readonly "cited_text": string + readonly "encrypted_index": string + readonly "title": string | null + readonly "type": "web_search_result_location" + readonly "url": string +} +export const BetaResponseWebSearchResultLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "encrypted_index": Schema.String.annotate({ "title": "Encrypted Index" }), + "title": Schema.Union([Schema.String.check(Schema.isMaxLength(512)), Schema.Null]).annotate({ "title": "Title" }), + "type": Schema.Literal("web_search_result_location").annotate({ + "title": "Type", + "default": "web_search_result_location" + }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "ResponseWebSearchResultLocationCitation" }) +export type BetaServerToolCaller = { readonly "tool_id": string; readonly "type": "code_execution_20250825" } +export const BetaServerToolCaller = Schema.Struct({ + "tool_id": Schema.String.annotate({ "title": "Tool Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("code_execution_20250825").annotate({ "title": "Type" }) +}).annotate({ "title": "ServerToolCaller", "description": "Tool invocation generated by a server-side tool." }) +export type BetaServerToolCaller_20260120 = { readonly "tool_id": string; readonly "type": "code_execution_20260120" } +export const BetaServerToolCaller_20260120 = Schema.Struct({ + "tool_id": Schema.String.annotate({ "title": "Tool Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("code_execution_20260120").annotate({ "title": "Type" }) +}).annotate({ "title": "ServerToolCaller_20260120" }) +export type BetaServerToolUsage = { readonly "web_fetch_requests": number; readonly "web_search_requests": number } +export const BetaServerToolUsage = Schema.Struct({ + "web_fetch_requests": Schema.Number.annotate({ + "title": "Web Fetch Requests", + "description": "The number of web fetch tool requests.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "web_search_requests": Schema.Number.annotate({ + "title": "Web Search Requests", + "description": "The number of web search tool requests.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) +}).annotate({ "title": "ServerToolUsage" }) +export type BetaSignatureContentBlockDelta = { readonly "signature": string; readonly "type": "signature_delta" } +export const BetaSignatureContentBlockDelta = Schema.Struct({ + "signature": Schema.String.annotate({ "title": "Signature" }), + "type": Schema.Literal("signature_delta").annotate({ "title": "Type", "default": "signature_delta" }) +}).annotate({ "title": "SignatureContentBlockDelta" }) +export type BetaSkill = { + readonly "skill_id": string + readonly "type": "anthropic" | "custom" + readonly "version": string +} +export const BetaSkill = Schema.Struct({ + "skill_id": Schema.String.annotate({ "title": "Skill Id", "description": "Skill ID" }).check(Schema.isMinLength(1)) + .check(Schema.isMaxLength(64)), + "type": Schema.Literals(["anthropic", "custom"]).annotate({ + "title": "Type", + "description": "Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)" + }), + "version": Schema.String.annotate({ + "title": "Version", + "description": "Skill version or 'latest' for most recent version" + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)) +}).annotate({ "title": "Skill", "description": "A skill that was loaded in a container (response model)." }) +export type BetaSkillParams = { + readonly "skill_id": string + readonly "type": "anthropic" | "custom" + readonly "version"?: string +} +export const BetaSkillParams = Schema.Struct({ + "skill_id": Schema.String.annotate({ "title": "Skill Id", "description": "Skill ID" }).check(Schema.isMinLength(1)) + .check(Schema.isMaxLength(64)), + "type": Schema.Literals(["anthropic", "custom"]).annotate({ + "title": "Type", + "description": "Type of skill - either 'anthropic' (built-in) or 'custom' (user-defined)" + }), + "version": Schema.optionalKey( + Schema.String.annotate({ "title": "Version", "description": "Skill version or 'latest' for most recent version" }) + .check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)) + ) +}).annotate({ + "title": "SkillParams", + "description": "Specification for a skill to be loaded in a container (request model)." +}) +export type BetaSkillVersion = { + readonly "created_at": string + readonly "description": string + readonly "directory": string + readonly "id": string + readonly "name": string + readonly "skill_id": string + readonly "type": string + readonly "version": string +} +export const BetaSkillVersion = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill version was created." + }), + "description": Schema.String.annotate({ + "title": "Description", + "description": "Description of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "directory": Schema.String.annotate({ + "title": "Directory", + "description": + "Directory name of the skill version.\n\nThis is the top-level directory name that was extracted from the uploaded files." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill version.\n\nThe format and length of IDs may change over time." + }), + "name": Schema.String.annotate({ + "title": "Name", + "description": + "Human-readable name of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "skill_id": Schema.String.annotate({ + "title": "Skill Id", + "description": "Identifier for the skill that this version belongs to." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skill Versions, this is always `\"skill_version\"`.", + "default": "skill_version" + }), + "version": Schema.String.annotate({ + "title": "Version", + "description": + "Version identifier for the skill.\n\nEach version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\")." + }) +}).annotate({ "title": "SkillVersion" }) +export type BetaSpeed = "standard" | "fast" +export const BetaSpeed = Schema.Literals(["standard", "fast"]).annotate({ "title": "Speed" }) +export type BetaTextContentBlockDelta = { readonly "text": string; readonly "type": "text_delta" } +export const BetaTextContentBlockDelta = Schema.Struct({ + "text": Schema.String.annotate({ "title": "Text" }), + "type": Schema.Literal("text_delta").annotate({ "title": "Type", "default": "text_delta" }) +}).annotate({ "title": "TextContentBlockDelta" }) +export type BetaTextEditorCodeExecutionToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "too_many_requests" + | "execution_time_exceeded" + | "file_not_found" +export const BetaTextEditorCodeExecutionToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "too_many_requests", + "execution_time_exceeded", + "file_not_found" +]).annotate({ "title": "TextEditorCodeExecutionToolResultErrorCode" }) +export type BetaThinkingConfigAdaptive = { readonly "type": "adaptive" } +export const BetaThinkingConfigAdaptive = Schema.Struct({ + "type": Schema.Literal("adaptive").annotate({ "title": "Type" }) +}).annotate({ "title": "ThinkingConfigAdaptive" }) +export type BetaThinkingConfigDisabled = { readonly "type": "disabled" } +export const BetaThinkingConfigDisabled = Schema.Struct({ + "type": Schema.Literal("disabled").annotate({ "title": "Type" }) +}).annotate({ "title": "ThinkingConfigDisabled" }) +export type BetaThinkingConfigEnabled = { readonly "budget_tokens": number; readonly "type": "enabled" } +export const BetaThinkingConfigEnabled = Schema.Struct({ + "budget_tokens": Schema.Number.annotate({ + "title": "Budget Tokens", + "description": + "Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality.\n\nMust be ≥1024 and less than `max_tokens`.\n\nSee [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1024)), + "type": Schema.Literal("enabled").annotate({ "title": "Type" }) +}).annotate({ "title": "ThinkingConfigEnabled" }) +export type BetaThinkingContentBlockDelta = { readonly "thinking": string; readonly "type": "thinking_delta" } +export const BetaThinkingContentBlockDelta = Schema.Struct({ + "thinking": Schema.String.annotate({ "title": "Thinking" }), + "type": Schema.Literal("thinking_delta").annotate({ "title": "Type", "default": "thinking_delta" }) +}).annotate({ "title": "ThinkingContentBlockDelta" }) +export type BetaThinkingTurns = { readonly "type": "thinking_turns"; readonly "value": number } +export const BetaThinkingTurns = Schema.Struct({ + "type": Schema.Literal("thinking_turns").annotate({ "title": "Type" }), + "value": Schema.Number.annotate({ "title": "Value" }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)) +}).annotate({ "title": "ThinkingTurns" }) +export type BetaToolChoiceAny = { readonly "disable_parallel_tool_use"?: boolean; readonly "type": "any" } +export const BetaToolChoiceAny = Schema.Struct({ + "disable_parallel_tool_use": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Disable Parallel Tool Use", + "description": + "Whether to disable parallel tool use.\n\nDefaults to `false`. If set to `true`, the model will output exactly one tool use." + }) + ), + "type": Schema.Literal("any").annotate({ "title": "Type" }) +}).annotate({ "title": "ToolChoiceAny", "description": "The model will use any available tools." }) +export type BetaToolChoiceAuto = { readonly "disable_parallel_tool_use"?: boolean; readonly "type": "auto" } +export const BetaToolChoiceAuto = Schema.Struct({ + "disable_parallel_tool_use": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Disable Parallel Tool Use", + "description": + "Whether to disable parallel tool use.\n\nDefaults to `false`. If set to `true`, the model will output at most one tool use." + }) + ), + "type": Schema.Literal("auto").annotate({ "title": "Type" }) +}).annotate({ "title": "ToolChoiceAuto", "description": "The model will automatically decide whether to use tools." }) +export type BetaToolChoiceNone = { readonly "type": "none" } +export const BetaToolChoiceNone = Schema.Struct({ "type": Schema.Literal("none").annotate({ "title": "Type" }) }) + .annotate({ "title": "ToolChoiceNone", "description": "The model will not be allowed to use tools." }) +export type BetaToolChoiceTool = { + readonly "disable_parallel_tool_use"?: boolean + readonly "name": string + readonly "type": "tool" +} +export const BetaToolChoiceTool = Schema.Struct({ + "disable_parallel_tool_use": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Disable Parallel Tool Use", + "description": + "Whether to disable parallel tool use.\n\nDefaults to `false`. If set to `true`, the model will output exactly one tool use." + }) + ), + "name": Schema.String.annotate({ "title": "Name", "description": "The name of the tool to use." }), + "type": Schema.Literal("tool").annotate({ "title": "Type" }) +}).annotate({ + "title": "ToolChoiceTool", + "description": "The model will use the specified tool with `tool_choice.name`." +}) +export type BetaToolSearchToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "too_many_requests" + | "execution_time_exceeded" +export const BetaToolSearchToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "too_many_requests", + "execution_time_exceeded" +]).annotate({ "title": "ToolSearchToolResultErrorCode" }) +export type BetaToolUsesKeep = { readonly "type": "tool_uses"; readonly "value": number } +export const BetaToolUsesKeep = Schema.Struct({ + "type": Schema.Literal("tool_uses").annotate({ "title": "Type" }), + "value": Schema.Number.annotate({ "title": "Value" }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) +}).annotate({ "title": "ToolUsesKeep" }) +export type BetaToolUsesTrigger = { readonly "type": "tool_uses"; readonly "value": number } +export const BetaToolUsesTrigger = Schema.Struct({ + "type": Schema.Literal("tool_uses").annotate({ "title": "Type" }), + "value": Schema.Number.annotate({ "title": "Value" }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)) +}).annotate({ "title": "ToolUsesTrigger" }) +export type BetaURLImageSource = { readonly "type": "url"; readonly "url": string } +export const BetaURLImageSource = Schema.Struct({ + "type": Schema.Literal("url").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "URLImageSource" }) +export type BetaURLPDFSource = { readonly "type": "url"; readonly "url": string } +export const BetaURLPDFSource = Schema.Struct({ + "type": Schema.Literal("url").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "URLPDFSource" }) +export type BetaUserLocation = { + readonly "city"?: string | null + readonly "country"?: string | null + readonly "region"?: string | null + readonly "timezone"?: string | null + readonly "type": "approximate" +} +export const BetaUserLocation = Schema.Struct({ + "city": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), Schema.Null]).annotate({ + "title": "City", + "description": "The city of the user." + }) + ), + "country": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(2)).check(Schema.isMaxLength(2)), Schema.Null]).annotate({ + "title": "Country", + "description": "The two letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the user." + }) + ), + "region": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), Schema.Null]).annotate({ + "title": "Region", + "description": "The region of the user." + }) + ), + "timezone": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), Schema.Null]).annotate({ + "title": "Timezone", + "description": "The [IANA timezone](https://nodatime.org/TimeZones) of the user." + }) + ), + "type": Schema.Literal("approximate").annotate({ "title": "Type" }) +}).annotate({ "title": "UserLocation" }) +export type BetaWebFetchToolResultErrorCode = + | "invalid_tool_input" + | "url_too_long" + | "url_not_allowed" + | "url_not_accessible" + | "unsupported_content_type" + | "too_many_requests" + | "max_uses_exceeded" + | "unavailable" +export const BetaWebFetchToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "url_too_long", + "url_not_allowed", + "url_not_accessible", + "unsupported_content_type", + "too_many_requests", + "max_uses_exceeded", + "unavailable" +]).annotate({ "title": "WebFetchToolResultErrorCode" }) +export type BetaWebSearchToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "max_uses_exceeded" + | "too_many_requests" + | "query_too_long" + | "request_too_large" +export const BetaWebSearchToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "max_uses_exceeded", + "too_many_requests", + "query_too_long", + "request_too_large" +]).annotate({ "title": "WebSearchToolResultErrorCode" }) +export type Betaapi__schemas__skills__Skill = { + readonly "created_at": string + readonly "display_title": string | null + readonly "id": string + readonly "latest_version": string | null + readonly "source": string + readonly "type": string + readonly "updated_at": string +} +export const Betaapi__schemas__skills__Skill = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill was created." + }), + "display_title": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Display Title", + "description": + "Display title for the skill.\n\nThis is a human-readable label that is not included in the prompt sent to the model." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill.\n\nThe format and length of IDs may change over time." + }), + "latest_version": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Latest Version", + "description": + "The latest version identifier for the skill.\n\nThis represents the most recent version of the skill that has been created." + }), + "source": Schema.String.annotate({ + "title": "Source", + "description": + "Source of the skill.\n\nThis may be one of the following values:\n* `\"custom\"`: the skill was created by a user\n* `\"anthropic\"`: the skill was created by Anthropic" + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skills, this is always `\"skill\"`.", + "default": "skill" + }), + "updated_at": Schema.String.annotate({ + "title": "Updated At", + "description": "ISO 8601 timestamp of when the skill was last updated." + }) +}).annotate({ "title": "Skill" }) +export type BillingError = { readonly "message": string; readonly "type": "billing_error" } +export const BillingError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Billing error" }), + "type": Schema.Literal("billing_error").annotate({ "title": "Type", "default": "billing_error" }) +}).annotate({ "title": "BillingError" }) +export type Body_create_skill_v1_skills_post = { + readonly "display_title"?: string | null + readonly "files"?: ReadonlyArray | null +} +export const Body_create_skill_v1_skills_post = Schema.Struct({ + "display_title": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Display Title", + "description": + "Display title for the skill.\n\nThis is a human-readable label that is not included in the prompt sent to the model." + }) + ), + "files": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String.annotate({ "format": "binary" })), Schema.Null]).annotate({ + "title": "Files", + "description": + "Files to upload for the skill.\n\nAll files must be in the same top-level directory and must include a SKILL.md file at the root of that directory." + }) + ) +}).annotate({ "title": "Body_create_skill_v1_skills_post" }) +export type Body_create_skill_version_v1_skills__skill_id__versions_post = { + readonly "files"?: ReadonlyArray | null +} +export const Body_create_skill_version_v1_skills__skill_id__versions_post = Schema.Struct({ + "files": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String.annotate({ "format": "binary" })), Schema.Null]).annotate({ + "title": "Files", + "description": + "Files to upload for the skill.\n\nAll files must be in the same top-level directory and must include a SKILL.md file at the root of that directory." + }) + ) +}).annotate({ "title": "Body_create_skill_version_v1_skills__skill_id__versions_post" }) +export type CacheControlEphemeral = { readonly "ttl"?: "5m" | "1h"; readonly "type": "ephemeral" } +export const CacheControlEphemeral = Schema.Struct({ + "ttl": Schema.optionalKey( + Schema.Literals(["5m", "1h"]).annotate({ + "title": "Ttl", + "description": + "The time-to-live for the cache control breakpoint.\n\nThis may be one the following values:\n- `5m`: 5 minutes\n- `1h`: 1 hour\n\nDefaults to `5m`." + }) + ), + "type": Schema.Literal("ephemeral").annotate({ "title": "Type" }) +}).annotate({ "title": "CacheControlEphemeral" }) +export type CacheCreation = { + readonly "ephemeral_1h_input_tokens": number + readonly "ephemeral_5m_input_tokens": number +} +export const CacheCreation = Schema.Struct({ + "ephemeral_1h_input_tokens": Schema.Number.annotate({ + "title": "Ephemeral 1H Input Tokens", + "description": "The number of input tokens used to create the 1 hour cache entry.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "ephemeral_5m_input_tokens": Schema.Number.annotate({ + "title": "Ephemeral 5M Input Tokens", + "description": "The number of input tokens used to create the 5 minute cache entry.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) +}).annotate({ "title": "CacheCreation" }) +export type CanceledResult = { readonly "type": "canceled" } +export const CanceledResult = Schema.Struct({ + "type": Schema.Literal("canceled").annotate({ "title": "Type", "default": "canceled" }) +}).annotate({ "title": "CanceledResult" }) +export type CodeExecutionToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "too_many_requests" + | "execution_time_exceeded" +export const CodeExecutionToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "too_many_requests", + "execution_time_exceeded" +]).annotate({ "title": "CodeExecutionToolResultErrorCode" }) +export type Container = { readonly "expires_at": string; readonly "id": string } +export const Container = Schema.Struct({ + "expires_at": Schema.String.annotate({ + "title": "Expires At", + "description": "The time at which the container will expire.", + "format": "date-time" + }), + "id": Schema.String.annotate({ "title": "Id", "description": "Identifier for the container used in this request" }) +}).annotate({ + "title": "Container", + "description": "Information about the container used in the request (for the code execution tool)" +}) +export type ContentBlockStopEvent = { readonly "index": number; readonly "type": "content_block_stop" } +export const ContentBlockStopEvent = Schema.Struct({ + "index": Schema.Number.annotate({ "title": "Index" }).check(Schema.isInt()), + "type": Schema.Literal("content_block_stop").annotate({ "title": "Type", "default": "content_block_stop" }) +}).annotate({ "title": "ContentBlockStopEvent" }) +export type CountMessageTokensResponse = { readonly "input_tokens": number } +export const CountMessageTokensResponse = Schema.Struct({ + "input_tokens": Schema.Number.annotate({ + "title": "Input Tokens", + "description": "The total number of tokens across the provided list of messages, system prompt, and tools." + }).check(Schema.isInt()) +}).annotate({ "title": "CountMessageTokensResponse" }) +export type CreateSkillResponse = { + readonly "created_at": string + readonly "display_title": string | null + readonly "id": string + readonly "latest_version": string | null + readonly "source": string + readonly "type": string + readonly "updated_at": string +} +export const CreateSkillResponse = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill was created." + }), + "display_title": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Display Title", + "description": + "Display title for the skill.\n\nThis is a human-readable label that is not included in the prompt sent to the model." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill.\n\nThe format and length of IDs may change over time." + }), + "latest_version": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Latest Version", + "description": + "The latest version identifier for the skill.\n\nThis represents the most recent version of the skill that has been created." + }), + "source": Schema.String.annotate({ + "title": "Source", + "description": + "Source of the skill.\n\nThis may be one of the following values:\n* `\"custom\"`: the skill was created by a user\n* `\"anthropic\"`: the skill was created by Anthropic" + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skills, this is always `\"skill\"`.", + "default": "skill" + }), + "updated_at": Schema.String.annotate({ + "title": "Updated At", + "description": "ISO 8601 timestamp of when the skill was last updated." + }) +}).annotate({ "title": "CreateSkillResponse" }) +export type CreateSkillVersionResponse = { + readonly "created_at": string + readonly "description": string + readonly "directory": string + readonly "id": string + readonly "name": string + readonly "skill_id": string + readonly "type": string + readonly "version": string +} +export const CreateSkillVersionResponse = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill version was created." + }), + "description": Schema.String.annotate({ + "title": "Description", + "description": "Description of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "directory": Schema.String.annotate({ + "title": "Directory", + "description": + "Directory name of the skill version.\n\nThis is the top-level directory name that was extracted from the uploaded files." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill version.\n\nThe format and length of IDs may change over time." + }), + "name": Schema.String.annotate({ + "title": "Name", + "description": + "Human-readable name of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "skill_id": Schema.String.annotate({ + "title": "Skill Id", + "description": "Identifier for the skill that this version belongs to." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skill Versions, this is always `\"skill_version\"`.", + "default": "skill_version" + }), + "version": Schema.String.annotate({ + "title": "Version", + "description": + "Version identifier for the skill.\n\nEach version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\")." + }) +}).annotate({ "title": "CreateSkillVersionResponse" }) +export type DeleteMessageBatchResponse = { readonly "id": string; readonly "type": "message_batch_deleted" } +export const DeleteMessageBatchResponse = Schema.Struct({ + "id": Schema.String.annotate({ "title": "Id", "description": "ID of the Message Batch." }), + "type": Schema.Literal("message_batch_deleted").annotate({ + "title": "Type", + "description": "Deleted object type.\n\nFor Message Batches, this is always `\"message_batch_deleted\"`.", + "default": "message_batch_deleted" + }) +}).annotate({ "title": "DeleteMessageBatchResponse" }) +export type DeleteSkillResponse = { readonly "id": string; readonly "type": string } +export const DeleteSkillResponse = Schema.Struct({ + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill.\n\nThe format and length of IDs may change over time." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Deleted object type.\n\nFor Skills, this is always `\"skill_deleted\"`.", + "default": "skill_deleted" + }) +}).annotate({ "title": "DeleteSkillResponse" }) +export type DeleteSkillVersionResponse = { readonly "id": string; readonly "type": string } +export const DeleteSkillVersionResponse = Schema.Struct({ + "id": Schema.String.annotate({ + "title": "Id", + "description": + "Version identifier for the skill.\n\nEach version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\")." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Deleted object type.\n\nFor Skill Versions, this is always `\"skill_version_deleted\"`.", + "default": "skill_version_deleted" + }) +}).annotate({ "title": "DeleteSkillVersionResponse" }) +export type DirectCaller = { readonly "type": "direct" } +export const DirectCaller = Schema.Struct({ "type": Schema.Literal("direct").annotate({ "title": "Type" }) }).annotate({ + "title": "DirectCaller", + "description": "Tool invocation directly from the model." +}) +export type EffortLevel = "low" | "medium" | "high" | "max" +export const EffortLevel = Schema.Literals(["low", "medium", "high", "max"]).annotate({ + "title": "EffortLevel", + "description": "All possible effort levels." +}) +export type ExpiredResult = { readonly "type": "expired" } +export const ExpiredResult = Schema.Struct({ + "type": Schema.Literal("expired").annotate({ "title": "Type", "default": "expired" }) +}).annotate({ "title": "ExpiredResult" }) +export type FileDeleteResponse = { readonly "id": string; readonly "type"?: "file_deleted" } +export const FileDeleteResponse = Schema.Struct({ + "id": Schema.String.annotate({ "title": "Id", "description": "ID of the deleted file." }), + "type": Schema.optionalKey( + Schema.Literal("file_deleted").annotate({ + "title": "Type", + "description": "Deleted object type.\n\nFor file deletion, this is always `\"file_deleted\"`.", + "default": "file_deleted" + }) + ) +}).annotate({ "title": "FileDeleteResponse" }) +export type FileMetadataSchema = { + readonly "created_at": string + readonly "downloadable"?: boolean + readonly "filename": string + readonly "id": string + readonly "mime_type": string + readonly "size_bytes": number + readonly "type": "file" +} +export const FileMetadataSchema = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "RFC 3339 datetime string representing when the file was created.", + "format": "date-time" + }), + "downloadable": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Downloadable", + "description": "Whether the file can be downloaded.", + "default": false + }) + ), + "filename": Schema.String.annotate({ "title": "Filename", "description": "Original filename of the uploaded file." }) + .check(Schema.isMinLength(1)).check(Schema.isMaxLength(500)), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique object identifier.\n\nThe format and length of IDs may change over time." + }), + "mime_type": Schema.String.annotate({ "title": "Mime Type", "description": "MIME type of the file." }).check( + Schema.isMinLength(1) + ).check(Schema.isMaxLength(255)), + "size_bytes": Schema.Number.annotate({ "title": "Size Bytes", "description": "Size of the file in bytes." }).check( + Schema.isInt() + ).check(Schema.isGreaterThanOrEqualTo(0)), + "type": Schema.Literal("file").annotate({ + "title": "Type", + "description": "Object type.\n\nFor files, this is always `\"file\"`." + }) +}).annotate({ "title": "FileMetadataSchema" }) +export type GatewayTimeoutError = { readonly "message": string; readonly "type": "timeout_error" } +export const GatewayTimeoutError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Request timeout" }), + "type": Schema.Literal("timeout_error").annotate({ "title": "Type", "default": "timeout_error" }) +}).annotate({ "title": "GatewayTimeoutError" }) +export type GetSkillResponse = { + readonly "created_at": string + readonly "display_title": string | null + readonly "id": string + readonly "latest_version": string | null + readonly "source": string + readonly "type": string + readonly "updated_at": string +} +export const GetSkillResponse = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill was created." + }), + "display_title": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Display Title", + "description": + "Display title for the skill.\n\nThis is a human-readable label that is not included in the prompt sent to the model." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill.\n\nThe format and length of IDs may change over time." + }), + "latest_version": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Latest Version", + "description": + "The latest version identifier for the skill.\n\nThis represents the most recent version of the skill that has been created." + }), + "source": Schema.String.annotate({ + "title": "Source", + "description": + "Source of the skill.\n\nThis may be one of the following values:\n* `\"custom\"`: the skill was created by a user\n* `\"anthropic\"`: the skill was created by Anthropic" + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skills, this is always `\"skill\"`.", + "default": "skill" + }), + "updated_at": Schema.String.annotate({ + "title": "Updated At", + "description": "ISO 8601 timestamp of when the skill was last updated." + }) +}).annotate({ "title": "GetSkillResponse" }) +export type GetSkillVersionResponse = { + readonly "created_at": string + readonly "description": string + readonly "directory": string + readonly "id": string + readonly "name": string + readonly "skill_id": string + readonly "type": string + readonly "version": string +} +export const GetSkillVersionResponse = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill version was created." + }), + "description": Schema.String.annotate({ + "title": "Description", + "description": "Description of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "directory": Schema.String.annotate({ + "title": "Directory", + "description": + "Directory name of the skill version.\n\nThis is the top-level directory name that was extracted from the uploaded files." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill version.\n\nThe format and length of IDs may change over time." + }), + "name": Schema.String.annotate({ + "title": "Name", + "description": + "Human-readable name of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "skill_id": Schema.String.annotate({ + "title": "Skill Id", + "description": "Identifier for the skill that this version belongs to." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skill Versions, this is always `\"skill_version\"`.", + "default": "skill_version" + }), + "version": Schema.String.annotate({ + "title": "Version", + "description": + "Version identifier for the skill.\n\nEach version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\")." + }) +}).annotate({ "title": "GetSkillVersionResponse" }) +export type InputJsonContentBlockDelta = { readonly "partial_json": string; readonly "type": "input_json_delta" } +export const InputJsonContentBlockDelta = Schema.Struct({ + "partial_json": Schema.String.annotate({ "title": "Partial Json" }), + "type": Schema.Literal("input_json_delta").annotate({ "title": "Type", "default": "input_json_delta" }) +}).annotate({ "title": "InputJsonContentBlockDelta" }) +export type InvalidRequestError = { readonly "message": string; readonly "type": "invalid_request_error" } +export const InvalidRequestError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Invalid request" }), + "type": Schema.Literal("invalid_request_error").annotate({ "title": "Type", "default": "invalid_request_error" }) +}).annotate({ "title": "InvalidRequestError" }) +export type JsonOutputFormat = { + readonly "schema": { readonly [x: string]: Schema.Json } + readonly "type": "json_schema" +} +export const JsonOutputFormat = Schema.Struct({ + "schema": Schema.Record(Schema.String, Schema.Json).annotate({ + "title": "Schema", + "description": "The JSON schema of the format" + }), + "type": Schema.Literal("json_schema").annotate({ "title": "Type" }) +}).annotate({ "title": "JsonOutputFormat" }) +export type JsonValue = unknown +export const JsonValue = Schema.Unknown +export type MessageBatch = { + readonly "archived_at": string | null + readonly "cancel_initiated_at": string | null + readonly "created_at": string + readonly "ended_at": string | null + readonly "expires_at": string + readonly "id": string + readonly "processing_status": "in_progress" | "canceling" | "ended" + readonly "request_counts": { + readonly "canceled": number + readonly "errored": number + readonly "expired": number + readonly "processing": number + readonly "succeeded": number + } + readonly "results_url": string | null + readonly "type": "message_batch" +} +export const MessageBatch = Schema.Struct({ + "archived_at": Schema.Union([Schema.String.annotate({ "format": "date-time" }), Schema.Null]).annotate({ + "title": "Archived At", + "description": + "RFC 3339 datetime string representing the time at which the Message Batch was archived and its results became unavailable." + }), + "cancel_initiated_at": Schema.Union([Schema.String.annotate({ "format": "date-time" }), Schema.Null]).annotate({ + "title": "Cancel Initiated At", + "description": + "RFC 3339 datetime string representing the time at which cancellation was initiated for the Message Batch. Specified only if cancellation was initiated." + }), + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "RFC 3339 datetime string representing the time at which the Message Batch was created.", + "format": "date-time" + }), + "ended_at": Schema.Union([Schema.String.annotate({ "format": "date-time" }), Schema.Null]).annotate({ + "title": "Ended At", + "description": + "RFC 3339 datetime string representing the time at which processing for the Message Batch ended. Specified only once processing ends.\n\nProcessing ends when every request in a Message Batch has either succeeded, errored, canceled, or expired." + }), + "expires_at": Schema.String.annotate({ + "title": "Expires At", + "description": + "RFC 3339 datetime string representing the time at which the Message Batch will expire and end processing, which is 24 hours after creation.", + "format": "date-time" + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique object identifier.\n\nThe format and length of IDs may change over time." + }), + "processing_status": Schema.Literals(["in_progress", "canceling", "ended"]).annotate({ + "title": "Processing Status", + "description": "Processing status of the Message Batch." + }), + "request_counts": Schema.Struct({ + "canceled": Schema.Number.annotate({ + "title": "Canceled", + "description": + "Number of requests in the Message Batch that have been canceled.\n\nThis is zero until processing of the entire Message Batch has ended.", + "default": 0 + }).check(Schema.isInt()), + "errored": Schema.Number.annotate({ + "title": "Errored", + "description": + "Number of requests in the Message Batch that encountered an error.\n\nThis is zero until processing of the entire Message Batch has ended.", + "default": 0 + }).check(Schema.isInt()), + "expired": Schema.Number.annotate({ + "title": "Expired", + "description": + "Number of requests in the Message Batch that have expired.\n\nThis is zero until processing of the entire Message Batch has ended.", + "default": 0 + }).check(Schema.isInt()), + "processing": Schema.Number.annotate({ + "title": "Processing", + "description": "Number of requests in the Message Batch that are processing.", + "default": 0 + }).check(Schema.isInt()), + "succeeded": Schema.Number.annotate({ + "title": "Succeeded", + "description": + "Number of requests in the Message Batch that have completed successfully.\n\nThis is zero until processing of the entire Message Batch has ended.", + "default": 0 + }).check(Schema.isInt()) + }).annotate({ + "title": "RequestCounts", + "description": + "Tallies requests within the Message Batch, categorized by their status.\n\nRequests start as `processing` and move to one of the other statuses only once processing of the entire batch ends. The sum of all values always matches the total number of requests in the batch." + }), + "results_url": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Results Url", + "description": + "URL to a `.jsonl` file containing the results of the Message Batch requests. Specified only once processing ends.\n\nResults in the file are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests." + }), + "type": Schema.Literal("message_batch").annotate({ + "title": "Type", + "description": "Object type.\n\nFor Message Batches, this is always `\"message_batch\"`.", + "default": "message_batch" + }) +}).annotate({ "title": "MessageBatch" }) +export type MessageStopEvent = { readonly "type": "message_stop" } +export const MessageStopEvent = Schema.Struct({ + "type": Schema.Literal("message_stop").annotate({ "title": "Type", "default": "message_stop" }) +}).annotate({ "title": "MessageStopEvent" }) +export type ModelInfo = { + readonly "created_at": string + readonly "display_name": string + readonly "id": string + readonly "type": "model" +} +export const ModelInfo = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": + "RFC 3339 datetime string representing the time at which the model was released. May be set to an epoch value if the release date is unknown.", + "format": "date-time" + }), + "display_name": Schema.String.annotate({ + "title": "Display Name", + "description": "A human-readable name for the model." + }), + "id": Schema.String.annotate({ "title": "Id", "description": "Unique model identifier." }), + "type": Schema.Literal("model").annotate({ + "title": "Type", + "description": "Object type.\n\nFor Models, this is always `\"model\"`.", + "default": "model" + }) +}).annotate({ "title": "ModelInfo" }) +export type NotFoundError = { readonly "message": string; readonly "type": "not_found_error" } +export const NotFoundError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Not found" }), + "type": Schema.Literal("not_found_error").annotate({ "title": "Type", "default": "not_found_error" }) +}).annotate({ "title": "NotFoundError" }) +export type OverloadedError = { readonly "message": string; readonly "type": "overloaded_error" } +export const OverloadedError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Overloaded" }), + "type": Schema.Literal("overloaded_error").annotate({ "title": "Type", "default": "overloaded_error" }) +}).annotate({ "title": "OverloadedError" }) +export type PermissionError = { readonly "message": string; readonly "type": "permission_error" } +export const PermissionError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Permission denied" }), + "type": Schema.Literal("permission_error").annotate({ "title": "Type", "default": "permission_error" }) +}).annotate({ "title": "PermissionError" }) +export type PlainTextSource = { readonly "data": string; readonly "media_type": "text/plain"; readonly "type": "text" } +export const PlainTextSource = Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data" }), + "media_type": Schema.Literal("text/plain").annotate({ "title": "Media Type" }), + "type": Schema.Literal("text").annotate({ "title": "Type" }) +}).annotate({ "title": "PlainTextSource" }) +export type RateLimitError = { readonly "message": string; readonly "type": "rate_limit_error" } +export const RateLimitError = Schema.Struct({ + "message": Schema.String.annotate({ "title": "Message", "default": "Rate limited" }), + "type": Schema.Literal("rate_limit_error").annotate({ "title": "Type", "default": "rate_limit_error" }) +}).annotate({ "title": "RateLimitError" }) +export type RequestBashCodeExecutionOutputBlock = { + readonly "file_id": string + readonly "type": "bash_code_execution_output" +} +export const RequestBashCodeExecutionOutputBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("bash_code_execution_output").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestBashCodeExecutionOutputBlock" }) +export type RequestCharLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_char_index": number + readonly "start_char_index": number + readonly "type": "char_location" +} +export const RequestCharLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([ + Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), + Schema.Null + ]).annotate({ "title": "Document Title" }), + "end_char_index": Schema.Number.annotate({ "title": "End Char Index" }).check(Schema.isInt()), + "start_char_index": Schema.Number.annotate({ "title": "Start Char Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "type": Schema.Literal("char_location").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestCharLocationCitation" }) +export type RequestCitationsConfig = { readonly "enabled"?: boolean } +export const RequestCitationsConfig = Schema.Struct({ + "enabled": Schema.optionalKey(Schema.Boolean.annotate({ "title": "Enabled" })) +}).annotate({ "title": "RequestCitationsConfig" }) +export type RequestCodeExecutionOutputBlock = { readonly "file_id": string; readonly "type": "code_execution_output" } +export const RequestCodeExecutionOutputBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("code_execution_output").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestCodeExecutionOutputBlock" }) +export type RequestContentBlockLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_block_index": number + readonly "start_block_index": number + readonly "type": "content_block_location" +} +export const RequestContentBlockLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([ + Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), + Schema.Null + ]).annotate({ "title": "Document Title" }), + "end_block_index": Schema.Number.annotate({ "title": "End Block Index" }).check(Schema.isInt()), + "start_block_index": Schema.Number.annotate({ "title": "Start Block Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "type": Schema.Literal("content_block_location").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestContentBlockLocationCitation" }) +export type RequestPageLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_page_number": number + readonly "start_page_number": number + readonly "type": "page_location" +} +export const RequestPageLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([ + Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), + Schema.Null + ]).annotate({ "title": "Document Title" }), + "end_page_number": Schema.Number.annotate({ "title": "End Page Number" }).check(Schema.isInt()), + "start_page_number": Schema.Number.annotate({ "title": "Start Page Number" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(1) + ), + "type": Schema.Literal("page_location").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestPageLocationCitation" }) +export type RequestSearchResultLocationCitation = { + readonly "cited_text": string + readonly "end_block_index": number + readonly "search_result_index": number + readonly "source": string + readonly "start_block_index": number + readonly "title": string | null + readonly "type": "search_result_location" +} +export const RequestSearchResultLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "end_block_index": Schema.Number.annotate({ "title": "End Block Index" }).check(Schema.isInt()), + "search_result_index": Schema.Number.annotate({ "title": "Search Result Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "source": Schema.String.annotate({ "title": "Source" }), + "start_block_index": Schema.Number.annotate({ "title": "Start Block Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Title" }), + "type": Schema.Literal("search_result_location").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestSearchResultLocationCitation" }) +export type RequestTextEditorCodeExecutionCreateResultBlock = { + readonly "is_file_update": boolean + readonly "type": "text_editor_code_execution_create_result" +} +export const RequestTextEditorCodeExecutionCreateResultBlock = Schema.Struct({ + "is_file_update": Schema.Boolean.annotate({ "title": "Is File Update" }), + "type": Schema.Literal("text_editor_code_execution_create_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionCreateResultBlock" }) +export type RequestTextEditorCodeExecutionStrReplaceResultBlock = { + readonly "lines"?: ReadonlyArray | null + readonly "new_lines"?: number | null + readonly "new_start"?: number | null + readonly "old_lines"?: number | null + readonly "old_start"?: number | null + readonly "type": "text_editor_code_execution_str_replace_result" +} +export const RequestTextEditorCodeExecutionStrReplaceResultBlock = Schema.Struct({ + "lines": Schema.optionalKey(Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ "title": "Lines" })), + "new_lines": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "New Lines" }) + ), + "new_start": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "New Start" }) + ), + "old_lines": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Old Lines" }) + ), + "old_start": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Old Start" }) + ), + "type": Schema.Literal("text_editor_code_execution_str_replace_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionStrReplaceResultBlock" }) +export type RequestTextEditorCodeExecutionViewResultBlock = { + readonly "content": string + readonly "file_type": "text" | "image" | "pdf" + readonly "num_lines"?: number | null + readonly "start_line"?: number | null + readonly "total_lines"?: number | null + readonly "type": "text_editor_code_execution_view_result" +} +export const RequestTextEditorCodeExecutionViewResultBlock = Schema.Struct({ + "content": Schema.String.annotate({ "title": "Content" }), + "file_type": Schema.Literals(["text", "image", "pdf"]).annotate({ "title": "File Type" }), + "num_lines": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Num Lines" }) + ), + "start_line": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Start Line" }) + ), + "total_lines": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ "title": "Total Lines" }) + ), + "type": Schema.Literal("text_editor_code_execution_view_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionViewResultBlock" }) +export type RequestWebSearchResultBlock = { + readonly "encrypted_content": string + readonly "page_age"?: string | null + readonly "title": string + readonly "type": "web_search_result" + readonly "url": string +} +export const RequestWebSearchResultBlock = Schema.Struct({ + "encrypted_content": Schema.String.annotate({ "title": "Encrypted Content" }), + "page_age": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Page Age" })), + "title": Schema.String.annotate({ "title": "Title" }), + "type": Schema.Literal("web_search_result").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "RequestWebSearchResultBlock" }) +export type RequestWebSearchResultLocationCitation = { + readonly "cited_text": string + readonly "encrypted_index": string + readonly "title": string | null + readonly "type": "web_search_result_location" + readonly "url": string +} +export const RequestWebSearchResultLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "encrypted_index": Schema.String.annotate({ "title": "Encrypted Index" }), + "title": Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(512)), Schema.Null]) + .annotate({ "title": "Title" }), + "type": Schema.Literal("web_search_result_location").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url" }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(2048)) +}).annotate({ "title": "RequestWebSearchResultLocationCitation" }) +export type ResponseBashCodeExecutionOutputBlock = { + readonly "file_id": string + readonly "type": "bash_code_execution_output" +} +export const ResponseBashCodeExecutionOutputBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("bash_code_execution_output").annotate({ + "title": "Type", + "default": "bash_code_execution_output" + }) +}).annotate({ "title": "ResponseBashCodeExecutionOutputBlock" }) +export type ResponseCharLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_char_index": number + readonly "file_id": string | null + readonly "start_char_index": number + readonly "type": "char_location" +} +export const ResponseCharLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Document Title" }), + "end_char_index": Schema.Number.annotate({ "title": "End Char Index" }).check(Schema.isInt()), + "file_id": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "File Id", "default": null }), + "start_char_index": Schema.Number.annotate({ "title": "Start Char Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "type": Schema.Literal("char_location").annotate({ "title": "Type", "default": "char_location" }) +}).annotate({ "title": "ResponseCharLocationCitation" }) +export type ResponseCitationsConfig = { readonly "enabled": boolean } +export const ResponseCitationsConfig = Schema.Struct({ + "enabled": Schema.Boolean.annotate({ "title": "Enabled", "default": false }) +}).annotate({ "title": "ResponseCitationsConfig" }) +export type ResponseCodeExecutionOutputBlock = { readonly "file_id": string; readonly "type": "code_execution_output" } +export const ResponseCodeExecutionOutputBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("code_execution_output").annotate({ "title": "Type", "default": "code_execution_output" }) +}).annotate({ "title": "ResponseCodeExecutionOutputBlock" }) +export type ResponseContainerUploadBlock = { readonly "file_id": string; readonly "type": "container_upload" } +export const ResponseContainerUploadBlock = Schema.Struct({ + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("container_upload").annotate({ "title": "Type", "default": "container_upload" }) +}).annotate({ + "title": "ResponseContainerUploadBlock", + "description": "Response model for a file uploaded to the container." +}) +export type ResponseContentBlockLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_block_index": number + readonly "file_id": string | null + readonly "start_block_index": number + readonly "type": "content_block_location" +} +export const ResponseContentBlockLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Document Title" }), + "end_block_index": Schema.Number.annotate({ "title": "End Block Index" }).check(Schema.isInt()), + "file_id": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "File Id", "default": null }), + "start_block_index": Schema.Number.annotate({ "title": "Start Block Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "type": Schema.Literal("content_block_location").annotate({ "title": "Type", "default": "content_block_location" }) +}).annotate({ "title": "ResponseContentBlockLocationCitation" }) +export type ResponsePageLocationCitation = { + readonly "cited_text": string + readonly "document_index": number + readonly "document_title": string | null + readonly "end_page_number": number + readonly "file_id": string | null + readonly "start_page_number": number + readonly "type": "page_location" +} +export const ResponsePageLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "document_index": Schema.Number.annotate({ "title": "Document Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "document_title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Document Title" }), + "end_page_number": Schema.Number.annotate({ "title": "End Page Number" }).check(Schema.isInt()), + "file_id": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "File Id", "default": null }), + "start_page_number": Schema.Number.annotate({ "title": "Start Page Number" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(1) + ), + "type": Schema.Literal("page_location").annotate({ "title": "Type", "default": "page_location" }) +}).annotate({ "title": "ResponsePageLocationCitation" }) +export type ResponseRedactedThinkingBlock = { readonly "data": string; readonly "type": "redacted_thinking" } +export const ResponseRedactedThinkingBlock = Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data" }), + "type": Schema.Literal("redacted_thinking").annotate({ "title": "Type", "default": "redacted_thinking" }) +}).annotate({ "title": "ResponseRedactedThinkingBlock" }) +export type ResponseSearchResultLocationCitation = { + readonly "cited_text": string + readonly "end_block_index": number + readonly "search_result_index": number + readonly "source": string + readonly "start_block_index": number + readonly "title": string | null + readonly "type": "search_result_location" +} +export const ResponseSearchResultLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "end_block_index": Schema.Number.annotate({ "title": "End Block Index" }).check(Schema.isInt()), + "search_result_index": Schema.Number.annotate({ "title": "Search Result Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "source": Schema.String.annotate({ "title": "Source" }), + "start_block_index": Schema.Number.annotate({ "title": "Start Block Index" }).check(Schema.isInt()).check( + Schema.isGreaterThanOrEqualTo(0) + ), + "title": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Title" }), + "type": Schema.Literal("search_result_location").annotate({ "title": "Type", "default": "search_result_location" }) +}).annotate({ "title": "ResponseSearchResultLocationCitation" }) +export type ResponseTextEditorCodeExecutionCreateResultBlock = { + readonly "is_file_update": boolean + readonly "type": "text_editor_code_execution_create_result" +} +export const ResponseTextEditorCodeExecutionCreateResultBlock = Schema.Struct({ + "is_file_update": Schema.Boolean.annotate({ "title": "Is File Update" }), + "type": Schema.Literal("text_editor_code_execution_create_result").annotate({ + "title": "Type", + "default": "text_editor_code_execution_create_result" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionCreateResultBlock" }) +export type ResponseTextEditorCodeExecutionStrReplaceResultBlock = { + readonly "lines": ReadonlyArray | null + readonly "new_lines": number | null + readonly "new_start": number | null + readonly "old_lines": number | null + readonly "old_start": number | null + readonly "type": "text_editor_code_execution_str_replace_result" +} +export const ResponseTextEditorCodeExecutionStrReplaceResultBlock = Schema.Struct({ + "lines": Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ "title": "Lines", "default": null }), + "new_lines": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "New Lines", + "default": null + }), + "new_start": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "New Start", + "default": null + }), + "old_lines": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Old Lines", + "default": null + }), + "old_start": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Old Start", + "default": null + }), + "type": Schema.Literal("text_editor_code_execution_str_replace_result").annotate({ + "title": "Type", + "default": "text_editor_code_execution_str_replace_result" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionStrReplaceResultBlock" }) +export type ResponseTextEditorCodeExecutionViewResultBlock = { + readonly "content": string + readonly "file_type": "text" | "image" | "pdf" + readonly "num_lines": number | null + readonly "start_line": number | null + readonly "total_lines": number | null + readonly "type": "text_editor_code_execution_view_result" +} +export const ResponseTextEditorCodeExecutionViewResultBlock = Schema.Struct({ + "content": Schema.String.annotate({ "title": "Content" }), + "file_type": Schema.Literals(["text", "image", "pdf"]).annotate({ "title": "File Type" }), + "num_lines": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Num Lines", + "default": null + }), + "start_line": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Start Line", + "default": null + }), + "total_lines": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Total Lines", + "default": null + }), + "type": Schema.Literal("text_editor_code_execution_view_result").annotate({ + "title": "Type", + "default": "text_editor_code_execution_view_result" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionViewResultBlock" }) +export type ResponseThinkingBlock = { + readonly "signature": string + readonly "thinking": string + readonly "type": "thinking" +} +export const ResponseThinkingBlock = Schema.Struct({ + "signature": Schema.String.annotate({ "title": "Signature" }), + "thinking": Schema.String.annotate({ "title": "Thinking" }), + "type": Schema.Literal("thinking").annotate({ "title": "Type", "default": "thinking" }) +}).annotate({ "title": "ResponseThinkingBlock" }) +export type ResponseToolReferenceBlock = { readonly "tool_name": string; readonly "type": "tool_reference" } +export const ResponseToolReferenceBlock = Schema.Struct({ + "tool_name": Schema.String.annotate({ "title": "Tool Name" }).check(Schema.isMinLength(1)).check( + Schema.isMaxLength(256) + ).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]{1,256}$"))), + "type": Schema.Literal("tool_reference").annotate({ "title": "Type", "default": "tool_reference" }) +}).annotate({ "title": "ResponseToolReferenceBlock" }) +export type ResponseWebSearchResultBlock = { + readonly "encrypted_content": string + readonly "page_age": string | null + readonly "title": string + readonly "type": "web_search_result" + readonly "url": string +} +export const ResponseWebSearchResultBlock = Schema.Struct({ + "encrypted_content": Schema.String.annotate({ "title": "Encrypted Content" }), + "page_age": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Page Age", "default": null }), + "title": Schema.String.annotate({ "title": "Title" }), + "type": Schema.Literal("web_search_result").annotate({ "title": "Type", "default": "web_search_result" }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "ResponseWebSearchResultBlock" }) +export type ResponseWebSearchResultLocationCitation = { + readonly "cited_text": string + readonly "encrypted_index": string + readonly "title": string | null + readonly "type": "web_search_result_location" + readonly "url": string +} +export const ResponseWebSearchResultLocationCitation = Schema.Struct({ + "cited_text": Schema.String.annotate({ "title": "Cited Text" }), + "encrypted_index": Schema.String.annotate({ "title": "Encrypted Index" }), + "title": Schema.Union([Schema.String.check(Schema.isMaxLength(512)), Schema.Null]).annotate({ "title": "Title" }), + "type": Schema.Literal("web_search_result_location").annotate({ + "title": "Type", + "default": "web_search_result_location" + }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "ResponseWebSearchResultLocationCitation" }) +export type ServerToolCaller = { readonly "tool_id": string; readonly "type": "code_execution_20250825" } +export const ServerToolCaller = Schema.Struct({ + "tool_id": Schema.String.annotate({ "title": "Tool Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("code_execution_20250825").annotate({ "title": "Type" }) +}).annotate({ "title": "ServerToolCaller", "description": "Tool invocation generated by a server-side tool." }) +export type ServerToolCaller_20260120 = { readonly "tool_id": string; readonly "type": "code_execution_20260120" } +export const ServerToolCaller_20260120 = Schema.Struct({ + "tool_id": Schema.String.annotate({ "title": "Tool Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("code_execution_20260120").annotate({ "title": "Type" }) +}).annotate({ "title": "ServerToolCaller_20260120" }) +export type ServerToolUsage = { readonly "web_fetch_requests": number; readonly "web_search_requests": number } +export const ServerToolUsage = Schema.Struct({ + "web_fetch_requests": Schema.Number.annotate({ + "title": "Web Fetch Requests", + "description": "The number of web fetch tool requests.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "web_search_requests": Schema.Number.annotate({ + "title": "Web Search Requests", + "description": "The number of web search tool requests.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) +}).annotate({ "title": "ServerToolUsage" }) +export type SignatureContentBlockDelta = { readonly "signature": string; readonly "type": "signature_delta" } +export const SignatureContentBlockDelta = Schema.Struct({ + "signature": Schema.String.annotate({ "title": "Signature" }), + "type": Schema.Literal("signature_delta").annotate({ "title": "Type", "default": "signature_delta" }) +}).annotate({ "title": "SignatureContentBlockDelta" }) +export type Skill = { + readonly "created_at": string + readonly "display_title": string | null + readonly "id": string + readonly "latest_version": string | null + readonly "source": string + readonly "type": string + readonly "updated_at": string +} +export const Skill = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill was created." + }), + "display_title": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Display Title", + "description": + "Display title for the skill.\n\nThis is a human-readable label that is not included in the prompt sent to the model." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill.\n\nThe format and length of IDs may change over time." + }), + "latest_version": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Latest Version", + "description": + "The latest version identifier for the skill.\n\nThis represents the most recent version of the skill that has been created." + }), + "source": Schema.String.annotate({ + "title": "Source", + "description": + "Source of the skill.\n\nThis may be one of the following values:\n* `\"custom\"`: the skill was created by a user\n* `\"anthropic\"`: the skill was created by Anthropic" + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skills, this is always `\"skill\"`.", + "default": "skill" + }), + "updated_at": Schema.String.annotate({ + "title": "Updated At", + "description": "ISO 8601 timestamp of when the skill was last updated." + }) +}).annotate({ "title": "Skill" }) +export type SkillVersion = { + readonly "created_at": string + readonly "description": string + readonly "directory": string + readonly "id": string + readonly "name": string + readonly "skill_id": string + readonly "type": string + readonly "version": string +} +export const SkillVersion = Schema.Struct({ + "created_at": Schema.String.annotate({ + "title": "Created At", + "description": "ISO 8601 timestamp of when the skill version was created." + }), + "description": Schema.String.annotate({ + "title": "Description", + "description": "Description of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "directory": Schema.String.annotate({ + "title": "Directory", + "description": + "Directory name of the skill version.\n\nThis is the top-level directory name that was extracted from the uploaded files." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique identifier for the skill version.\n\nThe format and length of IDs may change over time." + }), + "name": Schema.String.annotate({ + "title": "Name", + "description": + "Human-readable name of the skill version.\n\nThis is extracted from the SKILL.md file in the skill upload." + }), + "skill_id": Schema.String.annotate({ + "title": "Skill Id", + "description": "Identifier for the skill that this version belongs to." + }), + "type": Schema.String.annotate({ + "title": "Type", + "description": "Object type.\n\nFor Skill Versions, this is always `\"skill_version\"`.", + "default": "skill_version" + }), + "version": Schema.String.annotate({ + "title": "Version", + "description": + "Version identifier for the skill.\n\nEach version is identified by a Unix epoch timestamp (e.g., \"1759178010641129\")." + }) +}).annotate({ "title": "SkillVersion" }) +export type TextContentBlockDelta = { readonly "text": string; readonly "type": "text_delta" } +export const TextContentBlockDelta = Schema.Struct({ + "text": Schema.String.annotate({ "title": "Text" }), + "type": Schema.Literal("text_delta").annotate({ "title": "Type", "default": "text_delta" }) +}).annotate({ "title": "TextContentBlockDelta" }) +export type TextEditorCodeExecutionToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "too_many_requests" + | "execution_time_exceeded" + | "file_not_found" +export const TextEditorCodeExecutionToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "too_many_requests", + "execution_time_exceeded", + "file_not_found" +]).annotate({ "title": "TextEditorCodeExecutionToolResultErrorCode" }) +export type ThinkingConfigAdaptive = { readonly "type": "adaptive" } +export const ThinkingConfigAdaptive = Schema.Struct({ + "type": Schema.Literal("adaptive").annotate({ "title": "Type" }) +}).annotate({ "title": "ThinkingConfigAdaptive" }) +export type ThinkingConfigDisabled = { readonly "type": "disabled" } +export const ThinkingConfigDisabled = Schema.Struct({ + "type": Schema.Literal("disabled").annotate({ "title": "Type" }) +}).annotate({ "title": "ThinkingConfigDisabled" }) +export type ThinkingConfigEnabled = { readonly "budget_tokens": number; readonly "type": "enabled" } +export const ThinkingConfigEnabled = Schema.Struct({ + "budget_tokens": Schema.Number.annotate({ + "title": "Budget Tokens", + "description": + "Determines how many tokens Claude can use for its internal reasoning process. Larger budgets can enable more thorough analysis for complex problems, improving response quality.\n\nMust be ≥1024 and less than `max_tokens`.\n\nSee [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1024)), + "type": Schema.Literal("enabled").annotate({ "title": "Type" }) +}).annotate({ "title": "ThinkingConfigEnabled" }) +export type ThinkingContentBlockDelta = { readonly "thinking": string; readonly "type": "thinking_delta" } +export const ThinkingContentBlockDelta = Schema.Struct({ + "thinking": Schema.String.annotate({ "title": "Thinking" }), + "type": Schema.Literal("thinking_delta").annotate({ "title": "Type", "default": "thinking_delta" }) +}).annotate({ "title": "ThinkingContentBlockDelta" }) +export type ToolChoiceAny = { readonly "disable_parallel_tool_use"?: boolean; readonly "type": "any" } +export const ToolChoiceAny = Schema.Struct({ + "disable_parallel_tool_use": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Disable Parallel Tool Use", + "description": + "Whether to disable parallel tool use.\n\nDefaults to `false`. If set to `true`, the model will output exactly one tool use." + }) + ), + "type": Schema.Literal("any").annotate({ "title": "Type" }) +}).annotate({ "title": "ToolChoiceAny", "description": "The model will use any available tools." }) +export type ToolChoiceAuto = { readonly "disable_parallel_tool_use"?: boolean; readonly "type": "auto" } +export const ToolChoiceAuto = Schema.Struct({ + "disable_parallel_tool_use": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Disable Parallel Tool Use", + "description": + "Whether to disable parallel tool use.\n\nDefaults to `false`. If set to `true`, the model will output at most one tool use." + }) + ), + "type": Schema.Literal("auto").annotate({ "title": "Type" }) +}).annotate({ "title": "ToolChoiceAuto", "description": "The model will automatically decide whether to use tools." }) +export type ToolChoiceNone = { readonly "type": "none" } +export const ToolChoiceNone = Schema.Struct({ "type": Schema.Literal("none").annotate({ "title": "Type" }) }).annotate({ + "title": "ToolChoiceNone", + "description": "The model will not be allowed to use tools." +}) +export type ToolChoiceTool = { + readonly "disable_parallel_tool_use"?: boolean + readonly "name": string + readonly "type": "tool" +} +export const ToolChoiceTool = Schema.Struct({ + "disable_parallel_tool_use": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Disable Parallel Tool Use", + "description": + "Whether to disable parallel tool use.\n\nDefaults to `false`. If set to `true`, the model will output exactly one tool use." + }) + ), + "name": Schema.String.annotate({ "title": "Name", "description": "The name of the tool to use." }), + "type": Schema.Literal("tool").annotate({ "title": "Type" }) +}).annotate({ + "title": "ToolChoiceTool", + "description": "The model will use the specified tool with `tool_choice.name`." +}) +export type ToolSearchToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "too_many_requests" + | "execution_time_exceeded" +export const ToolSearchToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "too_many_requests", + "execution_time_exceeded" +]).annotate({ "title": "ToolSearchToolResultErrorCode" }) +export type URLImageSource = { readonly "type": "url"; readonly "url": string } +export const URLImageSource = Schema.Struct({ + "type": Schema.Literal("url").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "URLImageSource" }) +export type URLPDFSource = { readonly "type": "url"; readonly "url": string } +export const URLPDFSource = Schema.Struct({ + "type": Schema.Literal("url").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "URLPDFSource" }) +export type UserLocation = { + readonly "city"?: string | null + readonly "country"?: string | null + readonly "region"?: string | null + readonly "timezone"?: string | null + readonly "type": "approximate" +} +export const UserLocation = Schema.Struct({ + "city": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), Schema.Null]).annotate({ + "title": "City", + "description": "The city of the user." + }) + ), + "country": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(2)).check(Schema.isMaxLength(2)), Schema.Null]).annotate({ + "title": "Country", + "description": "The two letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) of the user." + }) + ), + "region": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), Schema.Null]).annotate({ + "title": "Region", + "description": "The region of the user." + }) + ), + "timezone": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), Schema.Null]).annotate({ + "title": "Timezone", + "description": "The [IANA timezone](https://nodatime.org/TimeZones) of the user." + }) + ), + "type": Schema.Literal("approximate").annotate({ "title": "Type" }) +}).annotate({ "title": "UserLocation" }) +export type WebFetchToolResultErrorCode = + | "invalid_tool_input" + | "url_too_long" + | "url_not_allowed" + | "url_not_accessible" + | "unsupported_content_type" + | "too_many_requests" + | "max_uses_exceeded" + | "unavailable" +export const WebFetchToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "url_too_long", + "url_not_allowed", + "url_not_accessible", + "unsupported_content_type", + "too_many_requests", + "max_uses_exceeded", + "unavailable" +]).annotate({ "title": "WebFetchToolResultErrorCode" }) +export type WebSearchToolResultErrorCode = + | "invalid_tool_input" + | "unavailable" + | "max_uses_exceeded" + | "too_many_requests" + | "query_too_long" + | "request_too_large" +export const WebSearchToolResultErrorCode = Schema.Literals([ + "invalid_tool_input", + "unavailable", + "max_uses_exceeded", + "too_many_requests", + "query_too_long", + "request_too_large" +]).annotate({ "title": "WebSearchToolResultErrorCode" }) +export type StopReason = "end_turn" | "max_tokens" | "stop_sequence" | "tool_use" | "pause_turn" | "refusal" +export const StopReason = Schema.Literals([ + "end_turn", + "max_tokens", + "stop_sequence", + "tool_use", + "pause_turn", + "refusal" +]) +export type BetaStopReason = + | "end_turn" + | "max_tokens" + | "stop_sequence" + | "tool_use" + | "pause_turn" + | "compaction" + | "refusal" + | "model_context_window_exceeded" +export const BetaStopReason = Schema.Literals([ + "end_turn", + "max_tokens", + "stop_sequence", + "tool_use", + "pause_turn", + "compaction", + "refusal", + "model_context_window_exceeded" +]) +export type Model = + | string + | "claude-sonnet-5" + | "claude-fable-5" + | "claude-mythos-5" + | "claude-opus-4-8" + | "claude-opus-4-7" + | "claude-mythos-preview" + | "claude-opus-4-6" + | "claude-sonnet-4-6" + | "claude-haiku-4-5" + | "claude-haiku-4-5-20251001" + | "claude-opus-4-5" + | "claude-opus-4-5-20251101" + | "claude-sonnet-4-5" + | "claude-sonnet-4-5-20250929" + | "claude-opus-4-1" + | "claude-opus-4-1-20250805" +export const Model = Schema.Union([ + Schema.String, + Schema.Literals([ + "claude-sonnet-5", + "claude-fable-5", + "claude-mythos-5", + "claude-opus-4-8", + "claude-opus-4-7", + "claude-mythos-preview", + "claude-opus-4-6", + "claude-sonnet-4-6", + "claude-haiku-4-5", + "claude-haiku-4-5-20251001", + "claude-opus-4-5", + "claude-opus-4-5-20251101", + "claude-sonnet-4-5", + "claude-sonnet-4-5-20250929", + "claude-opus-4-1", + "claude-opus-4-1-20250805" + ]) +]).annotate({ + "title": "Model", + "description": + "The model that will complete your prompt.\n\nSee [models](https://docs.anthropic.com/en/docs/models-overview) for additional details and options." +}) +export type BetaMemoryTool_20250818_ViewCommand = { + readonly "command": "view" + readonly "path": string + readonly "view_range"?: ReadonlyArray +} +export const BetaMemoryTool_20250818_ViewCommand = Schema.Struct({ + "command": Schema.Literal("view").annotate({ "description": "Command type identifier", "default": "view" }), + "path": Schema.String.annotate({ "description": "Path to directory or file to view" }), + "view_range": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": "Optional line range for viewing specific lines" + }).check(Schema.isMinLength(2)).check(Schema.isMaxLength(2)) + ) +}) +export type BetaMemoryTool_20250818_CreateCommand = { + readonly "command": "create" + readonly "path": string + readonly "file_text": string +} +export const BetaMemoryTool_20250818_CreateCommand = Schema.Struct({ + "command": Schema.Literal("create").annotate({ "description": "Command type identifier", "default": "create" }), + "path": Schema.String.annotate({ "description": "Path where the file should be created" }), + "file_text": Schema.String.annotate({ "description": "Content to write to the file" }) +}) +export type BetaMemoryTool_20250818_StrReplaceCommand = { + readonly "command": "str_replace" + readonly "path": string + readonly "old_str": string + readonly "new_str": string +} +export const BetaMemoryTool_20250818_StrReplaceCommand = Schema.Struct({ + "command": Schema.Literal("str_replace").annotate({ + "description": "Command type identifier", + "default": "str_replace" + }), + "path": Schema.String.annotate({ "description": "Path to the file where text should be replaced" }), + "old_str": Schema.String.annotate({ "description": "Text to search for and replace" }), + "new_str": Schema.String.annotate({ "description": "Text to replace with" }) +}) +export type BetaMemoryTool_20250818_InsertCommand = { + readonly "command": "insert" + readonly "path": string + readonly "insert_line": number + readonly "insert_text": string +} +export const BetaMemoryTool_20250818_InsertCommand = Schema.Struct({ + "command": Schema.Literal("insert").annotate({ "description": "Command type identifier", "default": "insert" }), + "path": Schema.String.annotate({ "description": "Path to the file where text should be inserted" }), + "insert_line": Schema.Number.annotate({ "description": "Line number where text should be inserted" }).check( + Schema.isInt() + ).check(Schema.isGreaterThanOrEqualTo(1)), + "insert_text": Schema.String.annotate({ "description": "Text to insert at the specified line" }) +}) +export type BetaMemoryTool_20250818_DeleteCommand = { readonly "command": "delete"; readonly "path": string } +export const BetaMemoryTool_20250818_DeleteCommand = Schema.Struct({ + "command": Schema.Literal("delete").annotate({ "description": "Command type identifier", "default": "delete" }), + "path": Schema.String.annotate({ "description": "Path to the file or directory to delete" }) +}) +export type BetaMemoryTool_20250818_RenameCommand = { + readonly "command": "rename" + readonly "old_path": string + readonly "new_path": string +} +export const BetaMemoryTool_20250818_RenameCommand = Schema.Struct({ + "command": Schema.Literal("rename").annotate({ "description": "Command type identifier", "default": "rename" }), + "old_path": Schema.String.annotate({ "description": "Current path of the file or directory" }), + "new_path": Schema.String.annotate({ "description": "New path for the file or directory" }) +}) +export type RequestBashCodeExecutionToolResultError = { + readonly "error_code": BashCodeExecutionToolResultErrorCode + readonly "type": "bash_code_execution_tool_result_error" +} +export const RequestBashCodeExecutionToolResultError = Schema.Struct({ + "error_code": BashCodeExecutionToolResultErrorCode, + "type": Schema.Literal("bash_code_execution_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestBashCodeExecutionToolResultError" }) +export type ResponseBashCodeExecutionToolResultError = { + readonly "error_code": BashCodeExecutionToolResultErrorCode + readonly "type": "bash_code_execution_tool_result_error" +} +export const ResponseBashCodeExecutionToolResultError = Schema.Struct({ + "error_code": BashCodeExecutionToolResultErrorCode, + "type": Schema.Literal("bash_code_execution_tool_result_error").annotate({ + "title": "Type", + "default": "bash_code_execution_tool_result_error" + }) +}).annotate({ "title": "ResponseBashCodeExecutionToolResultError" }) +export type BetaRequestBashCodeExecutionToolResultError = { + readonly "error_code": BetaBashCodeExecutionToolResultErrorCode + readonly "type": "bash_code_execution_tool_result_error" +} +export const BetaRequestBashCodeExecutionToolResultError = Schema.Struct({ + "error_code": BetaBashCodeExecutionToolResultErrorCode, + "type": Schema.Literal("bash_code_execution_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestBashCodeExecutionToolResultError" }) +export type BetaResponseBashCodeExecutionToolResultError = { + readonly "error_code": BetaBashCodeExecutionToolResultErrorCode + readonly "type": "bash_code_execution_tool_result_error" +} +export const BetaResponseBashCodeExecutionToolResultError = Schema.Struct({ + "error_code": BetaBashCodeExecutionToolResultErrorCode, + "type": Schema.Literal("bash_code_execution_tool_result_error").annotate({ + "title": "Type", + "default": "bash_code_execution_tool_result_error" + }) +}).annotate({ "title": "ResponseBashCodeExecutionToolResultError" }) +export type BetaCodeExecutionTool_20250522 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "code_execution" + readonly "strict"?: boolean + readonly "type": "code_execution_20250522" +} +export const BetaCodeExecutionTool_20250522 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("code_execution").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("code_execution_20250522").annotate({ "title": "Type" }) +}).annotate({ "title": "CodeExecutionTool_20250522" }) +export type BetaCodeExecutionTool_20250825 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "code_execution" + readonly "strict"?: boolean + readonly "type": "code_execution_20250825" +} +export const BetaCodeExecutionTool_20250825 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("code_execution").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("code_execution_20250825").annotate({ "title": "Type" }) +}).annotate({ "title": "CodeExecutionTool_20250825" }) +export type BetaCodeExecutionTool_20260120 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "code_execution" + readonly "strict"?: boolean + readonly "type": "code_execution_20260120" +} +export const BetaCodeExecutionTool_20260120 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("code_execution").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("code_execution_20260120").annotate({ "title": "Type" }) +}).annotate({ + "title": "CodeExecutionTool_20260120", + "description": "Code execution tool with REPL state persistence (daemon mode + gVisor checkpoint)." +}) +export type BetaRequestCompactionBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "content": string | null + readonly "type": "compaction" +} +export const BetaRequestCompactionBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Content", + "description": "Summary of previously compacted content, or null if compaction failed" + }), + "type": Schema.Literal("compaction").annotate({ "title": "Type" }) +}).annotate({ + "title": "RequestCompactionBlock", + "description": + "A compaction block containing summary of previous context.\n\nUsers should round-trip these blocks from responses to subsequent requests\nto maintain context across compaction boundaries.\n\nWhen content is None, the block represents a failed compaction. The server\ntreats these as no-ops. Empty string content is not allowed." +}) +export type BetaRequestContainerUploadBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "file_id": string + readonly "type": "container_upload" +} +export const BetaRequestContainerUploadBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("container_upload").annotate({ "title": "Type" }) +}).annotate({ + "title": "RequestContainerUploadBlock", + "description": + "A content block that represents a file to be uploaded to the container\nFiles uploaded via this block will be available in the container's input directory." +}) +export type BetaRequestMCPToolUseBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": string + readonly "server_name": string + readonly "type": "mcp_tool_use" +} +export const BetaRequestMCPToolUseBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.String.annotate({ "title": "Name" }), + "server_name": Schema.String.annotate({ "title": "Server Name", "description": "The name of the MCP server" }), + "type": Schema.Literal("mcp_tool_use").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestMCPToolUseBlock" }) +export type BetaRequestToolReferenceBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "tool_name": string + readonly "type": "tool_reference" +} +export const BetaRequestToolReferenceBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "tool_name": Schema.String.annotate({ "title": "Tool Name" }).check(Schema.isMinLength(1)).check( + Schema.isMaxLength(256) + ).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]{1,256}$"))), + "type": Schema.Literal("tool_reference").annotate({ "title": "Type" }) +}).annotate({ + "title": "RequestToolReferenceBlock", + "description": "Tool reference block that can be included in tool_result content." +}) +export type BetaToolSearchToolBM25_20251119 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "tool_search_tool_bm25" + readonly "strict"?: boolean + readonly "type": "tool_search_tool_bm25_20251119" | "tool_search_tool_bm25" +} +export const BetaToolSearchToolBM25_20251119 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("tool_search_tool_bm25").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literals(["tool_search_tool_bm25_20251119", "tool_search_tool_bm25"]).annotate({ "title": "Type" }) +}).annotate({ "title": "ToolSearchToolBM25_20251119" }) +export type BetaToolSearchToolRegex_20251119 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "tool_search_tool_regex" + readonly "strict"?: boolean + readonly "type": "tool_search_tool_regex_20251119" | "tool_search_tool_regex" +} +export const BetaToolSearchToolRegex_20251119 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("tool_search_tool_regex").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literals(["tool_search_tool_regex_20251119", "tool_search_tool_regex"]).annotate({ "title": "Type" }) +}).annotate({ "title": "ToolSearchToolRegex_20251119" }) +export type BetaCompactionIterationUsage = { + readonly "cache_creation": BetaCacheCreation | null + readonly "cache_creation_input_tokens": number + readonly "cache_read_input_tokens": number + readonly "input_tokens": number + readonly "output_tokens": number + readonly "type": "compaction" +} +export const BetaCompactionIterationUsage = Schema.Struct({ + "cache_creation": Schema.Union([BetaCacheCreation, Schema.Null]).annotate({ + "description": "Breakdown of cached tokens by TTL", + "default": null + }), + "cache_creation_input_tokens": Schema.Number.annotate({ + "title": "Cache Creation Input Tokens", + "description": "The number of input tokens used to create the cache entry.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "cache_read_input_tokens": Schema.Number.annotate({ + "title": "Cache Read Input Tokens", + "description": "The number of input tokens read from the cache.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "input_tokens": Schema.Number.annotate({ + "title": "Input Tokens", + "description": "The number of input tokens which were used." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "output_tokens": Schema.Number.annotate({ + "title": "Output Tokens", + "description": "The number of output tokens which were used." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "type": Schema.Literal("compaction").annotate({ + "title": "Type", + "description": "Usage for a compaction iteration", + "default": "compaction" + }) +}).annotate({ "title": "CompactionIterationUsage", "description": "Token usage for a compaction iteration." }) +export type BetaMessageIterationUsage = { + readonly "cache_creation": BetaCacheCreation | null + readonly "cache_creation_input_tokens": number + readonly "cache_read_input_tokens": number + readonly "input_tokens": number + readonly "output_tokens": number + readonly "type": "message" +} +export const BetaMessageIterationUsage = Schema.Struct({ + "cache_creation": Schema.Union([BetaCacheCreation, Schema.Null]).annotate({ + "description": "Breakdown of cached tokens by TTL", + "default": null + }), + "cache_creation_input_tokens": Schema.Number.annotate({ + "title": "Cache Creation Input Tokens", + "description": "The number of input tokens used to create the cache entry.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "cache_read_input_tokens": Schema.Number.annotate({ + "title": "Cache Read Input Tokens", + "description": "The number of input tokens read from the cache.", + "default": 0 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "input_tokens": Schema.Number.annotate({ + "title": "Input Tokens", + "description": "The number of input tokens which were used." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "output_tokens": Schema.Number.annotate({ + "title": "Output Tokens", + "description": "The number of output tokens which were used." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "type": Schema.Literal("message").annotate({ + "title": "Type", + "description": "Usage for a sampling iteration", + "default": "message" + }) +}).annotate({ "title": "MessageIterationUsage", "description": "Token usage for a sampling iteration." }) +export type BetaRequestCodeExecutionToolResultError = { + readonly "error_code": BetaCodeExecutionToolResultErrorCode + readonly "type": "code_execution_tool_result_error" +} +export const BetaRequestCodeExecutionToolResultError = Schema.Struct({ + "error_code": BetaCodeExecutionToolResultErrorCode, + "type": Schema.Literal("code_execution_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "Error" }) +export type BetaResponseCodeExecutionToolResultError = { + readonly "error_code": BetaCodeExecutionToolResultErrorCode + readonly "type": "code_execution_tool_result_error" +} +export const BetaResponseCodeExecutionToolResultError = Schema.Struct({ + "error_code": BetaCodeExecutionToolResultErrorCode, + "type": Schema.Literal("code_execution_tool_result_error").annotate({ + "title": "Type", + "default": "code_execution_tool_result_error" + }) +}).annotate({ "title": "ResponseCodeExecutionToolResultError" }) +export type BetaCountMessageTokensResponse = { + readonly "context_management": BetaContextManagementResponse | null + readonly "input_tokens": number +} +export const BetaCountMessageTokensResponse = Schema.Struct({ + "context_management": Schema.Union([BetaContextManagementResponse, Schema.Null]).annotate({ + "description": "Information about context management applied to the message." + }), + "input_tokens": Schema.Number.annotate({ + "title": "Input Tokens", + "description": "The total number of tokens across the provided list of messages, system prompt, and tools." + }).check(Schema.isInt()) +}).annotate({ "title": "CountMessageTokensResponse" }) +export type BetaFileListResponse = { + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "has_more"?: boolean + readonly "last_id"?: string | null +} +export const BetaFileListResponse = Schema.Struct({ + "data": Schema.Array(BetaFileMetadataSchema).annotate({ + "title": "Data", + "description": "List of file metadata objects." + }), + "first_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "First Id", + "description": "ID of the first file in this page of results." + }) + ), + "has_more": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Has More", + "description": "Whether there are more results available.", + "default": false + }) + ), + "last_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Last Id", + "description": "ID of the last file in this page of results." + }) + ) +}).annotate({ "title": "FileListResponse" }) +export type BetaCompact20260112 = { + readonly "instructions"?: string | null + readonly "pause_after_compaction"?: boolean + readonly "trigger"?: BetaInputTokensTrigger | null + readonly "type": "compact_20260112" +} +export const BetaCompact20260112 = Schema.Struct({ + "instructions": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Instructions", + "description": "Additional instructions for summarization." + }) + ), + "pause_after_compaction": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Pause After Compaction", + "description": "Whether to pause after compaction and return the compaction block to the user." + }) + ), + "trigger": Schema.optionalKey( + Schema.Union([BetaInputTokensTrigger, Schema.Null]).annotate({ + "description": "When to trigger compaction. Defaults to 150000 input tokens." + }) + ), + "type": Schema.Literal("compact_20260112").annotate({ "title": "Type" }) +}).annotate({ + "title": "Compact20260112", + "description": "Automatically compact older context when reaching the configured trigger threshold." +}) +export type BetaBashTool_20241022 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "name": "bash" + readonly "strict"?: boolean + readonly "type": "bash_20241022" +} +export const BetaBashTool_20241022 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("bash").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("bash_20241022").annotate({ "title": "Type" }) +}).annotate({ "title": "BashTool_20241022" }) +export type BetaBashTool_20250124 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "name": "bash" + readonly "strict"?: boolean + readonly "type": "bash_20250124" +} +export const BetaBashTool_20250124 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("bash").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("bash_20250124").annotate({ "title": "Type" }) +}).annotate({ "title": "BashTool_20250124" }) +export type BetaComputerUseTool_20241022 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "display_height_px": number + readonly "display_number"?: number | null + readonly "display_width_px": number + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "name": "computer" + readonly "strict"?: boolean + readonly "type": "computer_20241022" +} +export const BetaComputerUseTool_20241022 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "display_height_px": Schema.Number.annotate({ + "title": "Display Height Px", + "description": "The height of the display in pixels." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "display_number": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), Schema.Null]).annotate({ + "title": "Display Number", + "description": "The X11 display number (e.g. 0, 1) for the display." + }) + ), + "display_width_px": Schema.Number.annotate({ + "title": "Display Width Px", + "description": "The width of the display in pixels." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("computer").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("computer_20241022").annotate({ "title": "Type" }) +}).annotate({ "title": "ComputerUseTool_20241022" }) +export type BetaComputerUseTool_20250124 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "display_height_px": number + readonly "display_number"?: number | null + readonly "display_width_px": number + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "name": "computer" + readonly "strict"?: boolean + readonly "type": "computer_20250124" +} +export const BetaComputerUseTool_20250124 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "display_height_px": Schema.Number.annotate({ + "title": "Display Height Px", + "description": "The height of the display in pixels." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "display_number": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), Schema.Null]).annotate({ + "title": "Display Number", + "description": "The X11 display number (e.g. 0, 1) for the display." + }) + ), + "display_width_px": Schema.Number.annotate({ + "title": "Display Width Px", + "description": "The width of the display in pixels." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("computer").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("computer_20250124").annotate({ "title": "Type" }) +}).annotate({ "title": "ComputerUseTool_20250124" }) +export type BetaComputerUseTool_20251124 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "display_height_px": number + readonly "display_number"?: number | null + readonly "display_width_px": number + readonly "enable_zoom"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "name": "computer" + readonly "strict"?: boolean + readonly "type": "computer_20251124" +} +export const BetaComputerUseTool_20251124 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "display_height_px": Schema.Number.annotate({ + "title": "Display Height Px", + "description": "The height of the display in pixels." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "display_number": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), Schema.Null]).annotate({ + "title": "Display Number", + "description": "The X11 display number (e.g. 0, 1) for the display." + }) + ), + "display_width_px": Schema.Number.annotate({ + "title": "Display Width Px", + "description": "The width of the display in pixels." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "enable_zoom": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Enable Zoom", + "description": "Whether to enable an action to take a zoomed-in screenshot of the screen." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("computer").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("computer_20251124").annotate({ "title": "Type" }) +}).annotate({ "title": "ComputerUseTool_20251124" }) +export type BetaMemoryTool_20250818 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "name": "memory" + readonly "strict"?: boolean + readonly "type": "memory_20250818" +} +export const BetaMemoryTool_20250818 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("memory").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("memory_20250818").annotate({ "title": "Type" }) +}).annotate({ "title": "MemoryTool_20250818" }) +export type BetaTextEditor_20241022 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "name": "str_replace_editor" + readonly "strict"?: boolean + readonly "type": "text_editor_20241022" +} +export const BetaTextEditor_20241022 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("str_replace_editor").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("text_editor_20241022").annotate({ "title": "Type" }) +}).annotate({ "title": "TextEditor_20241022" }) +export type BetaTextEditor_20250124 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "name": "str_replace_editor" + readonly "strict"?: boolean + readonly "type": "text_editor_20250124" +} +export const BetaTextEditor_20250124 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("str_replace_editor").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("text_editor_20250124").annotate({ "title": "Type" }) +}).annotate({ "title": "TextEditor_20250124" }) +export type BetaTextEditor_20250429 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "name": "str_replace_based_edit_tool" + readonly "strict"?: boolean + readonly "type": "text_editor_20250429" +} +export const BetaTextEditor_20250429 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("str_replace_based_edit_tool").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("text_editor_20250429").annotate({ "title": "Type" }) +}).annotate({ "title": "TextEditor_20250429" }) +export type BetaTextEditor_20250728 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> + readonly "max_characters"?: number | null + readonly "name": "str_replace_based_edit_tool" + readonly "strict"?: boolean + readonly "type": "text_editor_20250728" +} +export const BetaTextEditor_20250728 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ), + "max_characters": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), Schema.Null]).annotate({ + "title": "Max Characters", + "description": + "Maximum number of characters to display when viewing a file. If not specified, defaults to displaying the full file." + }) + ), + "name": Schema.Literal("str_replace_based_edit_tool").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("text_editor_20250728").annotate({ "title": "Type" }) +}).annotate({ "title": "TextEditor_20250728" }) +export type BetaTool = { + readonly "type"?: null | "custom" + readonly "description"?: string + readonly "name": string + readonly "input_schema": { + readonly "properties"?: { readonly [x: string]: Schema.Json } | null + readonly "required"?: ReadonlyArray | null + readonly "type": "object" + readonly [x: string]: Schema.Json + } + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "strict"?: boolean + readonly "eager_input_streaming"?: boolean | null + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: BetaJsonValue }> +} +export const BetaTool = Schema.Struct({ + "type": Schema.optionalKey(Schema.Union([Schema.Null, Schema.Literal("custom")]).annotate({ "title": "Type" })), + "description": Schema.optionalKey(Schema.String.annotate({ + "title": "Description", + "description": + "Description of what this tool does.\n\nTool descriptions should be as detailed as possible. The more information that the model has about what the tool is and how to use it, the better it will perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema." + })), + "name": Schema.String.annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(128)).check( + Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]{1,128}$")) + ), + "input_schema": Schema.StructWithRest( + Schema.Struct({ + "properties": Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Json), Schema.Null]).annotate({ "title": "Properties" }) + ), + "required": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ "title": "Required" }) + ), + "type": Schema.Literal("object").annotate({ "title": "Type" }) + }), + [Schema.Record(Schema.String, Schema.Json)] + ).annotate({ + "title": "InputSchema", + "description": + "[JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n\nThis defines the shape of the `input` that your tool accepts and that the model will produce." + }), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "eager_input_streaming": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "title": "Eager Input Streaming", + "description": + "Enable eager input streaming for this tool. When true, tool input parameters will be streamed incrementally as they are generated, and types will be inferred on-the-fly rather than buffering the full JSON output. When false, streaming is disabled for this tool even if the fine-grained-tool-streaming beta is active. When null (default), uses the default behavior based on beta headers." + }) + ), + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, BetaJsonValue)).annotate({ "title": "Input Examples" }) + ) +}).annotate({ "title": "Tool" }) +export type BetaMCPToolset = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "configs"?: { readonly [x: string]: BetaMCPToolConfig } | null + readonly "default_config"?: { readonly "defer_loading"?: boolean; readonly "enabled"?: boolean } + readonly "mcp_server_name": string + readonly "type": "mcp_toolset" +} +export const BetaMCPToolset = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "configs": Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, BetaMCPToolConfig), Schema.Null]).annotate({ + "title": "Configs", + "description": "Configuration overrides for specific tools, keyed by tool name" + }) + ), + "default_config": Schema.optionalKey( + Schema.Struct({ + "defer_loading": Schema.optionalKey(Schema.Boolean.annotate({ "title": "Defer Loading" })), + "enabled": Schema.optionalKey(Schema.Boolean.annotate({ "title": "Enabled" })) + }).annotate({ + "title": "MCPToolDefaultConfig", + "description": "Default configuration applied to all tools from this server" + }) + ), + "mcp_server_name": Schema.String.annotate({ + "title": "Mcp Server Name", + "description": "Name of the MCP server to configure tools for" + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(255)), + "type": Schema.Literal("mcp_toolset").annotate({ "title": "Type" }) +}).annotate({ + "title": "MCPToolset", + "description": + "Configuration for a group of tools from an MCP server.\n\nAllows configuring enabled status and defer_loading for all tools\nfrom an MCP server, with optional per-tool overrides." +}) +export type BetaListResponse_MessageBatch_ = { + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "has_more": boolean + readonly "last_id": string | null +} +export const BetaListResponse_MessageBatch_ = Schema.Struct({ + "data": Schema.Array(BetaMessageBatch).annotate({ "title": "Data" }), + "first_id": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "First Id", + "description": "First ID in the `data` list. Can be used as the `before_id` for the previous page." + }), + "has_more": Schema.Boolean.annotate({ + "title": "Has More", + "description": "Indicates if there are more results in the requested page direction." + }), + "last_id": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Last Id", + "description": "Last ID in the `data` list. Can be used as the `after_id` for the next page." + }) +}).annotate({ "title": "ListResponse[MessageBatch]" }) +export type BetaListResponse_ModelInfo_ = { + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "has_more": boolean + readonly "last_id": string | null +} +export const BetaListResponse_ModelInfo_ = Schema.Struct({ + "data": Schema.Array(BetaModelInfo).annotate({ "title": "Data" }), + "first_id": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "First Id", + "description": "First ID in the `data` list. Can be used as the `before_id` for the previous page." + }), + "has_more": Schema.Boolean.annotate({ + "title": "Has More", + "description": "Indicates if there are more results in the requested page direction." + }), + "last_id": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Last Id", + "description": "Last ID in the `data` list. Can be used as the `after_id` for the next page." + }) +}).annotate({ "title": "ListResponse[ModelInfo]" }) +export type BetaErrorResponse = { + readonly "error": + | BetaInvalidRequestError + | BetaAuthenticationError + | BetaBillingError + | BetaPermissionError + | BetaNotFoundError + | BetaRateLimitError + | BetaGatewayTimeoutError + | BetaAPIError + | BetaOverloadedError + readonly "request_id": string | null + readonly "type": "error" +} +export const BetaErrorResponse = Schema.Struct({ + "error": Schema.Union([ + BetaInvalidRequestError, + BetaAuthenticationError, + BetaBillingError, + BetaPermissionError, + BetaNotFoundError, + BetaRateLimitError, + BetaGatewayTimeoutError, + BetaAPIError, + BetaOverloadedError + ], { mode: "oneOf" }).annotate({ "title": "Error" }), + "request_id": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Request Id", "default": null }), + "type": Schema.Literal("error").annotate({ "title": "Type", "default": "error" }) +}).annotate({ "title": "ErrorResponse" }) +export type BetaRequestBashCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "return_code": number + readonly "stderr": string + readonly "stdout": string + readonly "type": "bash_code_execution_result" +} +export const BetaRequestBashCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(BetaRequestBashCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "stdout": Schema.String.annotate({ "title": "Stdout" }), + "type": Schema.Literal("bash_code_execution_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestBashCodeExecutionResultBlock" }) +export type BetaWebFetchTool_20250910 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "allowed_domains"?: ReadonlyArray | null + readonly "blocked_domains"?: ReadonlyArray | null + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "citations"?: BetaRequestCitationsConfig | null + readonly "defer_loading"?: boolean + readonly "max_content_tokens"?: number | null + readonly "max_uses"?: number | null + readonly "name": "web_fetch" + readonly "strict"?: boolean + readonly "type": "web_fetch_20250910" +} +export const BetaWebFetchTool_20250910 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "allowed_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Allowed Domains", + "description": "List of domains to allow fetching from" + }) + ), + "blocked_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Blocked Domains", + "description": "List of domains to block fetching from" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey( + Schema.Union([BetaRequestCitationsConfig, Schema.Null]).annotate({ + "description": "Citations configuration for fetched documents. Citations are disabled by default." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "max_content_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Content Tokens", + "description": + "Maximum number of tokens used by including web page text content in the context. The limit is approximate and does not apply to binary content such as PDFs." + }) + ), + "max_uses": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Uses", + "description": "Maximum number of times the tool can be used in the API request." + }) + ), + "name": Schema.Literal("web_fetch").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("web_fetch_20250910").annotate({ "title": "Type" }) +}).annotate({ "title": "WebFetchTool_20250910" }) +export type BetaWebFetchTool_20260209 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "allowed_domains"?: ReadonlyArray | null + readonly "blocked_domains"?: ReadonlyArray | null + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "citations"?: BetaRequestCitationsConfig | null + readonly "defer_loading"?: boolean + readonly "max_content_tokens"?: number | null + readonly "max_uses"?: number | null + readonly "name": "web_fetch" + readonly "strict"?: boolean + readonly "type": "web_fetch_20260209" +} +export const BetaWebFetchTool_20260209 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "allowed_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Allowed Domains", + "description": "List of domains to allow fetching from" + }) + ), + "blocked_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Blocked Domains", + "description": "List of domains to block fetching from" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey( + Schema.Union([BetaRequestCitationsConfig, Schema.Null]).annotate({ + "description": "Citations configuration for fetched documents. Citations are disabled by default." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "max_content_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Content Tokens", + "description": + "Maximum number of tokens used by including web page text content in the context. The limit is approximate and does not apply to binary content such as PDFs." + }) + ), + "max_uses": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Uses", + "description": "Maximum number of times the tool can be used in the API request." + }) + ), + "name": Schema.Literal("web_fetch").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("web_fetch_20260209").annotate({ "title": "Type" }) +}).annotate({ "title": "WebFetchTool_20260209" }) +export type BetaRequestCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "return_code": number + readonly "stderr": string + readonly "stdout": string + readonly "type": "code_execution_result" +} +export const BetaRequestCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(BetaRequestCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "stdout": Schema.String.annotate({ "title": "Stdout" }), + "type": Schema.Literal("code_execution_result").annotate({ "title": "Type" }) +}).annotate({ "title": "Result Block" }) +export type BetaRequestEncryptedCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "encrypted_stdout": string + readonly "return_code": number + readonly "stderr": string + readonly "type": "encrypted_code_execution_result" +} +export const BetaRequestEncryptedCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(BetaRequestCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "encrypted_stdout": Schema.String.annotate({ "title": "Encrypted Stdout" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "type": Schema.Literal("encrypted_code_execution_result").annotate({ "title": "Type" }) +}).annotate({ + "title": "RequestEncryptedCodeExecutionResultBlock", + "description": "Code execution result with encrypted stdout for PFC + web_search results." +}) +export type BetaRequestMCPServerURLDefinition = { + readonly "authorization_token"?: string | null + readonly "name": string + readonly "tool_configuration"?: BetaRequestMCPServerToolConfiguration | null + readonly "type": "url" + readonly "url": string +} +export const BetaRequestMCPServerURLDefinition = Schema.Struct({ + "authorization_token": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Authorization Token" }) + ), + "name": Schema.String.annotate({ "title": "Name" }), + "tool_configuration": Schema.optionalKey(Schema.Union([BetaRequestMCPServerToolConfiguration, Schema.Null])), + "type": Schema.Literal("url").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url" }) +}).annotate({ "title": "RequestMCPServerURLDefinition" }) +export type BetaRequestMCPToolResultBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "content"?: + | string + | ReadonlyArray< + { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "citations"?: + | ReadonlyArray< + | BetaRequestCharLocationCitation + | BetaRequestPageLocationCitation + | BetaRequestContentBlockLocationCitation + | BetaRequestWebSearchResultLocationCitation + | BetaRequestSearchResultLocationCitation + > + | null + readonly "text": string + readonly "type": "text" + } + > + readonly "is_error"?: boolean + readonly "tool_use_id": string + readonly "type": "mcp_tool_result" +} +export const BetaRequestMCPToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Array( + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([ + BetaRequestCharLocationCitation, + BetaRequestPageLocationCitation, + BetaRequestContentBlockLocationCitation, + BetaRequestWebSearchResultLocationCitation, + BetaRequestSearchResultLocationCitation + ], { mode: "oneOf" }) + ), + Schema.Null + ]).annotate({ "title": "Citations" }) + ), + "text": Schema.String.annotate({ "title": "Text" }).check(Schema.isMinLength(1)), + "type": Schema.Literal("text").annotate({ "title": "Type" }) + }).annotate({ "title": "beta_mcp_tool_result_block_param_content_item" }) + ).annotate({ "title": "beta_mcp_tool_result_block_param_content" }) + ]).annotate({ "title": "Content" }) + ), + "is_error": Schema.optionalKey(Schema.Boolean.annotate({ "title": "Is Error" })), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$")) + ), + "type": Schema.Literal("mcp_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestMCPToolResultBlock" }) +export type BetaRequestTextBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "citations"?: + | ReadonlyArray< + | BetaRequestCharLocationCitation + | BetaRequestPageLocationCitation + | BetaRequestContentBlockLocationCitation + | BetaRequestWebSearchResultLocationCitation + | BetaRequestSearchResultLocationCitation + > + | null + readonly "text": string + readonly "type": "text" +} +export const BetaRequestTextBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([ + BetaRequestCharLocationCitation, + BetaRequestPageLocationCitation, + BetaRequestContentBlockLocationCitation, + BetaRequestWebSearchResultLocationCitation, + BetaRequestSearchResultLocationCitation + ], { mode: "oneOf" }) + ), + Schema.Null + ]).annotate({ "title": "Citations" }) + ), + "text": Schema.String.annotate({ "title": "Text" }).check(Schema.isMinLength(1)), + "type": Schema.Literal("text").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextBlock" }) +export type BetaResponseBashCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "return_code": number + readonly "stderr": string + readonly "stdout": string + readonly "type": "bash_code_execution_result" +} +export const BetaResponseBashCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(BetaResponseBashCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "stdout": Schema.String.annotate({ "title": "Stdout" }), + "type": Schema.Literal("bash_code_execution_result").annotate({ + "title": "Type", + "default": "bash_code_execution_result" + }) +}).annotate({ "title": "ResponseBashCodeExecutionResultBlock" }) +export type BetaResponseDocumentBlock = { + readonly "citations": BetaResponseCitationsConfig | null + readonly "source": BetaBase64PDFSource | BetaPlainTextSource + readonly "title": string | null + readonly "type": "document" +} +export const BetaResponseDocumentBlock = Schema.Struct({ + "citations": Schema.Union([BetaResponseCitationsConfig, Schema.Null]).annotate({ + "description": "Citation configuration for the document", + "default": null + }), + "source": Schema.Union([BetaBase64PDFSource, BetaPlainTextSource], { mode: "oneOf" }).annotate({ "title": "Source" }), + "title": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Title", + "description": "The title of the document", + "default": null + }), + "type": Schema.Literal("document").annotate({ "title": "Type", "default": "document" }) +}).annotate({ "title": "ResponseDocumentBlock" }) +export type BetaResponseContextManagement = { + readonly "applied_edits": ReadonlyArray +} +export const BetaResponseContextManagement = Schema.Struct({ + "applied_edits": Schema.Array( + Schema.Union([BetaResponseClearToolUses20250919Edit, BetaResponseClearThinking20251015Edit], { mode: "oneOf" }) + ).annotate({ "title": "Applied Edits", "description": "List of context management edits that were applied." }) +}).annotate({ "title": "ResponseContextManagement" }) +export type BetaResponseCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "return_code": number + readonly "stderr": string + readonly "stdout": string + readonly "type": "code_execution_result" +} +export const BetaResponseCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(BetaResponseCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "stdout": Schema.String.annotate({ "title": "Stdout" }), + "type": Schema.Literal("code_execution_result").annotate({ "title": "Type", "default": "code_execution_result" }) +}).annotate({ "title": "ResponseCodeExecutionResultBlock" }) +export type BetaResponseEncryptedCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "encrypted_stdout": string + readonly "return_code": number + readonly "stderr": string + readonly "type": "encrypted_code_execution_result" +} +export const BetaResponseEncryptedCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(BetaResponseCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "encrypted_stdout": Schema.String.annotate({ "title": "Encrypted Stdout" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "type": Schema.Literal("encrypted_code_execution_result").annotate({ + "title": "Type", + "default": "encrypted_code_execution_result" + }) +}).annotate({ + "title": "ResponseEncryptedCodeExecutionResultBlock", + "description": "Code execution result with encrypted stdout for PFC + web_search results." +}) +export type BetaResponseToolSearchToolSearchResultBlock = { + readonly "tool_references": ReadonlyArray + readonly "type": "tool_search_tool_search_result" +} +export const BetaResponseToolSearchToolSearchResultBlock = Schema.Struct({ + "tool_references": Schema.Array(BetaResponseToolReferenceBlock).annotate({ "title": "Tool References" }), + "type": Schema.Literal("tool_search_tool_search_result").annotate({ + "title": "Type", + "default": "tool_search_tool_search_result" + }) +}).annotate({ "title": "ResponseToolSearchToolSearchResultBlock" }) +export type BetaCitationsDelta = { + readonly "citation": + | BetaResponseCharLocationCitation + | BetaResponsePageLocationCitation + | BetaResponseContentBlockLocationCitation + | BetaResponseWebSearchResultLocationCitation + | BetaResponseSearchResultLocationCitation + readonly "type": "citations_delta" +} +export const BetaCitationsDelta = Schema.Struct({ + "citation": Schema.Union([ + BetaResponseCharLocationCitation, + BetaResponsePageLocationCitation, + BetaResponseContentBlockLocationCitation, + BetaResponseWebSearchResultLocationCitation, + BetaResponseSearchResultLocationCitation + ], { mode: "oneOf" }).annotate({ "title": "Citation" }), + "type": Schema.Literal("citations_delta").annotate({ "title": "Type", "default": "citations_delta" }) +}).annotate({ "title": "CitationsDelta" }) +export type BetaResponseMCPToolResultBlock = { + readonly "content": + | string + | ReadonlyArray< + { + readonly "citations": + | ReadonlyArray< + | BetaResponseCharLocationCitation + | BetaResponsePageLocationCitation + | BetaResponseContentBlockLocationCitation + | BetaResponseWebSearchResultLocationCitation + | BetaResponseSearchResultLocationCitation + > + | null + readonly "text": string + readonly "type": "text" + } + > + readonly "is_error": boolean + readonly "tool_use_id": string + readonly "type": "mcp_tool_result" +} +export const BetaResponseMCPToolResultBlock = Schema.Struct({ + "content": Schema.Union([ + Schema.String, + Schema.Array( + Schema.Struct({ + "citations": Schema.Union([ + Schema.Array( + Schema.Union([ + BetaResponseCharLocationCitation, + BetaResponsePageLocationCitation, + BetaResponseContentBlockLocationCitation, + BetaResponseWebSearchResultLocationCitation, + BetaResponseSearchResultLocationCitation + ], { mode: "oneOf" }) + ), + Schema.Null + ]).annotate({ + "title": "Citations", + "description": + "Citations supporting the text block.\n\nThe type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.", + "default": null + }), + "text": Schema.String.annotate({ "title": "Text" }).check(Schema.isMinLength(0)).check( + Schema.isMaxLength(5000000) + ), + "type": Schema.Literal("text").annotate({ "title": "Type", "default": "text" }) + }).annotate({ "title": "beta_mcp_tool_result_block_content_item" }) + ).annotate({ "title": "beta_mcp_tool_result_block_content" }) + ]).annotate({ "title": "Content" }), + "is_error": Schema.Boolean.annotate({ "title": "Is Error", "default": false }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$")) + ), + "type": Schema.Literal("mcp_tool_result").annotate({ "title": "Type", "default": "mcp_tool_result" }) +}).annotate({ "title": "ResponseMCPToolResultBlock" }) +export type BetaResponseTextBlock = { + readonly "citations"?: + | ReadonlyArray< + | BetaResponseCharLocationCitation + | BetaResponsePageLocationCitation + | BetaResponseContentBlockLocationCitation + | BetaResponseWebSearchResultLocationCitation + | BetaResponseSearchResultLocationCitation + > + | null + readonly "text": string + readonly "type": "text" +} +export const BetaResponseTextBlock = Schema.Struct({ + "citations": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([ + BetaResponseCharLocationCitation, + BetaResponsePageLocationCitation, + BetaResponseContentBlockLocationCitation, + BetaResponseWebSearchResultLocationCitation, + BetaResponseSearchResultLocationCitation + ], { mode: "oneOf" }) + ), + Schema.Null + ]).annotate({ + "title": "Citations", + "description": + "Citations supporting the text block.\n\nThe type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.", + "default": null + }) + ), + "text": Schema.String.annotate({ "title": "Text" }).check(Schema.isMinLength(0)).check(Schema.isMaxLength(5000000)), + "type": Schema.Literal("text").annotate({ "title": "Type", "default": "text" }) +}).annotate({ "title": "ResponseTextBlock" }) +export type BetaRequestServerToolUseBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "caller"?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller_20260120 + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": + | "web_search" + | "web_fetch" + | "code_execution" + | "bash_code_execution" + | "text_editor_code_execution" + | "tool_search_tool_regex" + | "tool_search_tool_bm25" + readonly "type": "server_tool_use" +} +export const BetaRequestServerToolUseBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "caller": Schema.optionalKey( + Schema.Union([BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.Literals([ + "web_search", + "web_fetch", + "code_execution", + "bash_code_execution", + "text_editor_code_execution", + "tool_search_tool_regex", + "tool_search_tool_bm25" + ]).annotate({ "title": "Name" }), + "type": Schema.Literal("server_tool_use").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestServerToolUseBlock" }) +export type BetaResponseServerToolUseBlock = { + readonly "caller"?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller_20260120 + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": + | "web_search" + | "web_fetch" + | "code_execution" + | "bash_code_execution" + | "text_editor_code_execution" + | "tool_search_tool_regex" + | "tool_search_tool_bm25" + readonly "type": "server_tool_use" +} +export const BetaResponseServerToolUseBlock = Schema.Struct({ + "caller": Schema.optionalKey( + Schema.Union([BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.Literals([ + "web_search", + "web_fetch", + "code_execution", + "bash_code_execution", + "text_editor_code_execution", + "tool_search_tool_regex", + "tool_search_tool_bm25" + ]).annotate({ "title": "Name" }), + "type": Schema.Literal("server_tool_use").annotate({ "title": "Type", "default": "server_tool_use" }) +}).annotate({ "title": "ResponseServerToolUseBlock" }) +export type BetaResponseToolUseBlock = { + readonly "caller"?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller_20260120 + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": string + readonly "type": "tool_use" +} +export const BetaResponseToolUseBlock = Schema.Struct({ + "caller": Schema.optionalKey( + Schema.Union([BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.String.annotate({ "title": "Name" }).check(Schema.isMinLength(1)), + "type": Schema.Literal("tool_use").annotate({ "title": "Type", "default": "tool_use" }) +}).annotate({ "title": "ResponseToolUseBlock" }) +export type BetaContainer = { + readonly "expires_at": string + readonly "id": string + readonly "skills": ReadonlyArray | null +} +export const BetaContainer = Schema.Struct({ + "expires_at": Schema.String.annotate({ + "title": "Expires At", + "description": "The time at which the container will expire.", + "format": "date-time" + }), + "id": Schema.String.annotate({ "title": "Id", "description": "Identifier for the container used in this request" }), + "skills": Schema.Union([Schema.Array(BetaSkill), Schema.Null]).annotate({ + "title": "Skills", + "description": "Skills loaded in the container", + "default": null + }) +}).annotate({ + "title": "Container", + "description": "Information about the container used in the request (for the code execution tool)" +}) +export type BetaContainerParams = { + readonly "id"?: string | null + readonly "skills"?: ReadonlyArray | null +} +export const BetaContainerParams = Schema.Struct({ + "id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Id", "description": "Container id" }) + ), + "skills": Schema.optionalKey( + Schema.Union([Schema.Array(BetaSkillParams).check(Schema.isMaxLength(8)), Schema.Null]).annotate({ + "title": "Skills", + "description": "List of skills to load in the container" + }) + ) +}).annotate({ "title": "ContainerParams", "description": "Container parameters with skills to be loaded." }) +export type BetaListSkillVersionsResponse = { + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next_page": string | null +} +export const BetaListSkillVersionsResponse = Schema.Struct({ + "data": Schema.Array(BetaSkillVersion).annotate({ "title": "Data", "description": "List of skill versions." }), + "has_more": Schema.Boolean.annotate({ + "title": "Has More", + "description": "Indicates if there are more results in the requested page direction." + }), + "next_page": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Next Page", + "description": "Token to provide in as `page` in the subsequent request to retrieve the next page of data." + }) +}).annotate({ "title": "ListSkillVersionsResponse" }) +export type BetaRequestTextEditorCodeExecutionToolResultError = { + readonly "error_code": BetaTextEditorCodeExecutionToolResultErrorCode + readonly "error_message"?: string | null + readonly "type": "text_editor_code_execution_tool_result_error" +} +export const BetaRequestTextEditorCodeExecutionToolResultError = Schema.Struct({ + "error_code": BetaTextEditorCodeExecutionToolResultErrorCode, + "error_message": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Error Message" }) + ), + "type": Schema.Literal("text_editor_code_execution_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionToolResultError" }) +export type BetaResponseTextEditorCodeExecutionToolResultError = { + readonly "error_code": BetaTextEditorCodeExecutionToolResultErrorCode + readonly "error_message": string | null + readonly "type": "text_editor_code_execution_tool_result_error" +} +export const BetaResponseTextEditorCodeExecutionToolResultError = Schema.Struct({ + "error_code": BetaTextEditorCodeExecutionToolResultErrorCode, + "error_message": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Error Message", "default": null }), + "type": Schema.Literal("text_editor_code_execution_tool_result_error").annotate({ + "title": "Type", + "default": "text_editor_code_execution_tool_result_error" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionToolResultError" }) +export type BetaThinkingConfigParam = + | BetaThinkingConfigEnabled + | BetaThinkingConfigDisabled + | BetaThinkingConfigAdaptive +export const BetaThinkingConfigParam = Schema.Union([ + BetaThinkingConfigEnabled, + BetaThinkingConfigDisabled, + BetaThinkingConfigAdaptive +], { mode: "oneOf" }).annotate({ + "title": "Thinking", + "description": + "Configuration for enabling Claude's extended thinking.\n\nWhen enabled, responses include `thinking` content blocks showing Claude's thinking process before the final answer. Requires a minimum budget of 1,024 tokens and counts towards your `max_tokens` limit.\n\nSee [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details." +}) +export type BetaClearThinking20251015 = { + readonly "keep"?: BetaThinkingTurns | BetaAllThinkingTurns | "all" + readonly "type": "clear_thinking_20251015" +} +export const BetaClearThinking20251015 = Schema.Struct({ + "keep": Schema.optionalKey( + Schema.Union([Schema.Union([BetaThinkingTurns, BetaAllThinkingTurns], { mode: "oneOf" }), Schema.Literal("all")]) + .annotate({ + "title": "Keep", + "description": + "Number of most recent assistant turns to keep thinking blocks for. Older turns will have their thinking blocks removed." + }) + ), + "type": Schema.Literal("clear_thinking_20251015").annotate({ "title": "Type" }) +}).annotate({ "title": "ClearThinking20251015" }) +export type BetaToolChoice = BetaToolChoiceAuto | BetaToolChoiceAny | BetaToolChoiceTool | BetaToolChoiceNone +export const BetaToolChoice = Schema.Union([ + BetaToolChoiceAuto, + BetaToolChoiceAny, + BetaToolChoiceTool, + BetaToolChoiceNone +], { mode: "oneOf" }).annotate({ + "title": "Tool Choice", + "description": + "How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all." +}) +export type BetaRequestToolSearchToolResultError = { + readonly "error_code": BetaToolSearchToolResultErrorCode + readonly "type": "tool_search_tool_result_error" +} +export const BetaRequestToolSearchToolResultError = Schema.Struct({ + "error_code": BetaToolSearchToolResultErrorCode, + "type": Schema.Literal("tool_search_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestToolSearchToolResultError" }) +export type BetaResponseToolSearchToolResultError = { + readonly "error_code": BetaToolSearchToolResultErrorCode + readonly "error_message": string | null + readonly "type": "tool_search_tool_result_error" +} +export const BetaResponseToolSearchToolResultError = Schema.Struct({ + "error_code": BetaToolSearchToolResultErrorCode, + "error_message": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Error Message", "default": null }), + "type": Schema.Literal("tool_search_tool_result_error").annotate({ + "title": "Type", + "default": "tool_search_tool_result_error" + }) +}).annotate({ "title": "ResponseToolSearchToolResultError" }) +export type BetaClearToolUses20250919 = { + readonly "clear_at_least"?: BetaInputTokensClearAtLeast | null + readonly "clear_tool_inputs"?: boolean | ReadonlyArray | null + readonly "exclude_tools"?: ReadonlyArray | null + readonly "keep"?: BetaToolUsesKeep + readonly "trigger"?: BetaInputTokensTrigger | BetaToolUsesTrigger + readonly "type": "clear_tool_uses_20250919" +} +export const BetaClearToolUses20250919 = Schema.Struct({ + "clear_at_least": Schema.optionalKey( + Schema.Union([BetaInputTokensClearAtLeast, Schema.Null]).annotate({ + "description": + "Minimum number of tokens that must be cleared when triggered. Context will only be modified if at least this many tokens can be removed." + }) + ), + "clear_tool_inputs": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Clear Tool Inputs", + "description": "Whether to clear all tool inputs (bool) or specific tool inputs to clear (list)" + }) + ), + "exclude_tools": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Exclude Tools", + "description": "Tool names whose uses are preserved from clearing" + }) + ), + "keep": Schema.optionalKey( + Schema.Union([BetaToolUsesKeep], { mode: "oneOf" }).annotate({ + "title": "Keep", + "description": "Number of tool uses to retain in the conversation" + }) + ), + "trigger": Schema.optionalKey( + Schema.Union([BetaInputTokensTrigger, BetaToolUsesTrigger], { mode: "oneOf" }).annotate({ + "title": "Trigger", + "description": "Condition that triggers the context management strategy" + }) + ), + "type": Schema.Literal("clear_tool_uses_20250919").annotate({ "title": "Type" }) +}).annotate({ "title": "ClearToolUses20250919" }) +export type BetaRequestImageBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "source": BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource + readonly "type": "image" +} +export const BetaRequestImageBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "source": Schema.Union([BetaBase64ImageSource, BetaURLImageSource, BetaFileImageSource], { mode: "oneOf" }).annotate({ + "title": "Source" + }), + "type": Schema.Literal("image").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestImageBlock" }) +export type BetaWebSearchTool_20250305 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "allowed_domains"?: ReadonlyArray | null + readonly "blocked_domains"?: ReadonlyArray | null + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "max_uses"?: number | null + readonly "name": "web_search" + readonly "strict"?: boolean + readonly "type": "web_search_20250305" + readonly "user_location"?: BetaUserLocation | null +} +export const BetaWebSearchTool_20250305 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "allowed_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Allowed Domains", + "description": + "If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`." + }) + ), + "blocked_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Blocked Domains", + "description": + "If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`." + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "max_uses": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Uses", + "description": "Maximum number of times the tool can be used in the API request." + }) + ), + "name": Schema.Literal("web_search").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("web_search_20250305").annotate({ "title": "Type" }), + "user_location": Schema.optionalKey( + Schema.Union([BetaUserLocation, Schema.Null]).annotate({ + "description": "Parameters for the user's location. Used to provide more relevant search results." + }) + ) +}).annotate({ "title": "WebSearchTool_20250305" }) +export type BetaWebSearchTool_20260209 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "allowed_domains"?: ReadonlyArray | null + readonly "blocked_domains"?: ReadonlyArray | null + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "max_uses"?: number | null + readonly "name": "web_search" + readonly "strict"?: boolean + readonly "type": "web_search_20260209" + readonly "user_location"?: BetaUserLocation | null +} +export const BetaWebSearchTool_20260209 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "allowed_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Allowed Domains", + "description": + "If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`." + }) + ), + "blocked_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Blocked Domains", + "description": + "If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`." + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "max_uses": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Uses", + "description": "Maximum number of times the tool can be used in the API request." + }) + ), + "name": Schema.Literal("web_search").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("web_search_20260209").annotate({ "title": "Type" }), + "user_location": Schema.optionalKey( + Schema.Union([BetaUserLocation, Schema.Null]).annotate({ + "description": "Parameters for the user's location. Used to provide more relevant search results." + }) + ) +}).annotate({ "title": "WebSearchTool_20260209" }) +export type BetaRequestWebFetchToolResultError = { + readonly "error_code": BetaWebFetchToolResultErrorCode + readonly "type": "web_fetch_tool_result_error" +} +export const BetaRequestWebFetchToolResultError = Schema.Struct({ + "error_code": BetaWebFetchToolResultErrorCode, + "type": Schema.Literal("web_fetch_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestWebFetchToolResultError" }) +export type BetaResponseWebFetchToolResultError = { + readonly "error_code": BetaWebFetchToolResultErrorCode + readonly "type": "web_fetch_tool_result_error" +} +export const BetaResponseWebFetchToolResultError = Schema.Struct({ + "error_code": BetaWebFetchToolResultErrorCode, + "type": Schema.Literal("web_fetch_tool_result_error").annotate({ + "title": "Type", + "default": "web_fetch_tool_result_error" + }) +}).annotate({ "title": "ResponseWebFetchToolResultError" }) +export type BetaRequestWebSearchToolResultError = { + readonly "error_code": BetaWebSearchToolResultErrorCode + readonly "type": "web_search_tool_result_error" +} +export const BetaRequestWebSearchToolResultError = Schema.Struct({ + "error_code": BetaWebSearchToolResultErrorCode, + "type": Schema.Literal("web_search_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "Error" }) +export type BetaResponseWebSearchToolResultError = { + readonly "error_code": BetaWebSearchToolResultErrorCode + readonly "type": "web_search_tool_result_error" +} +export const BetaResponseWebSearchToolResultError = Schema.Struct({ + "error_code": BetaWebSearchToolResultErrorCode, + "type": Schema.Literal("web_search_tool_result_error").annotate({ + "title": "Type", + "default": "web_search_tool_result_error" + }) +}).annotate({ "title": "ResponseWebSearchToolResultError" }) +export type BetaListSkillsResponse = { + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next_page": string | null +} +export const BetaListSkillsResponse = Schema.Struct({ + "data": Schema.Array(Betaapi__schemas__skills__Skill).annotate({ "title": "Data", "description": "List of skills." }), + "has_more": Schema.Boolean.annotate({ + "title": "Has More", + "description": + "Whether there are more results available.\n\nIf `true`, there are additional results that can be fetched using the `next_page` token." + }), + "next_page": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Next Page", + "description": + "Token for fetching the next page of results.\n\nIf `null`, there are no more results available. Pass this value to the `page_token` parameter in the next request to get the next page." + }) +}).annotate({ "title": "ListSkillsResponse" }) +export type CodeExecutionTool_20250522 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "code_execution" + readonly "strict"?: boolean + readonly "type": "code_execution_20250522" +} +export const CodeExecutionTool_20250522 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("code_execution").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("code_execution_20250522").annotate({ "title": "Type" }) +}).annotate({ "title": "CodeExecutionTool_20250522" }) +export type CodeExecutionTool_20250825 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "code_execution" + readonly "strict"?: boolean + readonly "type": "code_execution_20250825" +} +export const CodeExecutionTool_20250825 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("code_execution").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("code_execution_20250825").annotate({ "title": "Type" }) +}).annotate({ "title": "CodeExecutionTool_20250825" }) +export type CodeExecutionTool_20260120 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "code_execution" + readonly "strict"?: boolean + readonly "type": "code_execution_20260120" +} +export const CodeExecutionTool_20260120 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("code_execution").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("code_execution_20260120").annotate({ "title": "Type" }) +}).annotate({ + "title": "CodeExecutionTool_20260120", + "description": "Code execution tool with REPL state persistence (daemon mode + gVisor checkpoint)." +}) +export type RequestContainerUploadBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "file_id": string + readonly "type": "container_upload" +} +export const RequestContainerUploadBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "file_id": Schema.String.annotate({ "title": "File Id" }), + "type": Schema.Literal("container_upload").annotate({ "title": "Type" }) +}).annotate({ + "title": "RequestContainerUploadBlock", + "description": + "A content block that represents a file to be uploaded to the container\nFiles uploaded via this block will be available in the container's input directory." +}) +export type RequestToolReferenceBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "tool_name": string + readonly "type": "tool_reference" +} +export const RequestToolReferenceBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "tool_name": Schema.String.annotate({ "title": "Tool Name" }).check(Schema.isMinLength(1)).check( + Schema.isMaxLength(256) + ).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]{1,256}$"))), + "type": Schema.Literal("tool_reference").annotate({ "title": "Type" }) +}).annotate({ + "title": "RequestToolReferenceBlock", + "description": "Tool reference block that can be included in tool_result content." +}) +export type ToolSearchToolBM25_20251119 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "tool_search_tool_bm25" + readonly "strict"?: boolean + readonly "type": "tool_search_tool_bm25_20251119" | "tool_search_tool_bm25" +} +export const ToolSearchToolBM25_20251119 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("tool_search_tool_bm25").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literals(["tool_search_tool_bm25_20251119", "tool_search_tool_bm25"]).annotate({ "title": "Type" }) +}).annotate({ "title": "ToolSearchToolBM25_20251119" }) +export type ToolSearchToolRegex_20251119 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "name": "tool_search_tool_regex" + readonly "strict"?: boolean + readonly "type": "tool_search_tool_regex_20251119" | "tool_search_tool_regex" +} +export const ToolSearchToolRegex_20251119 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "name": Schema.Literal("tool_search_tool_regex").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literals(["tool_search_tool_regex_20251119", "tool_search_tool_regex"]).annotate({ "title": "Type" }) +}).annotate({ "title": "ToolSearchToolRegex_20251119" }) +export type RequestCodeExecutionToolResultError = { + readonly "error_code": CodeExecutionToolResultErrorCode + readonly "type": "code_execution_tool_result_error" +} +export const RequestCodeExecutionToolResultError = Schema.Struct({ + "error_code": CodeExecutionToolResultErrorCode, + "type": Schema.Literal("code_execution_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestCodeExecutionToolResultError" }) +export type ResponseCodeExecutionToolResultError = { + readonly "error_code": CodeExecutionToolResultErrorCode + readonly "type": "code_execution_tool_result_error" +} +export const ResponseCodeExecutionToolResultError = Schema.Struct({ + "error_code": CodeExecutionToolResultErrorCode, + "type": Schema.Literal("code_execution_tool_result_error").annotate({ + "title": "Type", + "default": "code_execution_tool_result_error" + }) +}).annotate({ "title": "ResponseCodeExecutionToolResultError" }) +export type FileListResponse = { + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "has_more"?: boolean + readonly "last_id"?: string | null +} +export const FileListResponse = Schema.Struct({ + "data": Schema.Array(FileMetadataSchema).annotate({ + "title": "Data", + "description": "List of file metadata objects." + }), + "first_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "First Id", + "description": "ID of the first file in this page of results." + }) + ), + "has_more": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Has More", + "description": "Whether there are more results available.", + "default": false + }) + ), + "last_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Last Id", + "description": "ID of the last file in this page of results." + }) + ) +}).annotate({ "title": "FileListResponse" }) +export type BashTool_20250124 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: JsonValue }> + readonly "name": "bash" + readonly "strict"?: boolean + readonly "type": "bash_20250124" +} +export const BashTool_20250124 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, JsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("bash").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("bash_20250124").annotate({ "title": "Type" }) +}).annotate({ "title": "BashTool_20250124" }) +export type MemoryTool_20250818 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: JsonValue }> + readonly "name": "memory" + readonly "strict"?: boolean + readonly "type": "memory_20250818" +} +export const MemoryTool_20250818 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, JsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("memory").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("memory_20250818").annotate({ "title": "Type" }) +}).annotate({ "title": "MemoryTool_20250818" }) +export type TextEditor_20250124 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: JsonValue }> + readonly "name": "str_replace_editor" + readonly "strict"?: boolean + readonly "type": "text_editor_20250124" +} +export const TextEditor_20250124 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, JsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("str_replace_editor").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("text_editor_20250124").annotate({ "title": "Type" }) +}).annotate({ "title": "TextEditor_20250124" }) +export type TextEditor_20250429 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: JsonValue }> + readonly "name": "str_replace_based_edit_tool" + readonly "strict"?: boolean + readonly "type": "text_editor_20250429" +} +export const TextEditor_20250429 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, JsonValue)).annotate({ "title": "Input Examples" }) + ), + "name": Schema.Literal("str_replace_based_edit_tool").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("text_editor_20250429").annotate({ "title": "Type" }) +}).annotate({ "title": "TextEditor_20250429" }) +export type TextEditor_20250728 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: JsonValue }> + readonly "max_characters"?: number | null + readonly "name": "str_replace_based_edit_tool" + readonly "strict"?: boolean + readonly "type": "text_editor_20250728" +} +export const TextEditor_20250728 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, JsonValue)).annotate({ "title": "Input Examples" }) + ), + "max_characters": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), Schema.Null]).annotate({ + "title": "Max Characters", + "description": + "Maximum number of characters to display when viewing a file. If not specified, defaults to displaying the full file." + }) + ), + "name": Schema.Literal("str_replace_based_edit_tool").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("text_editor_20250728").annotate({ "title": "Type" }) +}).annotate({ "title": "TextEditor_20250728" }) +export type Tool = { + readonly "type"?: null | "custom" + readonly "description"?: string + readonly "name": string + readonly "input_schema": { + readonly "properties"?: { readonly [x: string]: Schema.Json } | null + readonly "required"?: ReadonlyArray | null + readonly "type": "object" + readonly [x: string]: Schema.Json + } + readonly "cache_control"?: CacheControlEphemeral | null + readonly "strict"?: boolean + readonly "eager_input_streaming"?: boolean | null + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "defer_loading"?: boolean + readonly "input_examples"?: ReadonlyArray<{ readonly [x: string]: JsonValue }> +} +export const Tool = Schema.Struct({ + "type": Schema.optionalKey(Schema.Union([Schema.Null, Schema.Literal("custom")]).annotate({ "title": "Type" })), + "description": Schema.optionalKey(Schema.String.annotate({ + "title": "Description", + "description": + "Description of what this tool does.\n\nTool descriptions should be as detailed as possible. The more information that the model has about what the tool is and how to use it, the better it will perform. You can use natural language descriptions to reinforce important aspects of the tool input JSON schema." + })), + "name": Schema.String.annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(128)).check( + Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]{1,128}$")) + ), + "input_schema": Schema.StructWithRest( + Schema.Struct({ + "properties": Schema.optionalKey( + Schema.Union([Schema.Record(Schema.String, Schema.Json), Schema.Null]).annotate({ "title": "Properties" }) + ), + "required": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ "title": "Required" }) + ), + "type": Schema.Literal("object").annotate({ "title": "Type" }) + }), + [Schema.Record(Schema.String, Schema.Json)] + ).annotate({ + "title": "InputSchema", + "description": + "[JSON schema](https://json-schema.org/draft/2020-12) for this tool's input.\n\nThis defines the shape of the `input` that your tool accepts and that the model will produce." + }), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "eager_input_streaming": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "title": "Eager Input Streaming", + "description": + "Enable eager input streaming for this tool. When true, tool input parameters will be streamed incrementally as they are generated, and types will be inferred on-the-fly rather than buffering the full JSON output. When false, streaming is disabled for this tool even if the fine-grained-tool-streaming beta is active. When null (default), uses the default behavior based on beta headers." + }) + ), + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "input_examples": Schema.optionalKey( + Schema.Array(Schema.Record(Schema.String, JsonValue)).annotate({ "title": "Input Examples" }) + ) +}).annotate({ "title": "Tool" }) +export type ListResponse_MessageBatch_ = { + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "has_more": boolean + readonly "last_id": string | null +} +export const ListResponse_MessageBatch_ = Schema.Struct({ + "data": Schema.Array(MessageBatch).annotate({ "title": "Data" }), + "first_id": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "First Id", + "description": "First ID in the `data` list. Can be used as the `before_id` for the previous page." + }), + "has_more": Schema.Boolean.annotate({ + "title": "Has More", + "description": "Indicates if there are more results in the requested page direction." + }), + "last_id": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Last Id", + "description": "Last ID in the `data` list. Can be used as the `after_id` for the next page." + }) +}).annotate({ "title": "ListResponse[MessageBatch]" }) +export type ListResponse_ModelInfo_ = { + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "has_more": boolean + readonly "last_id": string | null +} +export const ListResponse_ModelInfo_ = Schema.Struct({ + "data": Schema.Array(ModelInfo).annotate({ "title": "Data" }), + "first_id": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "First Id", + "description": "First ID in the `data` list. Can be used as the `before_id` for the previous page." + }), + "has_more": Schema.Boolean.annotate({ + "title": "Has More", + "description": "Indicates if there are more results in the requested page direction." + }), + "last_id": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Last Id", + "description": "Last ID in the `data` list. Can be used as the `after_id` for the next page." + }) +}).annotate({ "title": "ListResponse[ModelInfo]" }) +export type ErrorResponse = { + readonly "error": + | InvalidRequestError + | AuthenticationError + | BillingError + | PermissionError + | NotFoundError + | RateLimitError + | GatewayTimeoutError + | APIError + | OverloadedError + readonly "request_id": string | null + readonly "type": "error" +} +export const ErrorResponse = Schema.Struct({ + "error": Schema.Union([ + InvalidRequestError, + AuthenticationError, + BillingError, + PermissionError, + NotFoundError, + RateLimitError, + GatewayTimeoutError, + APIError, + OverloadedError + ], { mode: "oneOf" }).annotate({ "title": "Error" }), + "request_id": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Request Id", "default": null }), + "type": Schema.Literal("error").annotate({ "title": "Type", "default": "error" }) +}).annotate({ "title": "ErrorResponse" }) +export type RequestBashCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "return_code": number + readonly "stderr": string + readonly "stdout": string + readonly "type": "bash_code_execution_result" +} +export const RequestBashCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(RequestBashCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "stdout": Schema.String.annotate({ "title": "Stdout" }), + "type": Schema.Literal("bash_code_execution_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestBashCodeExecutionResultBlock" }) +export type WebFetchTool_20250910 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "allowed_domains"?: ReadonlyArray | null + readonly "blocked_domains"?: ReadonlyArray | null + readonly "cache_control"?: CacheControlEphemeral | null + readonly "citations"?: RequestCitationsConfig | null + readonly "defer_loading"?: boolean + readonly "max_content_tokens"?: number | null + readonly "max_uses"?: number | null + readonly "name": "web_fetch" + readonly "strict"?: boolean + readonly "type": "web_fetch_20250910" +} +export const WebFetchTool_20250910 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "allowed_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Allowed Domains", + "description": "List of domains to allow fetching from" + }) + ), + "blocked_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Blocked Domains", + "description": "List of domains to block fetching from" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey( + Schema.Union([RequestCitationsConfig, Schema.Null]).annotate({ + "description": "Citations configuration for fetched documents. Citations are disabled by default." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "max_content_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Content Tokens", + "description": + "Maximum number of tokens used by including web page text content in the context. The limit is approximate and does not apply to binary content such as PDFs." + }) + ), + "max_uses": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Uses", + "description": "Maximum number of times the tool can be used in the API request." + }) + ), + "name": Schema.Literal("web_fetch").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("web_fetch_20250910").annotate({ "title": "Type" }) +}).annotate({ "title": "WebFetchTool_20250910" }) +export type WebFetchTool_20260209 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "allowed_domains"?: ReadonlyArray | null + readonly "blocked_domains"?: ReadonlyArray | null + readonly "cache_control"?: CacheControlEphemeral | null + readonly "citations"?: RequestCitationsConfig | null + readonly "defer_loading"?: boolean + readonly "max_content_tokens"?: number | null + readonly "max_uses"?: number | null + readonly "name": "web_fetch" + readonly "strict"?: boolean + readonly "type": "web_fetch_20260209" +} +export const WebFetchTool_20260209 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "allowed_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Allowed Domains", + "description": "List of domains to allow fetching from" + }) + ), + "blocked_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Blocked Domains", + "description": "List of domains to block fetching from" + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey( + Schema.Union([RequestCitationsConfig, Schema.Null]).annotate({ + "description": "Citations configuration for fetched documents. Citations are disabled by default." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "max_content_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Content Tokens", + "description": + "Maximum number of tokens used by including web page text content in the context. The limit is approximate and does not apply to binary content such as PDFs." + }) + ), + "max_uses": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Uses", + "description": "Maximum number of times the tool can be used in the API request." + }) + ), + "name": Schema.Literal("web_fetch").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("web_fetch_20260209").annotate({ "title": "Type" }) +}).annotate({ "title": "WebFetchTool_20260209" }) +export type RequestCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "return_code": number + readonly "stderr": string + readonly "stdout": string + readonly "type": "code_execution_result" +} +export const RequestCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(RequestCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "stdout": Schema.String.annotate({ "title": "Stdout" }), + "type": Schema.Literal("code_execution_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestCodeExecutionResultBlock" }) +export type RequestEncryptedCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "encrypted_stdout": string + readonly "return_code": number + readonly "stderr": string + readonly "type": "encrypted_code_execution_result" +} +export const RequestEncryptedCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(RequestCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "encrypted_stdout": Schema.String.annotate({ "title": "Encrypted Stdout" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "type": Schema.Literal("encrypted_code_execution_result").annotate({ "title": "Type" }) +}).annotate({ + "title": "RequestEncryptedCodeExecutionResultBlock", + "description": "Code execution result with encrypted stdout for PFC + web_search results." +}) +export type RequestTextBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "citations"?: + | ReadonlyArray< + | RequestCharLocationCitation + | RequestPageLocationCitation + | RequestContentBlockLocationCitation + | RequestWebSearchResultLocationCitation + | RequestSearchResultLocationCitation + > + | null + readonly "text": string + readonly "type": "text" +} +export const RequestTextBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([ + RequestCharLocationCitation, + RequestPageLocationCitation, + RequestContentBlockLocationCitation, + RequestWebSearchResultLocationCitation, + RequestSearchResultLocationCitation + ], { mode: "oneOf" }) + ), + Schema.Null + ]).annotate({ "title": "Citations" }) + ), + "text": Schema.String.annotate({ "title": "Text" }).check(Schema.isMinLength(1)), + "type": Schema.Literal("text").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextBlock" }) +export type ResponseBashCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "return_code": number + readonly "stderr": string + readonly "stdout": string + readonly "type": "bash_code_execution_result" +} +export const ResponseBashCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(ResponseBashCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "stdout": Schema.String.annotate({ "title": "Stdout" }), + "type": Schema.Literal("bash_code_execution_result").annotate({ + "title": "Type", + "default": "bash_code_execution_result" + }) +}).annotate({ "title": "ResponseBashCodeExecutionResultBlock" }) +export type ResponseDocumentBlock = { + readonly "citations": ResponseCitationsConfig | null + readonly "source": Base64PDFSource | PlainTextSource + readonly "title": string | null + readonly "type": "document" +} +export const ResponseDocumentBlock = Schema.Struct({ + "citations": Schema.Union([ResponseCitationsConfig, Schema.Null]).annotate({ + "description": "Citation configuration for the document", + "default": null + }), + "source": Schema.Union([Base64PDFSource, PlainTextSource], { mode: "oneOf" }).annotate({ "title": "Source" }), + "title": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Title", + "description": "The title of the document", + "default": null + }), + "type": Schema.Literal("document").annotate({ "title": "Type", "default": "document" }) +}).annotate({ "title": "ResponseDocumentBlock" }) +export type ResponseCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "return_code": number + readonly "stderr": string + readonly "stdout": string + readonly "type": "code_execution_result" +} +export const ResponseCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(ResponseCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "stdout": Schema.String.annotate({ "title": "Stdout" }), + "type": Schema.Literal("code_execution_result").annotate({ "title": "Type", "default": "code_execution_result" }) +}).annotate({ "title": "ResponseCodeExecutionResultBlock" }) +export type ResponseEncryptedCodeExecutionResultBlock = { + readonly "content": ReadonlyArray + readonly "encrypted_stdout": string + readonly "return_code": number + readonly "stderr": string + readonly "type": "encrypted_code_execution_result" +} +export const ResponseEncryptedCodeExecutionResultBlock = Schema.Struct({ + "content": Schema.Array(ResponseCodeExecutionOutputBlock).annotate({ "title": "Content" }), + "encrypted_stdout": Schema.String.annotate({ "title": "Encrypted Stdout" }), + "return_code": Schema.Number.annotate({ "title": "Return Code" }).check(Schema.isInt()), + "stderr": Schema.String.annotate({ "title": "Stderr" }), + "type": Schema.Literal("encrypted_code_execution_result").annotate({ + "title": "Type", + "default": "encrypted_code_execution_result" + }) +}).annotate({ + "title": "ResponseEncryptedCodeExecutionResultBlock", + "description": "Code execution result with encrypted stdout for PFC + web_search results." +}) +export type ResponseToolSearchToolSearchResultBlock = { + readonly "tool_references": ReadonlyArray + readonly "type": "tool_search_tool_search_result" +} +export const ResponseToolSearchToolSearchResultBlock = Schema.Struct({ + "tool_references": Schema.Array(ResponseToolReferenceBlock).annotate({ "title": "Tool References" }), + "type": Schema.Literal("tool_search_tool_search_result").annotate({ + "title": "Type", + "default": "tool_search_tool_search_result" + }) +}).annotate({ "title": "ResponseToolSearchToolSearchResultBlock" }) +export type CitationsDelta = { + readonly "citation": + | ResponseCharLocationCitation + | ResponsePageLocationCitation + | ResponseContentBlockLocationCitation + | ResponseWebSearchResultLocationCitation + | ResponseSearchResultLocationCitation + readonly "type": "citations_delta" +} +export const CitationsDelta = Schema.Struct({ + "citation": Schema.Union([ + ResponseCharLocationCitation, + ResponsePageLocationCitation, + ResponseContentBlockLocationCitation, + ResponseWebSearchResultLocationCitation, + ResponseSearchResultLocationCitation + ], { mode: "oneOf" }).annotate({ "title": "Citation" }), + "type": Schema.Literal("citations_delta").annotate({ "title": "Type", "default": "citations_delta" }) +}).annotate({ "title": "CitationsDelta" }) +export type ResponseTextBlock = { + readonly "citations"?: + | ReadonlyArray< + | ResponseCharLocationCitation + | ResponsePageLocationCitation + | ResponseContentBlockLocationCitation + | ResponseWebSearchResultLocationCitation + | ResponseSearchResultLocationCitation + > + | null + readonly "text": string + readonly "type": "text" +} +export const ResponseTextBlock = Schema.Struct({ + "citations": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([ + ResponseCharLocationCitation, + ResponsePageLocationCitation, + ResponseContentBlockLocationCitation, + ResponseWebSearchResultLocationCitation, + ResponseSearchResultLocationCitation + ], { mode: "oneOf" }) + ), + Schema.Null + ]).annotate({ + "title": "Citations", + "description": + "Citations supporting the text block.\n\nThe type of citation returned will depend on the type of document being cited. Citing a PDF results in `page_location`, plain text results in `char_location`, and content document results in `content_block_location`.", + "default": null + }) + ), + "text": Schema.String.annotate({ "title": "Text" }).check(Schema.isMinLength(0)).check(Schema.isMaxLength(5000000)), + "type": Schema.Literal("text").annotate({ "title": "Type", "default": "text" }) +}).annotate({ "title": "ResponseTextBlock" }) +export type RequestServerToolUseBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "caller"?: DirectCaller | ServerToolCaller | ServerToolCaller_20260120 + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": + | "web_search" + | "web_fetch" + | "code_execution" + | "bash_code_execution" + | "text_editor_code_execution" + | "tool_search_tool_regex" + | "tool_search_tool_bm25" + readonly "type": "server_tool_use" +} +export const RequestServerToolUseBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "caller": Schema.optionalKey( + Schema.Union([DirectCaller, ServerToolCaller, ServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.Literals([ + "web_search", + "web_fetch", + "code_execution", + "bash_code_execution", + "text_editor_code_execution", + "tool_search_tool_regex", + "tool_search_tool_bm25" + ]).annotate({ "title": "Name" }), + "type": Schema.Literal("server_tool_use").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestServerToolUseBlock" }) +export type ResponseServerToolUseBlock = { + readonly "caller": DirectCaller | ServerToolCaller | ServerToolCaller_20260120 + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": + | "web_search" + | "web_fetch" + | "code_execution" + | "bash_code_execution" + | "text_editor_code_execution" + | "tool_search_tool_regex" + | "tool_search_tool_bm25" + readonly "type": "server_tool_use" +} +export const ResponseServerToolUseBlock = Schema.Struct({ + "caller": Schema.Union([DirectCaller, ServerToolCaller, ServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller", + "default": { "type": "direct" } + }), + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.Literals([ + "web_search", + "web_fetch", + "code_execution", + "bash_code_execution", + "text_editor_code_execution", + "tool_search_tool_regex", + "tool_search_tool_bm25" + ]).annotate({ "title": "Name" }), + "type": Schema.Literal("server_tool_use").annotate({ "title": "Type", "default": "server_tool_use" }) +}).annotate({ "title": "ResponseServerToolUseBlock" }) +export type ResponseToolUseBlock = { + readonly "caller": DirectCaller | ServerToolCaller | ServerToolCaller_20260120 + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": string + readonly "type": "tool_use" +} +export const ResponseToolUseBlock = Schema.Struct({ + "caller": Schema.Union([DirectCaller, ServerToolCaller, ServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller", + "default": { "type": "direct" } + }), + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.String.annotate({ "title": "Name" }).check(Schema.isMinLength(1)), + "type": Schema.Literal("tool_use").annotate({ "title": "Type", "default": "tool_use" }) +}).annotate({ "title": "ResponseToolUseBlock" }) +export type ListSkillsResponse = { + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next_page": string | null +} +export const ListSkillsResponse = Schema.Struct({ + "data": Schema.Array(Skill).annotate({ "title": "Data", "description": "List of skills." }), + "has_more": Schema.Boolean.annotate({ + "title": "Has More", + "description": + "Whether there are more results available.\n\nIf `true`, there are additional results that can be fetched using the `next_page` token." + }), + "next_page": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Next Page", + "description": + "Token for fetching the next page of results.\n\nIf `null`, there are no more results available. Pass this value to the `page_token` parameter in the next request to get the next page." + }) +}).annotate({ "title": "ListSkillsResponse" }) +export type ListSkillVersionsResponse = { + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next_page": string | null +} +export const ListSkillVersionsResponse = Schema.Struct({ + "data": Schema.Array(SkillVersion).annotate({ "title": "Data", "description": "List of skill versions." }), + "has_more": Schema.Boolean.annotate({ + "title": "Has More", + "description": "Indicates if there are more results in the requested page direction." + }), + "next_page": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Next Page", + "description": "Token to provide in as `page` in the subsequent request to retrieve the next page of data." + }) +}).annotate({ "title": "ListSkillVersionsResponse" }) +export type RequestTextEditorCodeExecutionToolResultError = { + readonly "error_code": TextEditorCodeExecutionToolResultErrorCode + readonly "error_message"?: string | null + readonly "type": "text_editor_code_execution_tool_result_error" +} +export const RequestTextEditorCodeExecutionToolResultError = Schema.Struct({ + "error_code": TextEditorCodeExecutionToolResultErrorCode, + "error_message": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Error Message" }) + ), + "type": Schema.Literal("text_editor_code_execution_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionToolResultError" }) +export type ResponseTextEditorCodeExecutionToolResultError = { + readonly "error_code": TextEditorCodeExecutionToolResultErrorCode + readonly "error_message": string | null + readonly "type": "text_editor_code_execution_tool_result_error" +} +export const ResponseTextEditorCodeExecutionToolResultError = Schema.Struct({ + "error_code": TextEditorCodeExecutionToolResultErrorCode, + "error_message": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Error Message", "default": null }), + "type": Schema.Literal("text_editor_code_execution_tool_result_error").annotate({ + "title": "Type", + "default": "text_editor_code_execution_tool_result_error" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionToolResultError" }) +export type ThinkingConfigParam = ThinkingConfigEnabled | ThinkingConfigDisabled | ThinkingConfigAdaptive +export const ThinkingConfigParam = Schema.Union( + [ThinkingConfigEnabled, ThinkingConfigDisabled, ThinkingConfigAdaptive], + { mode: "oneOf" } +).annotate({ + "title": "Thinking", + "description": + "Configuration for enabling Claude's extended thinking.\n\nWhen enabled, responses include `thinking` content blocks showing Claude's thinking process before the final answer. Requires a minimum budget of 1,024 tokens and counts towards your `max_tokens` limit.\n\nSee [extended thinking](https://docs.claude.com/en/docs/build-with-claude/extended-thinking) for details." +}) +export type ToolChoice = ToolChoiceAuto | ToolChoiceAny | ToolChoiceTool | ToolChoiceNone +export const ToolChoice = Schema.Union([ToolChoiceAuto, ToolChoiceAny, ToolChoiceTool, ToolChoiceNone], { + mode: "oneOf" +}).annotate({ + "title": "Tool Choice", + "description": + "How the model should use the provided tools. The model can use a specific tool, any available tool, decide by itself, or not use tools at all." +}) +export type RequestToolSearchToolResultError = { + readonly "error_code": ToolSearchToolResultErrorCode + readonly "type": "tool_search_tool_result_error" +} +export const RequestToolSearchToolResultError = Schema.Struct({ + "error_code": ToolSearchToolResultErrorCode, + "type": Schema.Literal("tool_search_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestToolSearchToolResultError" }) +export type ResponseToolSearchToolResultError = { + readonly "error_code": ToolSearchToolResultErrorCode + readonly "error_message": string | null + readonly "type": "tool_search_tool_result_error" +} +export const ResponseToolSearchToolResultError = Schema.Struct({ + "error_code": ToolSearchToolResultErrorCode, + "error_message": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Error Message", "default": null }), + "type": Schema.Literal("tool_search_tool_result_error").annotate({ + "title": "Type", + "default": "tool_search_tool_result_error" + }) +}).annotate({ "title": "ResponseToolSearchToolResultError" }) +export type RequestImageBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "source": Base64ImageSource | URLImageSource + readonly "type": "image" +} +export const RequestImageBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "source": Schema.Union([Base64ImageSource, URLImageSource], { mode: "oneOf" }).annotate({ "title": "Source" }), + "type": Schema.Literal("image").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestImageBlock" }) +export type WebSearchTool_20250305 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "allowed_domains"?: ReadonlyArray | null + readonly "blocked_domains"?: ReadonlyArray | null + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "max_uses"?: number | null + readonly "name": "web_search" + readonly "strict"?: boolean + readonly "type": "web_search_20250305" + readonly "user_location"?: UserLocation | null +} +export const WebSearchTool_20250305 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "allowed_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Allowed Domains", + "description": + "If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`." + }) + ), + "blocked_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Blocked Domains", + "description": + "If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`." + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "max_uses": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Uses", + "description": "Maximum number of times the tool can be used in the API request." + }) + ), + "name": Schema.Literal("web_search").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("web_search_20250305").annotate({ "title": "Type" }), + "user_location": Schema.optionalKey( + Schema.Union([UserLocation, Schema.Null]).annotate({ + "description": "Parameters for the user's location. Used to provide more relevant search results." + }) + ) +}).annotate({ "title": "WebSearchTool_20250305" }) +export type WebSearchTool_20260209 = { + readonly "allowed_callers"?: ReadonlyArray<"direct" | "code_execution_20250825" | "code_execution_20260120"> + readonly "allowed_domains"?: ReadonlyArray | null + readonly "blocked_domains"?: ReadonlyArray | null + readonly "cache_control"?: CacheControlEphemeral | null + readonly "defer_loading"?: boolean + readonly "max_uses"?: number | null + readonly "name": "web_search" + readonly "strict"?: boolean + readonly "type": "web_search_20260209" + readonly "user_location"?: UserLocation | null +} +export const WebSearchTool_20260209 = Schema.Struct({ + "allowed_callers": Schema.optionalKey( + Schema.Array(Schema.Literals(["direct", "code_execution_20250825", "code_execution_20260120"])).annotate({ + "title": "Allowed Callers" + }) + ), + "allowed_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Allowed Domains", + "description": + "If provided, only these domains will be included in results. Cannot be used alongside `blocked_domains`." + }) + ), + "blocked_domains": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "title": "Blocked Domains", + "description": + "If provided, these domains will never appear in results. Cannot be used alongside `allowed_domains`." + }) + ), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Defer Loading", + "description": + "If true, tool will not be included in initial system prompt. Only loaded when returned via tool_reference from tool search." + }) + ), + "max_uses": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThan(0)), Schema.Null]).annotate({ + "title": "Max Uses", + "description": "Maximum number of times the tool can be used in the API request." + }) + ), + "name": Schema.Literal("web_search").annotate({ + "title": "Name", + "description": "Name of the tool.\n\nThis is how the tool will be called by the model and in `tool_use` blocks." + }), + "strict": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Strict", + "description": "When true, guarantees schema validation on tool names and inputs" + }) + ), + "type": Schema.Literal("web_search_20260209").annotate({ "title": "Type" }), + "user_location": Schema.optionalKey( + Schema.Union([UserLocation, Schema.Null]).annotate({ + "description": "Parameters for the user's location. Used to provide more relevant search results." + }) + ) +}).annotate({ "title": "WebSearchTool_20260209" }) +export type RequestWebFetchToolResultError = { + readonly "error_code": WebFetchToolResultErrorCode + readonly "type": "web_fetch_tool_result_error" +} +export const RequestWebFetchToolResultError = Schema.Struct({ + "error_code": WebFetchToolResultErrorCode, + "type": Schema.Literal("web_fetch_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestWebFetchToolResultError" }) +export type ResponseWebFetchToolResultError = { + readonly "error_code": WebFetchToolResultErrorCode + readonly "type": "web_fetch_tool_result_error" +} +export const ResponseWebFetchToolResultError = Schema.Struct({ + "error_code": WebFetchToolResultErrorCode, + "type": Schema.Literal("web_fetch_tool_result_error").annotate({ + "title": "Type", + "default": "web_fetch_tool_result_error" + }) +}).annotate({ "title": "ResponseWebFetchToolResultError" }) +export type RequestWebSearchToolResultError = { + readonly "error_code": WebSearchToolResultErrorCode + readonly "type": "web_search_tool_result_error" +} +export const RequestWebSearchToolResultError = Schema.Struct({ + "error_code": WebSearchToolResultErrorCode, + "type": Schema.Literal("web_search_tool_result_error").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestWebSearchToolResultError" }) +export type ResponseWebSearchToolResultError = { + readonly "error_code": WebSearchToolResultErrorCode + readonly "type": "web_search_tool_result_error" +} +export const ResponseWebSearchToolResultError = Schema.Struct({ + "error_code": WebSearchToolResultErrorCode, + "type": Schema.Literal("web_search_tool_result_error").annotate({ + "title": "Type", + "default": "web_search_tool_result_error" + }) +}).annotate({ "title": "ResponseWebSearchToolResultError" }) +export type MessageDelta = { + readonly "container": Container | null + readonly "stop_reason": StopReason | null + readonly "stop_sequence": string | null +} +export const MessageDelta = Schema.Struct({ + "container": Schema.Union([Container, Schema.Null]).annotate({ + "description": + "Information about the container used in this request.\n\nThis will be non-null if a container tool (e.g. code execution) was used.", + "default": null + }), + "stop_reason": Schema.Union([StopReason, Schema.Null]).annotate({ "title": "Stop Reason", "default": null }), + "stop_sequence": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Stop Sequence", "default": null }) +}).annotate({ "title": "MessageDelta" }) +export type CompletionRequest = { + readonly "model": Model + readonly "prompt": string + readonly "max_tokens_to_sample": number + readonly "stop_sequences"?: ReadonlyArray + readonly "temperature"?: number + readonly "top_p"?: number + readonly "top_k"?: number + readonly "metadata"?: { readonly "user_id"?: string | null } + readonly "stream"?: boolean +} +export const CompletionRequest = Schema.Struct({ + "model": Model, + "prompt": Schema.String.annotate({ + "title": "Prompt", + "description": + "The prompt that you want Claude to complete.\n\nFor proper response generation you will need to format your prompt using alternating `\\n\\nHuman:` and `\\n\\nAssistant:` conversational turns. For example:\n\n```\n\"\\n\\nHuman: {userQuestion}\\n\\nAssistant:\"\n```\n\nSee [prompt validation](https://docs.claude.com/en/api/prompt-validation) and our guide to [prompt design](https://docs.claude.com/en/docs/intro-to-prompting) for more details." + }).check(Schema.isMinLength(1)), + "max_tokens_to_sample": Schema.Number.annotate({ + "title": "Max Tokens To Sample", + "description": + "The maximum number of tokens to generate before stopping.\n\nNote that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "stop_sequences": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "title": "Stop Sequences", + "description": + "Sequences that will cause the model to stop generating.\n\nOur models stop on `\"\\n\\nHuman:\"`, and may include additional built-in stop sequences in the future. By providing the stop_sequences parameter, you may include additional strings that will cause the model to stop generating." + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Temperature", + "description": + "Amount of randomness injected into the response.\n\nDefaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for analytical / multiple choice, and closer to `1.0` for creative and generative tasks.\n\nNote that even with `temperature` of `0.0`, the results will not be fully deterministic." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ), + "top_p": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top P", + "description": + "Use nucleus sampling.\n\nIn nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ), + "top_k": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top K", + "description": + "Only sample from the top K options for each subsequent token.\n\nUsed to remove \"long tail\" low probability responses. [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) + ), + "metadata": Schema.optionalKey( + Schema.Struct({ + "user_id": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMaxLength(256)), Schema.Null]).annotate({ + "title": "User Id", + "description": + "An external identifier for the user who is associated with the request.\n\nThis should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number." + }) + ) + }).annotate({ "title": "Metadata", "description": "An object describing metadata about the request." }) + ), + "stream": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Stream", + "description": + "Whether to incrementally stream the response using server-sent events.\n\nSee [streaming](https://docs.claude.com/en/api/streaming) for details." + }) + ) +}).annotate({ "title": "CompletionRequest" }) +export type CompletionResponse = { + readonly "completion": string + readonly "id": string + readonly "model": Model + readonly "stop_reason": string | null + readonly "type": "completion" +} +export const CompletionResponse = Schema.Struct({ + "completion": Schema.String.annotate({ + "title": "Completion", + "description": "The resulting completion up to and excluding the stop sequences." + }), + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique object identifier.\n\nThe format and length of IDs may change over time." + }), + "model": Model, + "stop_reason": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Stop Reason", + "description": + "The reason that we stopped.\n\nThis may be one the following values:\n* `\"stop_sequence\"`: we reached a stop sequence — either provided by you via the `stop_sequences` parameter, or a stop sequence built into the model\n* `\"max_tokens\"`: we exceeded `max_tokens_to_sample` or the model's maximum" + }), + "type": Schema.Literal("completion").annotate({ + "title": "Type", + "description": "Object type.\n\nFor Text Completions, this is always `\"completion\"`.", + "default": "completion" + }) +}).annotate({ "title": "CompletionResponse" }) +export type BetaRequestToolSearchToolSearchResultBlock = { + readonly "tool_references": ReadonlyArray + readonly "type": "tool_search_tool_search_result" +} +export const BetaRequestToolSearchToolSearchResultBlock = Schema.Struct({ + "tool_references": Schema.Array(BetaRequestToolReferenceBlock).annotate({ "title": "Tool References" }), + "type": Schema.Literal("tool_search_tool_search_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestToolSearchToolSearchResultBlock" }) +export type BetaIterationsUsage = ReadonlyArray | null +export const BetaIterationsUsage = Schema.Union([ + Schema.Array(Schema.Union([BetaMessageIterationUsage, BetaCompactionIterationUsage])), + Schema.Null +]).annotate({ + "title": "Iterations", + "description": + "Per-iteration token usage breakdown.\n\nEach entry represents one sampling iteration, with its own input/output token counts and cache statistics. This allows you to:\n- Determine which iterations exceeded long context thresholds (>=200k tokens)\n- Calculate the true context window size from the last iteration\n- Understand token accumulation across server-side tool use loops", + "default": null +}) +export type BetaErroredResult = { readonly "error": BetaErrorResponse; readonly "type": "errored" } +export const BetaErroredResult = Schema.Struct({ + "error": BetaErrorResponse, + "type": Schema.Literal("errored").annotate({ "title": "Type", "default": "errored" }) +}).annotate({ "title": "ErroredResult" }) +export type BetaRequestBashCodeExecutionToolResultBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "content": BetaRequestBashCodeExecutionToolResultError | BetaRequestBashCodeExecutionResultBlock + readonly "tool_use_id": string + readonly "type": "bash_code_execution_tool_result" +} +export const BetaRequestBashCodeExecutionToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.Union([BetaRequestBashCodeExecutionToolResultError, BetaRequestBashCodeExecutionResultBlock]) + .annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("bash_code_execution_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestBashCodeExecutionToolResultBlock" }) +export type BetaRequestCodeExecutionToolResultBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "content": + | BetaRequestCodeExecutionToolResultError + | BetaRequestCodeExecutionResultBlock + | BetaRequestEncryptedCodeExecutionResultBlock + readonly "tool_use_id": string + readonly "type": "code_execution_tool_result" +} +export const BetaRequestCodeExecutionToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.Union([ + BetaRequestCodeExecutionToolResultError, + BetaRequestCodeExecutionResultBlock, + BetaRequestEncryptedCodeExecutionResultBlock + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("code_execution_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestCodeExecutionToolResultBlock" }) +export type BetaRequestSearchResultBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "citations"?: BetaRequestCitationsConfig + readonly "content": ReadonlyArray + readonly "source": string + readonly "title": string + readonly "type": "search_result" +} +export const BetaRequestSearchResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey(BetaRequestCitationsConfig), + "content": Schema.Array(BetaRequestTextBlock).annotate({ "title": "Content" }), + "source": Schema.String.annotate({ "title": "Source" }), + "title": Schema.String.annotate({ "title": "Title" }), + "type": Schema.Literal("search_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestSearchResultBlock" }) +export type BetaResponseBashCodeExecutionToolResultBlock = { + readonly "content": BetaResponseBashCodeExecutionToolResultError | BetaResponseBashCodeExecutionResultBlock + readonly "tool_use_id": string + readonly "type": "bash_code_execution_tool_result" +} +export const BetaResponseBashCodeExecutionToolResultBlock = Schema.Struct({ + "content": Schema.Union([BetaResponseBashCodeExecutionToolResultError, BetaResponseBashCodeExecutionResultBlock]) + .annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("bash_code_execution_tool_result").annotate({ + "title": "Type", + "default": "bash_code_execution_tool_result" + }) +}).annotate({ "title": "ResponseBashCodeExecutionToolResultBlock" }) +export type BetaResponseWebFetchResultBlock = { + readonly "content": BetaResponseDocumentBlock + readonly "retrieved_at": string | null + readonly "type": "web_fetch_result" + readonly "url": string +} +export const BetaResponseWebFetchResultBlock = Schema.Struct({ + "content": BetaResponseDocumentBlock, + "retrieved_at": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Retrieved At", + "description": "ISO 8601 timestamp when the content was retrieved", + "default": null + }), + "type": Schema.Literal("web_fetch_result").annotate({ "title": "Type", "default": "web_fetch_result" }), + "url": Schema.String.annotate({ "title": "Url", "description": "Fetched content URL" }) +}).annotate({ "title": "ResponseWebFetchResultBlock" }) +export type BetaResponseCodeExecutionToolResultBlock = { + readonly "content": + | BetaResponseCodeExecutionToolResultError + | BetaResponseCodeExecutionResultBlock + | BetaResponseEncryptedCodeExecutionResultBlock + readonly "tool_use_id": string + readonly "type": "code_execution_tool_result" +} +export const BetaResponseCodeExecutionToolResultBlock = Schema.Struct({ + "content": Schema.Union([ + BetaResponseCodeExecutionToolResultError, + BetaResponseCodeExecutionResultBlock, + BetaResponseEncryptedCodeExecutionResultBlock + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("code_execution_tool_result").annotate({ + "title": "Type", + "default": "code_execution_tool_result" + }) +}).annotate({ "title": "ResponseCodeExecutionToolResultBlock" }) +export type BetaContentBlockDeltaEvent = { + readonly "delta": + | BetaTextContentBlockDelta + | BetaInputJsonContentBlockDelta + | BetaCitationsDelta + | BetaThinkingContentBlockDelta + | BetaSignatureContentBlockDelta + | BetaCompactionContentBlockDelta + readonly "index": number + readonly "type": "content_block_delta" +} +export const BetaContentBlockDeltaEvent = Schema.Struct({ + "delta": Schema.Union([ + BetaTextContentBlockDelta, + BetaInputJsonContentBlockDelta, + BetaCitationsDelta, + BetaThinkingContentBlockDelta, + BetaSignatureContentBlockDelta, + BetaCompactionContentBlockDelta + ], { mode: "oneOf" }).annotate({ "title": "Delta" }), + "index": Schema.Number.annotate({ "title": "Index" }).check(Schema.isInt()), + "type": Schema.Literal("content_block_delta").annotate({ "title": "Type", "default": "content_block_delta" }) +}).annotate({ "title": "ContentBlockDeltaEvent" }) +export type BetaMessageDelta = { + readonly "container"?: BetaContainer | null + readonly "stop_reason": BetaStopReason | null + readonly "stop_sequence": string | null +} +export const BetaMessageDelta = Schema.Struct({ + "container": Schema.optionalKey( + Schema.Union([BetaContainer, Schema.Null]).annotate({ + "description": + "Information about the container used in this request.\n\nThis will be non-null if a container tool (e.g. code execution) was used.", + "default": null + }) + ), + "stop_reason": Schema.Union([BetaStopReason, Schema.Null]).annotate({ "title": "Stop Reason", "default": null }), + "stop_sequence": Schema.Union([Schema.String, Schema.Null]).annotate({ "title": "Stop Sequence", "default": null }) +}).annotate({ "title": "MessageDelta" }) +export type BetaRequestTextEditorCodeExecutionToolResultBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "content": + | BetaRequestTextEditorCodeExecutionToolResultError + | BetaRequestTextEditorCodeExecutionViewResultBlock + | BetaRequestTextEditorCodeExecutionCreateResultBlock + | BetaRequestTextEditorCodeExecutionStrReplaceResultBlock + readonly "tool_use_id": string + readonly "type": "text_editor_code_execution_tool_result" +} +export const BetaRequestTextEditorCodeExecutionToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.Union([ + BetaRequestTextEditorCodeExecutionToolResultError, + BetaRequestTextEditorCodeExecutionViewResultBlock, + BetaRequestTextEditorCodeExecutionCreateResultBlock, + BetaRequestTextEditorCodeExecutionStrReplaceResultBlock + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("text_editor_code_execution_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionToolResultBlock" }) +export type BetaResponseTextEditorCodeExecutionToolResultBlock = { + readonly "content": + | BetaResponseTextEditorCodeExecutionToolResultError + | BetaResponseTextEditorCodeExecutionViewResultBlock + | BetaResponseTextEditorCodeExecutionCreateResultBlock + | BetaResponseTextEditorCodeExecutionStrReplaceResultBlock + readonly "tool_use_id": string + readonly "type": "text_editor_code_execution_tool_result" +} +export const BetaResponseTextEditorCodeExecutionToolResultBlock = Schema.Struct({ + "content": Schema.Union([ + BetaResponseTextEditorCodeExecutionToolResultError, + BetaResponseTextEditorCodeExecutionViewResultBlock, + BetaResponseTextEditorCodeExecutionCreateResultBlock, + BetaResponseTextEditorCodeExecutionStrReplaceResultBlock + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("text_editor_code_execution_tool_result").annotate({ + "title": "Type", + "default": "text_editor_code_execution_tool_result" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionToolResultBlock" }) +export type BetaResponseToolSearchToolResultBlock = { + readonly "content": BetaResponseToolSearchToolResultError | BetaResponseToolSearchToolSearchResultBlock + readonly "tool_use_id": string + readonly "type": "tool_search_tool_result" +} +export const BetaResponseToolSearchToolResultBlock = Schema.Struct({ + "content": Schema.Union([BetaResponseToolSearchToolResultError, BetaResponseToolSearchToolSearchResultBlock]) + .annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("tool_search_tool_result").annotate({ "title": "Type", "default": "tool_search_tool_result" }) +}).annotate({ "title": "ResponseToolSearchToolResultBlock" }) +export type BetaContextManagementConfig = { + readonly "edits"?: ReadonlyArray +} +export const BetaContextManagementConfig = Schema.Struct({ + "edits": Schema.optionalKey( + Schema.Array( + Schema.Union([BetaClearToolUses20250919, BetaClearThinking20251015, BetaCompact20260112], { mode: "oneOf" }) + ).annotate({ "title": "Edits", "description": "List of context management edits to apply" }).check( + Schema.isMinLength(0) + ) + ) +}).annotate({ "title": "ContextManagementConfig" }) +export type BetaContentBlockSource = { + readonly "content": string | ReadonlyArray + readonly "type": "content" +} +export const BetaContentBlockSource = Schema.Struct({ + "content": Schema.Union([ + Schema.String, + Schema.Array( + Schema.Union([BetaRequestTextBlock, BetaRequestImageBlock], { mode: "oneOf" }).annotate({ + "title": "beta_content_block_source_content_item" + }) + ).annotate({ "title": "beta_content_block_source_content" }) + ]).annotate({ "title": "Content" }), + "type": Schema.Literal("content").annotate({ "title": "Type" }) +}).annotate({ "title": "ContentBlockSource" }) +export type BetaRequestWebSearchToolResultBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "caller"?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller_20260120 + readonly "content": ReadonlyArray | BetaRequestWebSearchToolResultError + readonly "tool_use_id": string + readonly "type": "web_search_tool_result" +} +export const BetaRequestWebSearchToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "caller": Schema.optionalKey( + Schema.Union([BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "content": Schema.Union([ + Schema.Array(BetaRequestWebSearchResultBlock).annotate({ "title": "Result Block" }), + BetaRequestWebSearchToolResultError + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("web_search_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestWebSearchToolResultBlock" }) +export type BetaResponseWebSearchToolResultBlock = { + readonly "caller"?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller_20260120 + readonly "content": BetaResponseWebSearchToolResultError | ReadonlyArray + readonly "tool_use_id": string + readonly "type": "web_search_tool_result" +} +export const BetaResponseWebSearchToolResultBlock = Schema.Struct({ + "caller": Schema.optionalKey( + Schema.Union([BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "content": Schema.Union([BetaResponseWebSearchToolResultError, Schema.Array(BetaResponseWebSearchResultBlock)]) + .annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("web_search_tool_result").annotate({ "title": "Type", "default": "web_search_tool_result" }) +}).annotate({ "title": "ResponseWebSearchToolResultBlock" }) +export type RequestToolSearchToolSearchResultBlock = { + readonly "tool_references": ReadonlyArray + readonly "type": "tool_search_tool_search_result" +} +export const RequestToolSearchToolSearchResultBlock = Schema.Struct({ + "tool_references": Schema.Array(RequestToolReferenceBlock).annotate({ "title": "Tool References" }), + "type": Schema.Literal("tool_search_tool_search_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestToolSearchToolSearchResultBlock" }) +export type ErroredResult = { readonly "error": ErrorResponse; readonly "type": "errored" } +export const ErroredResult = Schema.Struct({ + "error": ErrorResponse, + "type": Schema.Literal("errored").annotate({ "title": "Type", "default": "errored" }) +}).annotate({ "title": "ErroredResult" }) +export type RequestBashCodeExecutionToolResultBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "content": RequestBashCodeExecutionToolResultError | RequestBashCodeExecutionResultBlock + readonly "tool_use_id": string + readonly "type": "bash_code_execution_tool_result" +} +export const RequestBashCodeExecutionToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.Union([RequestBashCodeExecutionToolResultError, RequestBashCodeExecutionResultBlock]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("bash_code_execution_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestBashCodeExecutionToolResultBlock" }) +export type RequestCodeExecutionToolResultBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "content": + | RequestCodeExecutionToolResultError + | RequestCodeExecutionResultBlock + | RequestEncryptedCodeExecutionResultBlock + readonly "tool_use_id": string + readonly "type": "code_execution_tool_result" +} +export const RequestCodeExecutionToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.Union([ + RequestCodeExecutionToolResultError, + RequestCodeExecutionResultBlock, + RequestEncryptedCodeExecutionResultBlock + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("code_execution_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestCodeExecutionToolResultBlock" }) +export type RequestSearchResultBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "citations"?: RequestCitationsConfig + readonly "content": ReadonlyArray + readonly "source": string + readonly "title": string + readonly "type": "search_result" +} +export const RequestSearchResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey(RequestCitationsConfig), + "content": Schema.Array(RequestTextBlock).annotate({ "title": "Content" }), + "source": Schema.String.annotate({ "title": "Source" }), + "title": Schema.String.annotate({ "title": "Title" }), + "type": Schema.Literal("search_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestSearchResultBlock" }) +export type ResponseBashCodeExecutionToolResultBlock = { + readonly "content": ResponseBashCodeExecutionToolResultError | ResponseBashCodeExecutionResultBlock + readonly "tool_use_id": string + readonly "type": "bash_code_execution_tool_result" +} +export const ResponseBashCodeExecutionToolResultBlock = Schema.Struct({ + "content": Schema.Union([ResponseBashCodeExecutionToolResultError, ResponseBashCodeExecutionResultBlock]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("bash_code_execution_tool_result").annotate({ + "title": "Type", + "default": "bash_code_execution_tool_result" + }) +}).annotate({ "title": "ResponseBashCodeExecutionToolResultBlock" }) +export type ResponseWebFetchResultBlock = { + readonly "content": ResponseDocumentBlock + readonly "retrieved_at": string | null + readonly "type": "web_fetch_result" + readonly "url": string +} +export const ResponseWebFetchResultBlock = Schema.Struct({ + "content": ResponseDocumentBlock, + "retrieved_at": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Retrieved At", + "description": "ISO 8601 timestamp when the content was retrieved", + "default": null + }), + "type": Schema.Literal("web_fetch_result").annotate({ "title": "Type", "default": "web_fetch_result" }), + "url": Schema.String.annotate({ "title": "Url", "description": "Fetched content URL" }) +}).annotate({ "title": "ResponseWebFetchResultBlock" }) +export type ResponseCodeExecutionToolResultBlock = { + readonly "content": + | ResponseCodeExecutionToolResultError + | ResponseCodeExecutionResultBlock + | ResponseEncryptedCodeExecutionResultBlock + readonly "tool_use_id": string + readonly "type": "code_execution_tool_result" +} +export const ResponseCodeExecutionToolResultBlock = Schema.Struct({ + "content": Schema.Union([ + ResponseCodeExecutionToolResultError, + ResponseCodeExecutionResultBlock, + ResponseEncryptedCodeExecutionResultBlock + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("code_execution_tool_result").annotate({ + "title": "Type", + "default": "code_execution_tool_result" + }) +}).annotate({ "title": "ResponseCodeExecutionToolResultBlock" }) +export type ContentBlockDeltaEvent = { + readonly "delta": + | TextContentBlockDelta + | InputJsonContentBlockDelta + | CitationsDelta + | ThinkingContentBlockDelta + | SignatureContentBlockDelta + readonly "index": number + readonly "type": "content_block_delta" +} +export const ContentBlockDeltaEvent = Schema.Struct({ + "delta": Schema.Union([ + TextContentBlockDelta, + InputJsonContentBlockDelta, + CitationsDelta, + ThinkingContentBlockDelta, + SignatureContentBlockDelta + ], { mode: "oneOf" }).annotate({ "title": "Delta" }), + "index": Schema.Number.annotate({ "title": "Index" }).check(Schema.isInt()), + "type": Schema.Literal("content_block_delta").annotate({ "title": "Type", "default": "content_block_delta" }) +}).annotate({ "title": "ContentBlockDeltaEvent" }) +export type RequestTextEditorCodeExecutionToolResultBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "content": + | RequestTextEditorCodeExecutionToolResultError + | RequestTextEditorCodeExecutionViewResultBlock + | RequestTextEditorCodeExecutionCreateResultBlock + | RequestTextEditorCodeExecutionStrReplaceResultBlock + readonly "tool_use_id": string + readonly "type": "text_editor_code_execution_tool_result" +} +export const RequestTextEditorCodeExecutionToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.Union([ + RequestTextEditorCodeExecutionToolResultError, + RequestTextEditorCodeExecutionViewResultBlock, + RequestTextEditorCodeExecutionCreateResultBlock, + RequestTextEditorCodeExecutionStrReplaceResultBlock + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("text_editor_code_execution_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestTextEditorCodeExecutionToolResultBlock" }) +export type ResponseTextEditorCodeExecutionToolResultBlock = { + readonly "content": + | ResponseTextEditorCodeExecutionToolResultError + | ResponseTextEditorCodeExecutionViewResultBlock + | ResponseTextEditorCodeExecutionCreateResultBlock + | ResponseTextEditorCodeExecutionStrReplaceResultBlock + readonly "tool_use_id": string + readonly "type": "text_editor_code_execution_tool_result" +} +export const ResponseTextEditorCodeExecutionToolResultBlock = Schema.Struct({ + "content": Schema.Union([ + ResponseTextEditorCodeExecutionToolResultError, + ResponseTextEditorCodeExecutionViewResultBlock, + ResponseTextEditorCodeExecutionCreateResultBlock, + ResponseTextEditorCodeExecutionStrReplaceResultBlock + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("text_editor_code_execution_tool_result").annotate({ + "title": "Type", + "default": "text_editor_code_execution_tool_result" + }) +}).annotate({ "title": "ResponseTextEditorCodeExecutionToolResultBlock" }) +export type ResponseToolSearchToolResultBlock = { + readonly "content": ResponseToolSearchToolResultError | ResponseToolSearchToolSearchResultBlock + readonly "tool_use_id": string + readonly "type": "tool_search_tool_result" +} +export const ResponseToolSearchToolResultBlock = Schema.Struct({ + "content": Schema.Union([ResponseToolSearchToolResultError, ResponseToolSearchToolSearchResultBlock]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("tool_search_tool_result").annotate({ "title": "Type", "default": "tool_search_tool_result" }) +}).annotate({ "title": "ResponseToolSearchToolResultBlock" }) +export type ContentBlockSource = { + readonly "content": string | ReadonlyArray + readonly "type": "content" +} +export const ContentBlockSource = Schema.Struct({ + "content": Schema.Union([ + Schema.String, + Schema.Array( + Schema.Union([RequestTextBlock, RequestImageBlock], { mode: "oneOf" }).annotate({ + "title": "content_block_source_content_item" + }) + ).annotate({ "title": "content_block_source_content" }) + ]).annotate({ "title": "Content" }), + "type": Schema.Literal("content").annotate({ "title": "Type" }) +}).annotate({ "title": "ContentBlockSource" }) +export type RequestWebSearchToolResultBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "caller"?: DirectCaller | ServerToolCaller | ServerToolCaller_20260120 + readonly "content": ReadonlyArray | RequestWebSearchToolResultError + readonly "tool_use_id": string + readonly "type": "web_search_tool_result" +} +export const RequestWebSearchToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "caller": Schema.optionalKey( + Schema.Union([DirectCaller, ServerToolCaller, ServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "content": Schema.Union([ + Schema.Array(RequestWebSearchResultBlock).annotate({ "title": "web_search_tool_result_block_item" }), + RequestWebSearchToolResultError + ]).annotate({ "title": "Content" }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("web_search_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestWebSearchToolResultBlock" }) +export type ResponseWebSearchToolResultBlock = { + readonly "caller": DirectCaller | ServerToolCaller | ServerToolCaller_20260120 + readonly "content": ResponseWebSearchToolResultError | ReadonlyArray + readonly "tool_use_id": string + readonly "type": "web_search_tool_result" +} +export const ResponseWebSearchToolResultBlock = Schema.Struct({ + "caller": Schema.Union([DirectCaller, ServerToolCaller, ServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller", + "default": { "type": "direct" } + }), + "content": Schema.Union([ResponseWebSearchToolResultError, Schema.Array(ResponseWebSearchResultBlock)]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("web_search_tool_result").annotate({ "title": "Type", "default": "web_search_tool_result" }) +}).annotate({ "title": "ResponseWebSearchToolResultBlock" }) +export type MessageDeltaEvent = { + readonly "delta": MessageDelta + readonly "type": "message_delta" + readonly "usage": { + readonly "cache_creation_input_tokens": number | null + readonly "cache_read_input_tokens": number | null + readonly "input_tokens": number | null + readonly "output_tokens": number + readonly "server_tool_use"?: ServerToolUsage | null + } +} +export const MessageDeltaEvent = Schema.Struct({ + "delta": MessageDelta, + "type": Schema.Literal("message_delta").annotate({ "title": "Type", "default": "message_delta" }), + "usage": Schema.Struct({ + "cache_creation_input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Cache Creation Input Tokens", + "description": "The cumulative number of input tokens used to create the cache entry.", + "default": null + }), + "cache_read_input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Cache Read Input Tokens", + "description": "The cumulative number of input tokens read from the cache.", + "default": null + }), + "input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Input Tokens", + "description": "The cumulative number of input tokens which were used.", + "default": null + }), + "output_tokens": Schema.Number.annotate({ + "title": "Output Tokens", + "description": "The cumulative number of output tokens which were used." + }).check(Schema.isInt()), + "server_tool_use": Schema.optionalKey( + Schema.Union([ServerToolUsage, Schema.Null]).annotate({ + "description": "The number of server tool requests.", + "default": null + }) + ) + }).annotate({ + "title": "MessageDeltaUsage", + "description": + "Billing and rate-limit usage.\n\nAnthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.\n\nUnder the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.\n\nFor example, `output_tokens` will be non-zero, even for an empty string response from Claude.\n\nTotal input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`." + }) +}).annotate({ "title": "MessageDeltaEvent" }) +export type BetaRequestToolSearchToolResultBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "content": BetaRequestToolSearchToolResultError | BetaRequestToolSearchToolSearchResultBlock + readonly "tool_use_id": string + readonly "type": "tool_search_tool_result" +} +export const BetaRequestToolSearchToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.Union([BetaRequestToolSearchToolResultError, BetaRequestToolSearchToolSearchResultBlock]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("tool_search_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestToolSearchToolResultBlock" }) +export type BetaResponseWebFetchToolResultBlock = { + readonly "caller"?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller_20260120 + readonly "content": BetaResponseWebFetchToolResultError | BetaResponseWebFetchResultBlock + readonly "tool_use_id": string + readonly "type": "web_fetch_tool_result" +} +export const BetaResponseWebFetchToolResultBlock = Schema.Struct({ + "caller": Schema.optionalKey( + Schema.Union([BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "content": Schema.Union([BetaResponseWebFetchToolResultError, BetaResponseWebFetchResultBlock]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("web_fetch_tool_result").annotate({ "title": "Type", "default": "web_fetch_tool_result" }) +}).annotate({ "title": "ResponseWebFetchToolResultBlock" }) +export type BetaMessageDeltaEvent = { + readonly "context_management"?: BetaResponseContextManagement | null + readonly "delta": BetaMessageDelta + readonly "type": "message_delta" + readonly "usage": { + readonly "cache_creation_input_tokens": number | null + readonly "cache_read_input_tokens": number | null + readonly "input_tokens": number | null + readonly "iterations"?: BetaIterationsUsage + readonly "output_tokens": number + readonly "server_tool_use"?: BetaServerToolUsage | null + } +} +export const BetaMessageDeltaEvent = Schema.Struct({ + "context_management": Schema.optionalKey( + Schema.Union([BetaResponseContextManagement, Schema.Null]).annotate({ + "description": "Information about context management strategies applied during the request", + "default": null + }) + ), + "delta": BetaMessageDelta, + "type": Schema.Literal("message_delta").annotate({ "title": "Type", "default": "message_delta" }), + "usage": Schema.Struct({ + "cache_creation_input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Cache Creation Input Tokens", + "description": "The cumulative number of input tokens used to create the cache entry.", + "default": null + }), + "cache_read_input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Cache Read Input Tokens", + "description": "The cumulative number of input tokens read from the cache.", + "default": null + }), + "input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Input Tokens", + "description": "The cumulative number of input tokens which were used.", + "default": null + }), + "iterations": Schema.optionalKey(BetaIterationsUsage), + "output_tokens": Schema.Number.annotate({ + "title": "Output Tokens", + "description": "The cumulative number of output tokens which were used." + }).check(Schema.isInt()), + "server_tool_use": Schema.optionalKey( + Schema.Union([BetaServerToolUsage, Schema.Null]).annotate({ + "description": "The number of server tool requests.", + "default": null + }) + ) + }).annotate({ + "title": "MessageDeltaUsage", + "description": + "Billing and rate-limit usage.\n\nAnthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.\n\nUnder the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.\n\nFor example, `output_tokens` will be non-zero, even for an empty string response from Claude.\n\nTotal input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`." + }) +}).annotate({ "title": "MessageDeltaEvent" }) +export type BetaRequestDocumentBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "citations"?: BetaRequestCitationsConfig | null + readonly "context"?: string | null + readonly "source": + | BetaBase64PDFSource + | BetaPlainTextSource + | BetaContentBlockSource + | BetaURLPDFSource + | BetaFileDocumentSource + readonly "title"?: string | null + readonly "type": "document" +} +export const BetaRequestDocumentBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey(Schema.Union([BetaRequestCitationsConfig, Schema.Null])), + "context": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)), Schema.Null]).annotate({ "title": "Context" }) + ), + "source": Schema.Union([ + BetaBase64PDFSource, + BetaPlainTextSource, + BetaContentBlockSource, + BetaURLPDFSource, + BetaFileDocumentSource + ], { mode: "oneOf" }).annotate({ "title": "Source" }), + "title": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(500)), Schema.Null]).annotate({ + "title": "Title" + }) + ), + "type": Schema.Literal("document").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestDocumentBlock" }) +export type RequestToolSearchToolResultBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "content": RequestToolSearchToolResultError | RequestToolSearchToolSearchResultBlock + readonly "tool_use_id": string + readonly "type": "tool_search_tool_result" +} +export const RequestToolSearchToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.Union([RequestToolSearchToolResultError, RequestToolSearchToolSearchResultBlock]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("tool_search_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestToolSearchToolResultBlock" }) +export type ResponseWebFetchToolResultBlock = { + readonly "caller": DirectCaller | ServerToolCaller | ServerToolCaller_20260120 + readonly "content": ResponseWebFetchToolResultError | ResponseWebFetchResultBlock + readonly "tool_use_id": string + readonly "type": "web_fetch_tool_result" +} +export const ResponseWebFetchToolResultBlock = Schema.Struct({ + "caller": Schema.Union([DirectCaller, ServerToolCaller, ServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller", + "default": { "type": "direct" } + }), + "content": Schema.Union([ResponseWebFetchToolResultError, ResponseWebFetchResultBlock]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("web_fetch_tool_result").annotate({ "title": "Type", "default": "web_fetch_tool_result" }) +}).annotate({ "title": "ResponseWebFetchToolResultBlock" }) +export type RequestDocumentBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "citations"?: RequestCitationsConfig | null + readonly "context"?: string | null + readonly "source": Base64PDFSource | PlainTextSource | ContentBlockSource | URLPDFSource + readonly "title"?: string | null + readonly "type": "document" +} +export const RequestDocumentBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey(Schema.Union([RequestCitationsConfig, Schema.Null])), + "context": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)), Schema.Null]).annotate({ "title": "Context" }) + ), + "source": Schema.Union([Base64PDFSource, PlainTextSource, ContentBlockSource, URLPDFSource], { mode: "oneOf" }) + .annotate({ "title": "Source" }), + "title": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(500)), Schema.Null]).annotate({ + "title": "Title" + }) + ), + "type": Schema.Literal("document").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestDocumentBlock" }) +export type BetaContentBlockStartEvent = { + readonly "content_block": + | BetaResponseTextBlock + | BetaResponseThinkingBlock + | BetaResponseRedactedThinkingBlock + | BetaResponseToolUseBlock + | BetaResponseServerToolUseBlock + | BetaResponseWebSearchToolResultBlock + | BetaResponseWebFetchToolResultBlock + | BetaResponseCodeExecutionToolResultBlock + | BetaResponseBashCodeExecutionToolResultBlock + | BetaResponseTextEditorCodeExecutionToolResultBlock + | BetaResponseToolSearchToolResultBlock + | BetaResponseMCPToolUseBlock + | BetaResponseMCPToolResultBlock + | BetaResponseContainerUploadBlock + | BetaResponseCompactionBlock + readonly "index": number + readonly "type": "content_block_start" +} +export const BetaContentBlockStartEvent = Schema.Struct({ + "content_block": Schema.Union([ + BetaResponseTextBlock, + BetaResponseThinkingBlock, + BetaResponseRedactedThinkingBlock, + BetaResponseToolUseBlock, + BetaResponseServerToolUseBlock, + BetaResponseWebSearchToolResultBlock, + BetaResponseWebFetchToolResultBlock, + BetaResponseCodeExecutionToolResultBlock, + BetaResponseBashCodeExecutionToolResultBlock, + BetaResponseTextEditorCodeExecutionToolResultBlock, + BetaResponseToolSearchToolResultBlock, + BetaResponseMCPToolUseBlock, + BetaResponseMCPToolResultBlock, + BetaResponseContainerUploadBlock, + BetaResponseCompactionBlock + ], { mode: "oneOf" }).annotate({ "title": "Content Block" }), + "index": Schema.Number.annotate({ "title": "Index" }).check(Schema.isInt()), + "type": Schema.Literal("content_block_start").annotate({ "title": "Type", "default": "content_block_start" }) +}).annotate({ "title": "ContentBlockStartEvent" }) +export type BetaContentBlock = + | BetaResponseTextBlock + | BetaResponseThinkingBlock + | BetaResponseRedactedThinkingBlock + | BetaResponseToolUseBlock + | BetaResponseServerToolUseBlock + | BetaResponseWebSearchToolResultBlock + | BetaResponseWebFetchToolResultBlock + | BetaResponseCodeExecutionToolResultBlock + | BetaResponseBashCodeExecutionToolResultBlock + | BetaResponseTextEditorCodeExecutionToolResultBlock + | BetaResponseToolSearchToolResultBlock + | BetaResponseMCPToolUseBlock + | BetaResponseMCPToolResultBlock + | BetaResponseContainerUploadBlock + | BetaResponseCompactionBlock +export const BetaContentBlock = Schema.Union([ + BetaResponseTextBlock, + BetaResponseThinkingBlock, + BetaResponseRedactedThinkingBlock, + BetaResponseToolUseBlock, + BetaResponseServerToolUseBlock, + BetaResponseWebSearchToolResultBlock, + BetaResponseWebFetchToolResultBlock, + BetaResponseCodeExecutionToolResultBlock, + BetaResponseBashCodeExecutionToolResultBlock, + BetaResponseTextEditorCodeExecutionToolResultBlock, + BetaResponseToolSearchToolResultBlock, + BetaResponseMCPToolUseBlock, + BetaResponseMCPToolResultBlock, + BetaResponseContainerUploadBlock, + BetaResponseCompactionBlock +], { mode: "oneOf" }) +export type BetaRequestWebFetchResultBlock = { + readonly "content": BetaRequestDocumentBlock + readonly "retrieved_at"?: string | null + readonly "type": "web_fetch_result" + readonly "url": string +} +export const BetaRequestWebFetchResultBlock = Schema.Struct({ + "content": BetaRequestDocumentBlock, + "retrieved_at": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Retrieved At", + "description": "ISO 8601 timestamp when the content was retrieved" + }) + ), + "type": Schema.Literal("web_fetch_result").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url", "description": "Fetched content URL" }) +}).annotate({ "title": "RequestWebFetchResultBlock" }) +export type ContentBlockStartEvent = { + readonly "content_block": + | ResponseTextBlock + | ResponseThinkingBlock + | ResponseRedactedThinkingBlock + | ResponseToolUseBlock + | ResponseServerToolUseBlock + | ResponseWebSearchToolResultBlock + | ResponseWebFetchToolResultBlock + | ResponseCodeExecutionToolResultBlock + | ResponseBashCodeExecutionToolResultBlock + | ResponseTextEditorCodeExecutionToolResultBlock + | ResponseToolSearchToolResultBlock + | ResponseContainerUploadBlock + readonly "index": number + readonly "type": "content_block_start" +} +export const ContentBlockStartEvent = Schema.Struct({ + "content_block": Schema.Union([ + ResponseTextBlock, + ResponseThinkingBlock, + ResponseRedactedThinkingBlock, + ResponseToolUseBlock, + ResponseServerToolUseBlock, + ResponseWebSearchToolResultBlock, + ResponseWebFetchToolResultBlock, + ResponseCodeExecutionToolResultBlock, + ResponseBashCodeExecutionToolResultBlock, + ResponseTextEditorCodeExecutionToolResultBlock, + ResponseToolSearchToolResultBlock, + ResponseContainerUploadBlock + ], { mode: "oneOf" }).annotate({ "title": "Content Block" }), + "index": Schema.Number.annotate({ "title": "Index" }).check(Schema.isInt()), + "type": Schema.Literal("content_block_start").annotate({ "title": "Type", "default": "content_block_start" }) +}).annotate({ "title": "ContentBlockStartEvent" }) +export type ContentBlock = + | ResponseTextBlock + | ResponseThinkingBlock + | ResponseRedactedThinkingBlock + | ResponseToolUseBlock + | ResponseServerToolUseBlock + | ResponseWebSearchToolResultBlock + | ResponseWebFetchToolResultBlock + | ResponseCodeExecutionToolResultBlock + | ResponseBashCodeExecutionToolResultBlock + | ResponseTextEditorCodeExecutionToolResultBlock + | ResponseToolSearchToolResultBlock + | ResponseContainerUploadBlock +export const ContentBlock = Schema.Union([ + ResponseTextBlock, + ResponseThinkingBlock, + ResponseRedactedThinkingBlock, + ResponseToolUseBlock, + ResponseServerToolUseBlock, + ResponseWebSearchToolResultBlock, + ResponseWebFetchToolResultBlock, + ResponseCodeExecutionToolResultBlock, + ResponseBashCodeExecutionToolResultBlock, + ResponseTextEditorCodeExecutionToolResultBlock, + ResponseToolSearchToolResultBlock, + ResponseContainerUploadBlock +], { mode: "oneOf" }) +export type RequestWebFetchResultBlock = { + readonly "content": RequestDocumentBlock + readonly "retrieved_at"?: string | null + readonly "type": "web_fetch_result" + readonly "url": string +} +export const RequestWebFetchResultBlock = Schema.Struct({ + "content": RequestDocumentBlock, + "retrieved_at": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Retrieved At", + "description": "ISO 8601 timestamp when the content was retrieved" + }) + ), + "type": Schema.Literal("web_fetch_result").annotate({ "title": "Type" }), + "url": Schema.String.annotate({ "title": "Url", "description": "Fetched content URL" }) +}).annotate({ "title": "RequestWebFetchResultBlock" }) +export type BetaMessage = { + readonly "id": string + readonly "type": "message" + readonly "role": "assistant" + readonly "content": ReadonlyArray + readonly "model": Model + readonly "stop_reason": BetaStopReason | null + readonly "stop_sequence": string | null + readonly "usage": { + readonly "cache_creation": BetaCacheCreation | null + readonly "cache_creation_input_tokens": number | null + readonly "cache_read_input_tokens": number | null + readonly "inference_geo": string | null + readonly "input_tokens": number + readonly "iterations"?: BetaIterationsUsage + readonly "output_tokens": number + readonly "server_tool_use"?: BetaServerToolUsage | null + readonly "service_tier": "standard" | "priority" | "batch" | null + readonly "speed"?: BetaSpeed | null + } + readonly "context_management"?: BetaResponseContextManagement | null + readonly "container"?: BetaContainer | null +} +export const BetaMessage = Schema.Struct({ + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique object identifier.\n\nThe format and length of IDs may change over time." + }), + "type": Schema.Literal("message").annotate({ + "title": "Type", + "description": "Object type.\n\nFor Messages, this is always `\"message\"`.", + "default": "message" + }), + "role": Schema.Literal("assistant").annotate({ + "title": "Role", + "description": "Conversational role of the generated message.\n\nThis will always be `\"assistant\"`.", + "default": "assistant" + }), + "content": Schema.Array(BetaContentBlock).annotate({ + "title": "Content", + "description": + "Content generated by the model.\n\nThis is an array of content blocks, each of which has a `type` that determines its shape.\n\nExample:\n\n```json\n[{\"type\": \"text\", \"text\": \"Hi, I'm Claude.\"}]\n```\n\nIf the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output.\n\nFor example, if the input `messages` were:\n```json\n[\n {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n {\"role\": \"assistant\", \"content\": \"The best answer is (\"}\n]\n```\n\nThen the response `content` might be:\n\n```json\n[{\"type\": \"text\", \"text\": \"B)\"}]\n```" + }), + "model": Model, + "stop_reason": Schema.Union([BetaStopReason, Schema.Null]).annotate({ + "title": "Stop Reason", + "description": + "The reason that we stopped.\n\nThis may be one the following values:\n* `\"end_turn\"`: the model reached a natural stopping point\n* `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n* `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n* `\"tool_use\"`: the model invoked one or more tools\n* `\"pause_turn\"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.\n* `\"refusal\"`: when streaming classifiers intervene to handle potential policy violations\n\nIn non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise." + }), + "stop_sequence": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Stop Sequence", + "description": + "Which custom stop sequence was generated, if any.\n\nThis value will be a non-null string if one of your custom stop sequences was generated.", + "default": null + }), + "usage": Schema.Struct({ + "cache_creation": Schema.Union([BetaCacheCreation, Schema.Null]).annotate({ + "description": "Breakdown of cached tokens by TTL", + "default": null + }), + "cache_creation_input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Cache Creation Input Tokens", + "description": "The number of input tokens used to create the cache entry.", + "default": null + }), + "cache_read_input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Cache Read Input Tokens", + "description": "The number of input tokens read from the cache.", + "default": null + }), + "inference_geo": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Inference Geo", + "description": "The geographic region where inference was performed for this request.", + "default": null + }), + "input_tokens": Schema.Number.annotate({ + "title": "Input Tokens", + "description": "The number of input tokens which were used." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "iterations": Schema.optionalKey(BetaIterationsUsage), + "output_tokens": Schema.Number.annotate({ + "title": "Output Tokens", + "description": "The number of output tokens which were used." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "server_tool_use": Schema.optionalKey( + Schema.Union([BetaServerToolUsage, Schema.Null]).annotate({ + "description": "The number of server tool requests.", + "default": null + }) + ), + "service_tier": Schema.Union([Schema.Literals(["standard", "priority", "batch"]), Schema.Null]).annotate({ + "title": "Service Tier", + "description": "If the request used the priority, standard, or batch tier.", + "default": null + }), + "speed": Schema.optionalKey( + Schema.Union([BetaSpeed, Schema.Null]).annotate({ + "description": "The inference speed mode used for this request.", + "default": null + }) + ) + }).annotate({ + "title": "Usage", + "description": + "Billing and rate-limit usage.\n\nAnthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.\n\nUnder the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.\n\nFor example, `output_tokens` will be non-zero, even for an empty string response from Claude.\n\nTotal input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`." + }), + "context_management": Schema.optionalKey( + Schema.Union([BetaResponseContextManagement, Schema.Null]).annotate({ + "description": + "Context management response.\n\nInformation about context management strategies applied during the request.", + "default": null + }) + ), + "container": Schema.optionalKey( + Schema.Union([BetaContainer, Schema.Null]).annotate({ + "description": + "Information about the container used in this request.\n\nThis will be non-null if a container tool (e.g. code execution) was used.", + "default": null + }) + ) +}).annotate({ "title": "Message" }) +export type BetaRequestWebFetchToolResultBlock = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "caller"?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller_20260120 + readonly "content": BetaRequestWebFetchToolResultError | BetaRequestWebFetchResultBlock + readonly "tool_use_id": string + readonly "type": "web_fetch_tool_result" +} +export const BetaRequestWebFetchToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "caller": Schema.optionalKey( + Schema.Union([BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "content": Schema.Union([BetaRequestWebFetchToolResultError, BetaRequestWebFetchResultBlock]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("web_fetch_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestWebFetchToolResultBlock" }) +export type Message = { + readonly "id": string + readonly "type": "message" + readonly "role": "assistant" + readonly "content": ReadonlyArray + readonly "model": Model + readonly "stop_reason": StopReason | null + readonly "stop_sequence": string | null + readonly "usage": { + readonly "cache_creation": CacheCreation | null + readonly "cache_creation_input_tokens": number | null + readonly "cache_read_input_tokens": number | null + readonly "inference_geo": string | null + readonly "input_tokens": number + readonly "output_tokens": number + readonly "server_tool_use"?: ServerToolUsage | null + readonly "service_tier": "standard" | "priority" | "batch" | null + } + readonly "container": Container | null +} +export const Message = Schema.Struct({ + "id": Schema.String.annotate({ + "title": "Id", + "description": "Unique object identifier.\n\nThe format and length of IDs may change over time." + }), + "type": Schema.Literal("message").annotate({ + "title": "Type", + "description": "Object type.\n\nFor Messages, this is always `\"message\"`.", + "default": "message" + }), + "role": Schema.Literal("assistant").annotate({ + "title": "Role", + "description": "Conversational role of the generated message.\n\nThis will always be `\"assistant\"`.", + "default": "assistant" + }), + "content": Schema.Array(ContentBlock).annotate({ + "title": "Content", + "description": + "Content generated by the model.\n\nThis is an array of content blocks, each of which has a `type` that determines its shape.\n\nExample:\n\n```json\n[{\"type\": \"text\", \"text\": \"Hi, I'm Claude.\"}]\n```\n\nIf the request input `messages` ended with an `assistant` turn, then the response `content` will continue directly from that last turn. You can use this to constrain the model's output.\n\nFor example, if the input `messages` were:\n```json\n[\n {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n {\"role\": \"assistant\", \"content\": \"The best answer is (\"}\n]\n```\n\nThen the response `content` might be:\n\n```json\n[{\"type\": \"text\", \"text\": \"B)\"}]\n```" + }), + "model": Model, + "stop_reason": Schema.Union([StopReason, Schema.Null]).annotate({ + "title": "Stop Reason", + "description": + "The reason that we stopped.\n\nThis may be one the following values:\n* `\"end_turn\"`: the model reached a natural stopping point\n* `\"max_tokens\"`: we exceeded the requested `max_tokens` or the model's maximum\n* `\"stop_sequence\"`: one of your provided custom `stop_sequences` was generated\n* `\"tool_use\"`: the model invoked one or more tools\n* `\"pause_turn\"`: we paused a long-running turn. You may provide the response back as-is in a subsequent request to let the model continue.\n* `\"refusal\"`: when streaming classifiers intervene to handle potential policy violations\n\nIn non-streaming mode this value is always non-null. In streaming mode, it is null in the `message_start` event and non-null otherwise." + }), + "stop_sequence": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Stop Sequence", + "description": + "Which custom stop sequence was generated, if any.\n\nThis value will be a non-null string if one of your custom stop sequences was generated.", + "default": null + }), + "usage": Schema.Struct({ + "cache_creation": Schema.Union([CacheCreation, Schema.Null]).annotate({ + "description": "Breakdown of cached tokens by TTL", + "default": null + }), + "cache_creation_input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Cache Creation Input Tokens", + "description": "The number of input tokens used to create the cache entry.", + "default": null + }), + "cache_read_input_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]).annotate({ + "title": "Cache Read Input Tokens", + "description": "The number of input tokens read from the cache.", + "default": null + }), + "inference_geo": Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Inference Geo", + "description": "The geographic region where inference was performed for this request.", + "default": null + }), + "input_tokens": Schema.Number.annotate({ + "title": "Input Tokens", + "description": "The number of input tokens which were used." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "output_tokens": Schema.Number.annotate({ + "title": "Output Tokens", + "description": "The number of output tokens which were used." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "server_tool_use": Schema.optionalKey( + Schema.Union([ServerToolUsage, Schema.Null]).annotate({ + "description": "The number of server tool requests.", + "default": null + }) + ), + "service_tier": Schema.Union([Schema.Literals(["standard", "priority", "batch"]), Schema.Null]).annotate({ + "title": "Service Tier", + "description": "If the request used the priority, standard, or batch tier.", + "default": null + }) + }).annotate({ + "title": "Usage", + "description": + "Billing and rate-limit usage.\n\nAnthropic's API bills and rate-limits by token counts, as tokens represent the underlying cost to our systems.\n\nUnder the hood, the API transforms requests into a format suitable for the model. The model's output then goes through a parsing stage before becoming an API response. As a result, the token counts in `usage` will not match one-to-one with the exact visible content of an API request or response.\n\nFor example, `output_tokens` will be non-zero, even for an empty string response from Claude.\n\nTotal input tokens in a request is the summation of `input_tokens`, `cache_creation_input_tokens`, and `cache_read_input_tokens`." + }), + "container": Schema.Union([Container, Schema.Null]).annotate({ + "description": + "Information about the container used in this request.\n\nThis will be non-null if a container tool (e.g. code execution) was used.", + "default": null + }) +}).annotate({ "title": "Message" }) +export type RequestWebFetchToolResultBlock = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "caller"?: DirectCaller | ServerToolCaller | ServerToolCaller_20260120 + readonly "content": RequestWebFetchToolResultError | RequestWebFetchResultBlock + readonly "tool_use_id": string + readonly "type": "web_fetch_tool_result" +} +export const RequestWebFetchToolResultBlock = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "caller": Schema.optionalKey( + Schema.Union([DirectCaller, ServerToolCaller, ServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "content": Schema.Union([RequestWebFetchToolResultError, RequestWebFetchResultBlock]).annotate({ + "title": "Content" + }), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^srvtoolu_[a-zA-Z0-9_]+$")) + ), + "type": Schema.Literal("web_fetch_tool_result").annotate({ "title": "Type" }) +}).annotate({ "title": "RequestWebFetchToolResultBlock" }) +export type BetaMessageStartEvent = { readonly "message": BetaMessage; readonly "type": "message_start" } +export const BetaMessageStartEvent = Schema.Struct({ + "message": BetaMessage, + "type": Schema.Literal("message_start").annotate({ "title": "Type", "default": "message_start" }) +}).annotate({ "title": "MessageStartEvent" }) +export type BetaSucceededResult = { readonly "message": BetaMessage; readonly "type": "succeeded" } +export const BetaSucceededResult = Schema.Struct({ + "message": BetaMessage, + "type": Schema.Literal("succeeded").annotate({ "title": "Type", "default": "succeeded" }) +}).annotate({ "title": "SucceededResult" }) +export type BetaInputContentBlock = + | { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "citations"?: + | ReadonlyArray< + | BetaRequestCharLocationCitation + | BetaRequestPageLocationCitation + | BetaRequestContentBlockLocationCitation + | BetaRequestWebSearchResultLocationCitation + | BetaRequestSearchResultLocationCitation + > + | null + readonly "text": string + readonly "type": "text" + } + | { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "source": BetaBase64ImageSource | BetaURLImageSource | BetaFileImageSource + readonly "type": "image" + } + | { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "citations"?: BetaRequestCitationsConfig | null + readonly "context"?: string | null + readonly "source": + | BetaBase64PDFSource + | BetaPlainTextSource + | BetaContentBlockSource + | BetaURLPDFSource + | BetaFileDocumentSource + readonly "title"?: string | null + readonly "type": "document" + } + | { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "citations"?: BetaRequestCitationsConfig + readonly "content": ReadonlyArray + readonly "source": string + readonly "title": string + readonly "type": "search_result" + } + | { readonly "signature": string; readonly "thinking": string; readonly "type": "thinking" } + | { readonly "data": string; readonly "type": "redacted_thinking" } + | { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "caller"?: BetaDirectCaller | BetaServerToolCaller | BetaServerToolCaller_20260120 + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": string + readonly "type": "tool_use" + } + | { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "content"?: + | string + | ReadonlyArray< + | BetaRequestTextBlock + | BetaRequestImageBlock + | BetaRequestSearchResultBlock + | BetaRequestDocumentBlock + | BetaRequestToolReferenceBlock + > + readonly "is_error"?: boolean + readonly "tool_use_id": string + readonly "type": "tool_result" + } + | BetaRequestServerToolUseBlock + | BetaRequestWebSearchToolResultBlock + | BetaRequestWebFetchToolResultBlock + | BetaRequestCodeExecutionToolResultBlock + | BetaRequestBashCodeExecutionToolResultBlock + | BetaRequestTextEditorCodeExecutionToolResultBlock + | BetaRequestToolSearchToolResultBlock + | BetaRequestMCPToolUseBlock + | BetaRequestMCPToolResultBlock + | BetaRequestContainerUploadBlock + | BetaRequestCompactionBlock +export const BetaInputContentBlock = Schema.Union([ + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([ + BetaRequestCharLocationCitation, + BetaRequestPageLocationCitation, + BetaRequestContentBlockLocationCitation, + BetaRequestWebSearchResultLocationCitation, + BetaRequestSearchResultLocationCitation + ], { mode: "oneOf" }) + ), + Schema.Null + ]).annotate({ "title": "Citations" }) + ), + "text": Schema.String.annotate({ "title": "Text" }).check(Schema.isMinLength(1)), + "type": Schema.Literal("text").annotate({ "title": "Type" }) + }).annotate({ "title": "RequestTextBlock", "description": "Regular text content." }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "source": Schema.Union([BetaBase64ImageSource, BetaURLImageSource, BetaFileImageSource], { mode: "oneOf" }) + .annotate({ "title": "Source" }), + "type": Schema.Literal("image").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestImageBlock", + "description": "Image content specified directly as base64 data or as a reference via a URL." + }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey(Schema.Union([BetaRequestCitationsConfig, Schema.Null])), + "context": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)), Schema.Null]).annotate({ "title": "Context" }) + ), + "source": Schema.Union([ + BetaBase64PDFSource, + BetaPlainTextSource, + BetaContentBlockSource, + BetaURLPDFSource, + BetaFileDocumentSource + ], { mode: "oneOf" }).annotate({ "title": "Source" }), + "title": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(500)), Schema.Null]).annotate({ + "title": "Title" + }) + ), + "type": Schema.Literal("document").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestDocumentBlock", + "description": "Document content, either specified directly as base64 data, as text, or as a reference via a URL." + }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey(BetaRequestCitationsConfig), + "content": Schema.Array(BetaRequestTextBlock).annotate({ "title": "Content" }), + "source": Schema.String.annotate({ "title": "Source" }), + "title": Schema.String.annotate({ "title": "Title" }), + "type": Schema.Literal("search_result").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestSearchResultBlock", + "description": "A search result block containing source, title, and content from search operations." + }), + Schema.Struct({ + "signature": Schema.String.annotate({ "title": "Signature" }), + "thinking": Schema.String.annotate({ "title": "Thinking" }), + "type": Schema.Literal("thinking").annotate({ "title": "Type" }) + }).annotate({ "title": "RequestThinkingBlock", "description": "A block specifying internal thinking by the model." }), + Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data" }), + "type": Schema.Literal("redacted_thinking").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestRedactedThinkingBlock", + "description": "A block specifying internal, redacted thinking by the model." + }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "caller": Schema.optionalKey( + Schema.Union([BetaDirectCaller, BetaServerToolCaller, BetaServerToolCaller_20260120], { mode: "oneOf" }).annotate( + { "title": "Caller" } + ) + ), + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.String.annotate({ "title": "Name" }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(200)), + "type": Schema.Literal("tool_use").annotate({ "title": "Type" }) + }).annotate({ "title": "RequestToolUseBlock", "description": "A block indicating a tool use by the model." }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Array( + Schema.Union([ + BetaRequestTextBlock, + BetaRequestImageBlock, + BetaRequestSearchResultBlock, + BetaRequestDocumentBlock, + BetaRequestToolReferenceBlock + ], { mode: "oneOf" }).annotate({ "title": "Block" }) + ) + ]).annotate({ "title": "Content" }) + ), + "is_error": Schema.optionalKey(Schema.Boolean.annotate({ "title": "Is Error" })), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$")) + ), + "type": Schema.Literal("tool_result").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestToolResultBlock", + "description": "A block specifying the results of a tool use by the model." + }), + BetaRequestServerToolUseBlock, + BetaRequestWebSearchToolResultBlock, + BetaRequestWebFetchToolResultBlock, + BetaRequestCodeExecutionToolResultBlock, + BetaRequestBashCodeExecutionToolResultBlock, + BetaRequestTextEditorCodeExecutionToolResultBlock, + BetaRequestToolSearchToolResultBlock, + BetaRequestMCPToolUseBlock, + BetaRequestMCPToolResultBlock, + BetaRequestContainerUploadBlock, + BetaRequestCompactionBlock +], { mode: "oneOf" }) +export type MessageStartEvent = { readonly "message": Message; readonly "type": "message_start" } +export const MessageStartEvent = Schema.Struct({ + "message": Message, + "type": Schema.Literal("message_start").annotate({ "title": "Type", "default": "message_start" }) +}).annotate({ "title": "MessageStartEvent" }) +export type SucceededResult = { readonly "message": Message; readonly "type": "succeeded" } +export const SucceededResult = Schema.Struct({ + "message": Message, + "type": Schema.Literal("succeeded").annotate({ "title": "Type", "default": "succeeded" }) +}).annotate({ "title": "SucceededResult" }) +export type InputContentBlock = + | { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "citations"?: + | ReadonlyArray< + | RequestCharLocationCitation + | RequestPageLocationCitation + | RequestContentBlockLocationCitation + | RequestWebSearchResultLocationCitation + | RequestSearchResultLocationCitation + > + | null + readonly "text": string + readonly "type": "text" + } + | { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "source": Base64ImageSource | URLImageSource + readonly "type": "image" + } + | { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "citations"?: RequestCitationsConfig | null + readonly "context"?: string | null + readonly "source": Base64PDFSource | PlainTextSource | ContentBlockSource | URLPDFSource + readonly "title"?: string | null + readonly "type": "document" + } + | { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "citations"?: RequestCitationsConfig + readonly "content": ReadonlyArray + readonly "source": string + readonly "title": string + readonly "type": "search_result" + } + | { readonly "signature": string; readonly "thinking": string; readonly "type": "thinking" } + | { readonly "data": string; readonly "type": "redacted_thinking" } + | { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "caller"?: DirectCaller | ServerToolCaller | ServerToolCaller_20260120 + readonly "id": string + readonly "input": { readonly [x: string]: Schema.Json } + readonly "name": string + readonly "type": "tool_use" + } + | { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "content"?: + | string + | ReadonlyArray< + | RequestTextBlock + | RequestImageBlock + | RequestSearchResultBlock + | RequestDocumentBlock + | RequestToolReferenceBlock + > + readonly "is_error"?: boolean + readonly "tool_use_id": string + readonly "type": "tool_result" + } + | RequestServerToolUseBlock + | RequestWebSearchToolResultBlock + | RequestWebFetchToolResultBlock + | RequestCodeExecutionToolResultBlock + | RequestBashCodeExecutionToolResultBlock + | RequestTextEditorCodeExecutionToolResultBlock + | RequestToolSearchToolResultBlock + | RequestContainerUploadBlock +export const InputContentBlock = Schema.Union([ + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([ + RequestCharLocationCitation, + RequestPageLocationCitation, + RequestContentBlockLocationCitation, + RequestWebSearchResultLocationCitation, + RequestSearchResultLocationCitation + ], { mode: "oneOf" }) + ), + Schema.Null + ]).annotate({ "title": "Citations" }) + ), + "text": Schema.String.annotate({ "title": "Text" }).check(Schema.isMinLength(1)), + "type": Schema.Literal("text").annotate({ "title": "Type" }) + }).annotate({ "title": "RequestTextBlock", "description": "Regular text content." }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "source": Schema.Union([Base64ImageSource, URLImageSource], { mode: "oneOf" }).annotate({ "title": "Source" }), + "type": Schema.Literal("image").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestImageBlock", + "description": "Image content specified directly as base64 data or as a reference via a URL." + }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey(Schema.Union([RequestCitationsConfig, Schema.Null])), + "context": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)), Schema.Null]).annotate({ "title": "Context" }) + ), + "source": Schema.Union([Base64PDFSource, PlainTextSource, ContentBlockSource, URLPDFSource], { mode: "oneOf" }) + .annotate({ "title": "Source" }), + "title": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(500)), Schema.Null]).annotate({ + "title": "Title" + }) + ), + "type": Schema.Literal("document").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestDocumentBlock", + "description": "Document content, either specified directly as base64 data, as text, or as a reference via a URL." + }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "citations": Schema.optionalKey(RequestCitationsConfig), + "content": Schema.Array(RequestTextBlock).annotate({ "title": "Content" }), + "source": Schema.String.annotate({ "title": "Source" }), + "title": Schema.String.annotate({ "title": "Title" }), + "type": Schema.Literal("search_result").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestSearchResultBlock", + "description": "A search result block containing source, title, and content from search operations." + }), + Schema.Struct({ + "signature": Schema.String.annotate({ "title": "Signature" }), + "thinking": Schema.String.annotate({ "title": "Thinking" }), + "type": Schema.Literal("thinking").annotate({ "title": "Type" }) + }).annotate({ "title": "RequestThinkingBlock", "description": "A block specifying internal thinking by the model." }), + Schema.Struct({ + "data": Schema.String.annotate({ "title": "Data" }), + "type": Schema.Literal("redacted_thinking").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestRedactedThinkingBlock", + "description": "A block specifying internal, redacted thinking by the model." + }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "caller": Schema.optionalKey( + Schema.Union([DirectCaller, ServerToolCaller, ServerToolCaller_20260120], { mode: "oneOf" }).annotate({ + "title": "Caller" + }) + ), + "id": Schema.String.annotate({ "title": "Id" }).check(Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$"))), + "input": Schema.Record(Schema.String, Schema.Json).annotate({ "title": "Input" }), + "name": Schema.String.annotate({ "title": "Name" }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(200)), + "type": Schema.Literal("tool_use").annotate({ "title": "Type" }) + }).annotate({ "title": "RequestToolUseBlock", "description": "A block indicating a tool use by the model." }), + Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": "Create a cache control breakpoint at this content block." + }) + ), + "content": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Array( + Schema.Union([ + RequestTextBlock, + RequestImageBlock, + RequestSearchResultBlock, + RequestDocumentBlock, + RequestToolReferenceBlock + ], { mode: "oneOf" }).annotate({ "title": "Block" }) + ) + ]).annotate({ "title": "Content" }) + ), + "is_error": Schema.optionalKey(Schema.Boolean.annotate({ "title": "Is Error" })), + "tool_use_id": Schema.String.annotate({ "title": "Tool Use Id" }).check( + Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$")) + ), + "type": Schema.Literal("tool_result").annotate({ "title": "Type" }) + }).annotate({ + "title": "RequestToolResultBlock", + "description": "A block specifying the results of a tool use by the model." + }), + RequestServerToolUseBlock, + RequestWebSearchToolResultBlock, + RequestWebFetchToolResultBlock, + RequestCodeExecutionToolResultBlock, + RequestBashCodeExecutionToolResultBlock, + RequestTextEditorCodeExecutionToolResultBlock, + RequestToolSearchToolResultBlock, + RequestContainerUploadBlock +], { mode: "oneOf" }) +export type BetaInputMessage = { + readonly "content": string | ReadonlyArray + readonly "role": "user" | "assistant" +} +export const BetaInputMessage = Schema.Struct({ + "content": Schema.Union([Schema.String, Schema.Array(BetaInputContentBlock)]).annotate({ "title": "Content" }), + "role": Schema.Literals(["user", "assistant"]).annotate({ "title": "Role" }) +}).annotate({ "title": "InputMessage" }) +export type InputMessage = { + readonly "content": string | ReadonlyArray + readonly "role": "user" | "assistant" +} +export const InputMessage = Schema.Struct({ + "content": Schema.Union([Schema.String, Schema.Array(InputContentBlock)]).annotate({ "title": "Content" }), + "role": Schema.Literals(["user", "assistant"]).annotate({ "title": "Role" }) +}).annotate({ "title": "InputMessage" }) +export type BetaCountMessageTokensParams = { + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "context_management"?: BetaContextManagementConfig | null + readonly "mcp_servers"?: ReadonlyArray + readonly "messages": ReadonlyArray + readonly "model": Model + readonly "output_config"?: { + readonly "effort"?: BetaEffortLevel | null + readonly "format"?: BetaJsonOutputFormat | null + } + readonly "output_format"?: BetaJsonOutputFormat | null + readonly "speed"?: BetaSpeed | null + readonly "system"?: string | ReadonlyArray + readonly "thinking"?: BetaThinkingConfigParam + readonly "tool_choice"?: BetaToolChoice + readonly "tools"?: ReadonlyArray< + | BetaTool + | BetaBashTool_20241022 + | BetaBashTool_20250124 + | BetaCodeExecutionTool_20250522 + | BetaCodeExecutionTool_20250825 + | BetaCodeExecutionTool_20260120 + | BetaComputerUseTool_20241022 + | BetaMemoryTool_20250818 + | BetaComputerUseTool_20250124 + | BetaTextEditor_20241022 + | BetaComputerUseTool_20251124 + | BetaTextEditor_20250124 + | BetaTextEditor_20250429 + | BetaTextEditor_20250728 + | BetaWebSearchTool_20250305 + | BetaWebFetchTool_20250910 + | BetaWebSearchTool_20260209 + | BetaWebFetchTool_20260209 + | BetaToolSearchToolBM25_20251119 + | BetaToolSearchToolRegex_20251119 + | BetaMCPToolset + > +} +export const BetaCountMessageTokensParams = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": + "Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request." + }) + ), + "context_management": Schema.optionalKey( + Schema.Union([BetaContextManagementConfig, Schema.Null]).annotate({ + "description": + "Context management configuration.\n\nThis allows you to control how Claude manages context across multiple requests, such as whether to clear function results or not." + }) + ), + "mcp_servers": Schema.optionalKey( + Schema.Array(BetaRequestMCPServerURLDefinition).annotate({ + "title": "Mcp Servers", + "description": "MCP servers to be utilized in this request" + }).check(Schema.isMaxLength(20)) + ), + "messages": Schema.Array(BetaInputMessage).annotate({ + "title": "Messages", + "description": + "Input messages.\n\nOur models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n\nEach input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n\nIf the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n\nExample with a single `user` message:\n\n```json\n[{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n```\n\nExample with multiple conversational turns:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"Hello there.\"},\n {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n]\n```\n\nExample with a partially-filled response from Claude:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n]\n```\n\nEach input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n\n```json\n{\"role\": \"user\", \"content\": \"Hello, Claude\"}\n```\n\n```json\n{\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n```\n\nSee [input examples](https://docs.claude.com/en/api/messages-examples).\n\nNote that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n\nThere is a limit of 100,000 messages in a single request." + }), + "model": Model, + "output_config": Schema.optionalKey( + Schema.Struct({ + "effort": Schema.optionalKey( + Schema.Union([BetaEffortLevel, Schema.Null]).annotate({ + "description": + "How much effort the model should put into its response. Higher effort levels may result in more thorough analysis but take longer.\n\nValid values are `low`, `medium`, `high`, or `max`." + }) + ), + "format": Schema.optionalKey( + Schema.Union([BetaJsonOutputFormat, Schema.Null]).annotate({ + "description": + "A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)" + }) + ) + }).annotate({ + "title": "OutputConfig", + "description": "Configuration options for the model's output, such as the output format." + }) + ), + "output_format": Schema.optionalKey( + Schema.Union([BetaJsonOutputFormat, Schema.Null]).annotate({ + "description": + "Deprecated: Use `output_config.format` instead. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)\n\nA schema to specify Claude's output format in responses. This parameter will be removed in a future release." + }) + ), + "speed": Schema.optionalKey( + Schema.Union([BetaSpeed, Schema.Null]).annotate({ + "description": + "The inference speed mode for this request. `\"fast\"` enables high output-tokens-per-second inference." + }) + ), + "system": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Array(BetaRequestTextBlock)]).annotate({ + "title": "System", + "description": + "System prompt.\n\nA system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts)." + }) + ), + "thinking": Schema.optionalKey(BetaThinkingConfigParam), + "tool_choice": Schema.optionalKey(BetaToolChoice), + "tools": Schema.optionalKey( + Schema.Array( + Schema.Union([ + BetaTool, + BetaBashTool_20241022, + BetaBashTool_20250124, + BetaCodeExecutionTool_20250522, + BetaCodeExecutionTool_20250825, + BetaCodeExecutionTool_20260120, + BetaComputerUseTool_20241022, + BetaMemoryTool_20250818, + BetaComputerUseTool_20250124, + BetaTextEditor_20241022, + BetaComputerUseTool_20251124, + BetaTextEditor_20250124, + BetaTextEditor_20250429, + BetaTextEditor_20250728, + BetaWebSearchTool_20250305, + BetaWebFetchTool_20250910, + BetaWebSearchTool_20260209, + BetaWebFetchTool_20260209, + BetaToolSearchToolBM25_20251119, + BetaToolSearchToolRegex_20251119, + BetaMCPToolset + ], { mode: "oneOf" }) + ).annotate({ + "title": "Tools", + "description": + "Definitions of tools that the model may use.\n\nIf you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n\nThere are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n\nEach tool definition includes:\n\n* `name`: Name of the tool.\n* `description`: Optional, but strongly-recommended description of the tool.\n* `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n\nFor example, if you defined `tools` as:\n\n```json\n[\n {\n \"name\": \"get_stock_price\",\n \"description\": \"Get the current stock price for a given ticker symbol.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"ticker\": {\n \"type\": \"string\",\n \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n }\n },\n \"required\": [\"ticker\"]\n }\n }\n]\n```\n\nAnd then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n\n```json\n[\n {\n \"type\": \"tool_use\",\n \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"name\": \"get_stock_price\",\n \"input\": { \"ticker\": \"^GSPC\" }\n }\n]\n```\n\nYou might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n\n```json\n[\n {\n \"type\": \"tool_result\",\n \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"content\": \"259.75 USD\"\n }\n]\n```\n\nTools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n\nSee our [guide](https://docs.claude.com/en/docs/tool-use) for more details." + }) + ) +}).annotate({ "title": "CountMessageTokensParams" }) +export type BetaCreateMessageParams = { + readonly "model": Model + readonly "messages": ReadonlyArray + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "container"?: BetaContainerParams | string | null + readonly "context_management"?: BetaContextManagementConfig | null + readonly "inference_geo"?: string | null + readonly "max_tokens": number + readonly "mcp_servers"?: ReadonlyArray + readonly "metadata"?: { readonly "user_id"?: string | null } + readonly "output_config"?: { + readonly "effort"?: BetaEffortLevel | null + readonly "format"?: BetaJsonOutputFormat | null + } + readonly "output_format"?: BetaJsonOutputFormat | null + readonly "service_tier"?: "auto" | "standard_only" + readonly "speed"?: BetaSpeed | null + readonly "stop_sequences"?: ReadonlyArray + readonly "stream"?: boolean + readonly "system"?: string | ReadonlyArray + readonly "temperature"?: number + readonly "thinking"?: BetaThinkingConfigParam + readonly "tool_choice"?: BetaToolChoice + readonly "tools"?: ReadonlyArray< + | BetaTool + | BetaBashTool_20241022 + | BetaBashTool_20250124 + | BetaCodeExecutionTool_20250522 + | BetaCodeExecutionTool_20250825 + | BetaCodeExecutionTool_20260120 + | BetaComputerUseTool_20241022 + | BetaMemoryTool_20250818 + | BetaComputerUseTool_20250124 + | BetaTextEditor_20241022 + | BetaComputerUseTool_20251124 + | BetaTextEditor_20250124 + | BetaTextEditor_20250429 + | BetaTextEditor_20250728 + | BetaWebSearchTool_20250305 + | BetaWebFetchTool_20250910 + | BetaWebSearchTool_20260209 + | BetaWebFetchTool_20260209 + | BetaToolSearchToolBM25_20251119 + | BetaToolSearchToolRegex_20251119 + | BetaMCPToolset + > + readonly "top_k"?: number + readonly "top_p"?: number +} +export const BetaCreateMessageParams = Schema.Struct({ + "model": Model, + "messages": Schema.Array(BetaInputMessage).annotate({ + "title": "Messages", + "description": + "Input messages.\n\nOur models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n\nEach input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n\nIf the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n\nExample with a single `user` message:\n\n```json\n[{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n```\n\nExample with multiple conversational turns:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"Hello there.\"},\n {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n]\n```\n\nExample with a partially-filled response from Claude:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n]\n```\n\nEach input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n\n```json\n{\"role\": \"user\", \"content\": \"Hello, Claude\"}\n```\n\n```json\n{\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n```\n\nSee [input examples](https://docs.claude.com/en/api/messages-examples).\n\nNote that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n\nThere is a limit of 100,000 messages in a single request." + }), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": + "Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request." + }) + ), + "container": Schema.optionalKey( + Schema.Union([BetaContainerParams, Schema.String, Schema.Null]).annotate({ + "title": "Container", + "description": "Container identifier for reuse across requests." + }) + ), + "context_management": Schema.optionalKey( + Schema.Union([BetaContextManagementConfig, Schema.Null]).annotate({ + "description": + "Context management configuration.\n\nThis allows you to control how Claude manages context across multiple requests, such as whether to clear function results or not." + }) + ), + "inference_geo": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Inference Geo", + "description": + "Specifies the geographic region for inference processing. If not specified, the workspace's `default_inference_geo` is used." + }) + ), + "max_tokens": Schema.Number.annotate({ + "title": "Max Tokens", + "description": + "The maximum number of tokens to generate before stopping.\n\nNote that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate.\n\nDifferent models have different maximum values for this parameter. See [models](https://docs.claude.com/en/docs/models-overview) for details." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "mcp_servers": Schema.optionalKey( + Schema.Array(BetaRequestMCPServerURLDefinition).annotate({ + "title": "Mcp Servers", + "description": "MCP servers to be utilized in this request" + }).check(Schema.isMaxLength(20)) + ), + "metadata": Schema.optionalKey( + Schema.Struct({ + "user_id": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMaxLength(256)), Schema.Null]).annotate({ + "title": "User Id", + "description": + "An external identifier for the user who is associated with the request.\n\nThis should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number." + }) + ) + }).annotate({ "title": "Metadata", "description": "An object describing metadata about the request." }) + ), + "output_config": Schema.optionalKey( + Schema.Struct({ + "effort": Schema.optionalKey( + Schema.Union([BetaEffortLevel, Schema.Null]).annotate({ + "description": + "How much effort the model should put into its response. Higher effort levels may result in more thorough analysis but take longer.\n\nValid values are `low`, `medium`, `high`, or `max`." + }) + ), + "format": Schema.optionalKey( + Schema.Union([BetaJsonOutputFormat, Schema.Null]).annotate({ + "description": + "A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)" + }) + ) + }).annotate({ + "title": "OutputConfig", + "description": "Configuration options for the model's output, such as the output format." + }) + ), + "output_format": Schema.optionalKey( + Schema.Union([BetaJsonOutputFormat, Schema.Null]).annotate({ + "description": + "Deprecated: Use `output_config.format` instead. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)\n\nA schema to specify Claude's output format in responses. This parameter will be removed in a future release." + }) + ), + "service_tier": Schema.optionalKey( + Schema.Literals(["auto", "standard_only"]).annotate({ + "title": "Service Tier", + "description": + "Determines whether to use priority capacity (if available) or standard capacity for this request.\n\nAnthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details." + }) + ), + "speed": Schema.optionalKey( + Schema.Union([BetaSpeed, Schema.Null]).annotate({ + "description": + "The inference speed mode for this request. `\"fast\"` enables high output-tokens-per-second inference." + }) + ), + "stop_sequences": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "title": "Stop Sequences", + "description": + "Custom text sequences that will cause the model to stop generating.\n\nOur models will normally stop when they have naturally completed their turn, which will result in a response `stop_reason` of `\"end_turn\"`.\n\nIf you want the model to stop generating when it encounters custom strings of text, you can use the `stop_sequences` parameter. If the model encounters one of the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"` and the response `stop_sequence` value will contain the matched stop sequence." + }) + ), + "stream": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Stream", + "description": + "Whether to incrementally stream the response using server-sent events.\n\nSee [streaming](https://docs.claude.com/en/api/messages-streaming) for details." + }) + ), + "system": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Array(BetaRequestTextBlock)]).annotate({ + "title": "System", + "description": + "System prompt.\n\nA system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts)." + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Temperature", + "description": + "Amount of randomness injected into the response.\n\nDefaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for analytical / multiple choice, and closer to `1.0` for creative and generative tasks.\n\nNote that even with `temperature` of `0.0`, the results will not be fully deterministic." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ), + "thinking": Schema.optionalKey(BetaThinkingConfigParam), + "tool_choice": Schema.optionalKey(BetaToolChoice), + "tools": Schema.optionalKey( + Schema.Array( + Schema.Union([ + BetaTool, + BetaBashTool_20241022, + BetaBashTool_20250124, + BetaCodeExecutionTool_20250522, + BetaCodeExecutionTool_20250825, + BetaCodeExecutionTool_20260120, + BetaComputerUseTool_20241022, + BetaMemoryTool_20250818, + BetaComputerUseTool_20250124, + BetaTextEditor_20241022, + BetaComputerUseTool_20251124, + BetaTextEditor_20250124, + BetaTextEditor_20250429, + BetaTextEditor_20250728, + BetaWebSearchTool_20250305, + BetaWebFetchTool_20250910, + BetaWebSearchTool_20260209, + BetaWebFetchTool_20260209, + BetaToolSearchToolBM25_20251119, + BetaToolSearchToolRegex_20251119, + BetaMCPToolset + ], { mode: "oneOf" }) + ).annotate({ + "title": "Tools", + "description": + "Definitions of tools that the model may use.\n\nIf you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n\nThere are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n\nEach tool definition includes:\n\n* `name`: Name of the tool.\n* `description`: Optional, but strongly-recommended description of the tool.\n* `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n\nFor example, if you defined `tools` as:\n\n```json\n[\n {\n \"name\": \"get_stock_price\",\n \"description\": \"Get the current stock price for a given ticker symbol.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"ticker\": {\n \"type\": \"string\",\n \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n }\n },\n \"required\": [\"ticker\"]\n }\n }\n]\n```\n\nAnd then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n\n```json\n[\n {\n \"type\": \"tool_use\",\n \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"name\": \"get_stock_price\",\n \"input\": { \"ticker\": \"^GSPC\" }\n }\n]\n```\n\nYou might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n\n```json\n[\n {\n \"type\": \"tool_result\",\n \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"content\": \"259.75 USD\"\n }\n]\n```\n\nTools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n\nSee our [guide](https://docs.claude.com/en/docs/tool-use) for more details." + }) + ), + "top_k": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top K", + "description": + "Only sample from the top K options for each subsequent token.\n\nUsed to remove \"long tail\" low probability responses. [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) + ), + "top_p": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top P", + "description": + "Use nucleus sampling.\n\nIn nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ) +}).annotate({ "title": "CreateMessageParams" }) +export type BetaMessageBatchIndividualRequestParams = { + readonly "custom_id": string + readonly "params": { + readonly "model": Model + readonly "messages": ReadonlyArray + readonly "cache_control"?: BetaCacheControlEphemeral | null + readonly "container"?: BetaContainerParams | string | null + readonly "context_management"?: BetaContextManagementConfig | null + readonly "inference_geo"?: string | null + readonly "max_tokens": number + readonly "mcp_servers"?: ReadonlyArray + readonly "metadata"?: { readonly "user_id"?: string | null } + readonly "output_config"?: { + readonly "effort"?: BetaEffortLevel | null + readonly "format"?: BetaJsonOutputFormat | null + } + readonly "output_format"?: BetaJsonOutputFormat | null + readonly "service_tier"?: "auto" | "standard_only" + readonly "speed"?: BetaSpeed | null + readonly "stop_sequences"?: ReadonlyArray + readonly "stream"?: boolean + readonly "system"?: string | ReadonlyArray + readonly "temperature"?: number + readonly "thinking"?: BetaThinkingConfigParam + readonly "tool_choice"?: BetaToolChoice + readonly "tools"?: ReadonlyArray< + | BetaTool + | BetaBashTool_20241022 + | BetaBashTool_20250124 + | BetaCodeExecutionTool_20250522 + | BetaCodeExecutionTool_20250825 + | BetaCodeExecutionTool_20260120 + | BetaComputerUseTool_20241022 + | BetaMemoryTool_20250818 + | BetaComputerUseTool_20250124 + | BetaTextEditor_20241022 + | BetaComputerUseTool_20251124 + | BetaTextEditor_20250124 + | BetaTextEditor_20250429 + | BetaTextEditor_20250728 + | BetaWebSearchTool_20250305 + | BetaWebFetchTool_20250910 + | BetaWebSearchTool_20260209 + | BetaWebFetchTool_20260209 + | BetaToolSearchToolBM25_20251119 + | BetaToolSearchToolRegex_20251119 + | BetaMCPToolset + > + readonly "top_k"?: number + readonly "top_p"?: number + } +} +export const BetaMessageBatchIndividualRequestParams = Schema.Struct({ + "custom_id": Schema.String.annotate({ + "title": "Custom Id", + "description": + "Developer-provided ID created for each request in a Message Batch. Useful for matching results to requests, as results may be given out of request order.\n\nMust be unique for each request within the Message Batch." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)).check( + Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]{1,64}$")) + ), + "params": Schema.Struct({ + "model": Model, + "messages": Schema.Array(BetaInputMessage).annotate({ + "title": "Messages", + "description": + "Input messages.\n\nOur models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n\nEach input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n\nIf the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n\nExample with a single `user` message:\n\n```json\n[{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n```\n\nExample with multiple conversational turns:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"Hello there.\"},\n {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n]\n```\n\nExample with a partially-filled response from Claude:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n]\n```\n\nEach input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n\n```json\n{\"role\": \"user\", \"content\": \"Hello, Claude\"}\n```\n\n```json\n{\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n```\n\nSee [input examples](https://docs.claude.com/en/api/messages-examples).\n\nNote that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n\nThere is a limit of 100,000 messages in a single request." + }), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([BetaCacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": + "Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request." + }) + ), + "container": Schema.optionalKey( + Schema.Union([BetaContainerParams, Schema.String, Schema.Null]).annotate({ + "title": "Container", + "description": "Container identifier for reuse across requests." + }) + ), + "context_management": Schema.optionalKey( + Schema.Union([BetaContextManagementConfig, Schema.Null]).annotate({ + "description": + "Context management configuration.\n\nThis allows you to control how Claude manages context across multiple requests, such as whether to clear function results or not." + }) + ), + "inference_geo": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Inference Geo", + "description": + "Specifies the geographic region for inference processing. If not specified, the workspace's `default_inference_geo` is used." + }) + ), + "max_tokens": Schema.Number.annotate({ + "title": "Max Tokens", + "description": + "The maximum number of tokens to generate before stopping.\n\nNote that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate.\n\nDifferent models have different maximum values for this parameter. See [models](https://docs.claude.com/en/docs/models-overview) for details." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "mcp_servers": Schema.optionalKey( + Schema.Array(BetaRequestMCPServerURLDefinition).annotate({ + "title": "Mcp Servers", + "description": "MCP servers to be utilized in this request" + }).check(Schema.isMaxLength(20)) + ), + "metadata": Schema.optionalKey( + Schema.Struct({ + "user_id": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMaxLength(256)), Schema.Null]).annotate({ + "title": "User Id", + "description": + "An external identifier for the user who is associated with the request.\n\nThis should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number." + }) + ) + }).annotate({ "title": "Metadata", "description": "An object describing metadata about the request." }) + ), + "output_config": Schema.optionalKey( + Schema.Struct({ + "effort": Schema.optionalKey( + Schema.Union([BetaEffortLevel, Schema.Null]).annotate({ + "description": + "How much effort the model should put into its response. Higher effort levels may result in more thorough analysis but take longer.\n\nValid values are `low`, `medium`, `high`, or `max`." + }) + ), + "format": Schema.optionalKey( + Schema.Union([BetaJsonOutputFormat, Schema.Null]).annotate({ + "description": + "A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)" + }) + ) + }).annotate({ + "title": "OutputConfig", + "description": "Configuration options for the model's output, such as the output format." + }) + ), + "output_format": Schema.optionalKey( + Schema.Union([BetaJsonOutputFormat, Schema.Null]).annotate({ + "description": + "Deprecated: Use `output_config.format` instead. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)\n\nA schema to specify Claude's output format in responses. This parameter will be removed in a future release." + }) + ), + "service_tier": Schema.optionalKey( + Schema.Literals(["auto", "standard_only"]).annotate({ + "title": "Service Tier", + "description": + "Determines whether to use priority capacity (if available) or standard capacity for this request.\n\nAnthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details." + }) + ), + "speed": Schema.optionalKey( + Schema.Union([BetaSpeed, Schema.Null]).annotate({ + "description": + "The inference speed mode for this request. `\"fast\"` enables high output-tokens-per-second inference." + }) + ), + "stop_sequences": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "title": "Stop Sequences", + "description": + "Custom text sequences that will cause the model to stop generating.\n\nOur models will normally stop when they have naturally completed their turn, which will result in a response `stop_reason` of `\"end_turn\"`.\n\nIf you want the model to stop generating when it encounters custom strings of text, you can use the `stop_sequences` parameter. If the model encounters one of the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"` and the response `stop_sequence` value will contain the matched stop sequence." + }) + ), + "stream": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Stream", + "description": + "Whether to incrementally stream the response using server-sent events.\n\nSee [streaming](https://docs.claude.com/en/api/messages-streaming) for details." + }) + ), + "system": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Array(BetaRequestTextBlock)]).annotate({ + "title": "System", + "description": + "System prompt.\n\nA system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts)." + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Temperature", + "description": + "Amount of randomness injected into the response.\n\nDefaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for analytical / multiple choice, and closer to `1.0` for creative and generative tasks.\n\nNote that even with `temperature` of `0.0`, the results will not be fully deterministic." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ), + "thinking": Schema.optionalKey(BetaThinkingConfigParam), + "tool_choice": Schema.optionalKey(BetaToolChoice), + "tools": Schema.optionalKey( + Schema.Array( + Schema.Union([ + BetaTool, + BetaBashTool_20241022, + BetaBashTool_20250124, + BetaCodeExecutionTool_20250522, + BetaCodeExecutionTool_20250825, + BetaCodeExecutionTool_20260120, + BetaComputerUseTool_20241022, + BetaMemoryTool_20250818, + BetaComputerUseTool_20250124, + BetaTextEditor_20241022, + BetaComputerUseTool_20251124, + BetaTextEditor_20250124, + BetaTextEditor_20250429, + BetaTextEditor_20250728, + BetaWebSearchTool_20250305, + BetaWebFetchTool_20250910, + BetaWebSearchTool_20260209, + BetaWebFetchTool_20260209, + BetaToolSearchToolBM25_20251119, + BetaToolSearchToolRegex_20251119, + BetaMCPToolset + ], { mode: "oneOf" }) + ).annotate({ + "title": "Tools", + "description": + "Definitions of tools that the model may use.\n\nIf you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n\nThere are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n\nEach tool definition includes:\n\n* `name`: Name of the tool.\n* `description`: Optional, but strongly-recommended description of the tool.\n* `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n\nFor example, if you defined `tools` as:\n\n```json\n[\n {\n \"name\": \"get_stock_price\",\n \"description\": \"Get the current stock price for a given ticker symbol.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"ticker\": {\n \"type\": \"string\",\n \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n }\n },\n \"required\": [\"ticker\"]\n }\n }\n]\n```\n\nAnd then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n\n```json\n[\n {\n \"type\": \"tool_use\",\n \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"name\": \"get_stock_price\",\n \"input\": { \"ticker\": \"^GSPC\" }\n }\n]\n```\n\nYou might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n\n```json\n[\n {\n \"type\": \"tool_result\",\n \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"content\": \"259.75 USD\"\n }\n]\n```\n\nTools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n\nSee our [guide](https://docs.claude.com/en/docs/tool-use) for more details." + }) + ), + "top_k": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top K", + "description": + "Only sample from the top K options for each subsequent token.\n\nUsed to remove \"long tail\" low probability responses. [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) + ), + "top_p": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top P", + "description": + "Use nucleus sampling.\n\nIn nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ) + }).annotate({ + "title": "CreateMessageParams", + "description": + "Messages API creation parameters for the individual request.\n\nSee the [Messages API reference](https://docs.claude.com/en/api/messages) for full documentation on available parameters." + }) +}).annotate({ "title": "MessageBatchIndividualRequestParams" }) +export type CountMessageTokensParams = { + readonly "cache_control"?: CacheControlEphemeral | null + readonly "messages": ReadonlyArray + readonly "model": Model + readonly "output_config"?: { readonly "effort"?: EffortLevel | null; readonly "format"?: JsonOutputFormat | null } + readonly "system"?: string | ReadonlyArray + readonly "thinking"?: ThinkingConfigParam + readonly "tool_choice"?: ToolChoice + readonly "tools"?: ReadonlyArray< + | Tool + | BashTool_20250124 + | CodeExecutionTool_20250522 + | CodeExecutionTool_20250825 + | CodeExecutionTool_20260120 + | MemoryTool_20250818 + | TextEditor_20250124 + | TextEditor_20250429 + | TextEditor_20250728 + | WebSearchTool_20250305 + | WebFetchTool_20250910 + | WebSearchTool_20260209 + | WebFetchTool_20260209 + | ToolSearchToolBM25_20251119 + | ToolSearchToolRegex_20251119 + > +} +export const CountMessageTokensParams = Schema.Struct({ + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": + "Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request." + }) + ), + "messages": Schema.Array(InputMessage).annotate({ + "title": "Messages", + "description": + "Input messages.\n\nOur models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n\nEach input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n\nIf the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n\nExample with a single `user` message:\n\n```json\n[{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n```\n\nExample with multiple conversational turns:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"Hello there.\"},\n {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n]\n```\n\nExample with a partially-filled response from Claude:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n]\n```\n\nEach input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n\n```json\n{\"role\": \"user\", \"content\": \"Hello, Claude\"}\n```\n\n```json\n{\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n```\n\nSee [input examples](https://docs.claude.com/en/api/messages-examples).\n\nNote that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n\nThere is a limit of 100,000 messages in a single request." + }), + "model": Model, + "output_config": Schema.optionalKey( + Schema.Struct({ + "effort": Schema.optionalKey( + Schema.Union([EffortLevel, Schema.Null]).annotate({ + "description": + "How much effort the model should put into its response. Higher effort levels may result in more thorough analysis but take longer.\n\nValid values are `low`, `medium`, `high`, or `max`." + }) + ), + "format": Schema.optionalKey( + Schema.Union([JsonOutputFormat, Schema.Null]).annotate({ + "description": + "A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)" + }) + ) + }).annotate({ + "title": "OutputConfig", + "description": "Configuration options for the model's output, such as the output format." + }) + ), + "system": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Array(RequestTextBlock)]).annotate({ + "title": "System", + "description": + "System prompt.\n\nA system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts)." + }) + ), + "thinking": Schema.optionalKey(ThinkingConfigParam), + "tool_choice": Schema.optionalKey(ToolChoice), + "tools": Schema.optionalKey( + Schema.Array( + Schema.Union([ + Tool, + BashTool_20250124, + CodeExecutionTool_20250522, + CodeExecutionTool_20250825, + CodeExecutionTool_20260120, + MemoryTool_20250818, + TextEditor_20250124, + TextEditor_20250429, + TextEditor_20250728, + WebSearchTool_20250305, + WebFetchTool_20250910, + WebSearchTool_20260209, + WebFetchTool_20260209, + ToolSearchToolBM25_20251119, + ToolSearchToolRegex_20251119 + ], { mode: "oneOf" }) + ).annotate({ + "title": "Tools", + "description": + "Definitions of tools that the model may use.\n\nIf you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n\nThere are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n\nEach tool definition includes:\n\n* `name`: Name of the tool.\n* `description`: Optional, but strongly-recommended description of the tool.\n* `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n\nFor example, if you defined `tools` as:\n\n```json\n[\n {\n \"name\": \"get_stock_price\",\n \"description\": \"Get the current stock price for a given ticker symbol.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"ticker\": {\n \"type\": \"string\",\n \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n }\n },\n \"required\": [\"ticker\"]\n }\n }\n]\n```\n\nAnd then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n\n```json\n[\n {\n \"type\": \"tool_use\",\n \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"name\": \"get_stock_price\",\n \"input\": { \"ticker\": \"^GSPC\" }\n }\n]\n```\n\nYou might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n\n```json\n[\n {\n \"type\": \"tool_result\",\n \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"content\": \"259.75 USD\"\n }\n]\n```\n\nTools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n\nSee our [guide](https://docs.claude.com/en/docs/tool-use) for more details." + }) + ) +}).annotate({ "title": "CountMessageTokensParams" }) +export type CreateMessageParams = { + readonly "model": Model + readonly "messages": ReadonlyArray + readonly "cache_control"?: CacheControlEphemeral | null + readonly "container"?: string | null + readonly "inference_geo"?: string | null + readonly "max_tokens": number + readonly "metadata"?: { readonly "user_id"?: string | null } + readonly "output_config"?: { readonly "effort"?: EffortLevel | null; readonly "format"?: JsonOutputFormat | null } + readonly "service_tier"?: "auto" | "standard_only" + readonly "stop_sequences"?: ReadonlyArray + readonly "stream"?: boolean + readonly "system"?: string | ReadonlyArray + readonly "temperature"?: number + readonly "thinking"?: ThinkingConfigParam + readonly "tool_choice"?: ToolChoice + readonly "tools"?: ReadonlyArray< + | Tool + | BashTool_20250124 + | CodeExecutionTool_20250522 + | CodeExecutionTool_20250825 + | CodeExecutionTool_20260120 + | MemoryTool_20250818 + | TextEditor_20250124 + | TextEditor_20250429 + | TextEditor_20250728 + | WebSearchTool_20250305 + | WebFetchTool_20250910 + | WebSearchTool_20260209 + | WebFetchTool_20260209 + | ToolSearchToolBM25_20251119 + | ToolSearchToolRegex_20251119 + > + readonly "top_k"?: number + readonly "top_p"?: number +} +export const CreateMessageParams = Schema.Struct({ + "model": Model, + "messages": Schema.Array(InputMessage).annotate({ + "title": "Messages", + "description": + "Input messages.\n\nOur models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n\nEach input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n\nIf the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n\nExample with a single `user` message:\n\n```json\n[{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n```\n\nExample with multiple conversational turns:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"Hello there.\"},\n {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n]\n```\n\nExample with a partially-filled response from Claude:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n]\n```\n\nEach input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n\n```json\n{\"role\": \"user\", \"content\": \"Hello, Claude\"}\n```\n\n```json\n{\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n```\n\nSee [input examples](https://docs.claude.com/en/api/messages-examples).\n\nNote that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n\nThere is a limit of 100,000 messages in a single request." + }), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": + "Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request." + }) + ), + "container": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Container", + "description": "Container identifier for reuse across requests." + }) + ), + "inference_geo": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Inference Geo", + "description": + "Specifies the geographic region for inference processing. If not specified, the workspace's `default_inference_geo` is used." + }) + ), + "max_tokens": Schema.Number.annotate({ + "title": "Max Tokens", + "description": + "The maximum number of tokens to generate before stopping.\n\nNote that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate.\n\nDifferent models have different maximum values for this parameter. See [models](https://docs.claude.com/en/docs/models-overview) for details." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "metadata": Schema.optionalKey( + Schema.Struct({ + "user_id": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMaxLength(256)), Schema.Null]).annotate({ + "title": "User Id", + "description": + "An external identifier for the user who is associated with the request.\n\nThis should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number." + }) + ) + }).annotate({ "title": "Metadata", "description": "An object describing metadata about the request." }) + ), + "output_config": Schema.optionalKey( + Schema.Struct({ + "effort": Schema.optionalKey( + Schema.Union([EffortLevel, Schema.Null]).annotate({ + "description": + "How much effort the model should put into its response. Higher effort levels may result in more thorough analysis but take longer.\n\nValid values are `low`, `medium`, `high`, or `max`." + }) + ), + "format": Schema.optionalKey( + Schema.Union([JsonOutputFormat, Schema.Null]).annotate({ + "description": + "A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)" + }) + ) + }).annotate({ + "title": "OutputConfig", + "description": "Configuration options for the model's output, such as the output format." + }) + ), + "service_tier": Schema.optionalKey( + Schema.Literals(["auto", "standard_only"]).annotate({ + "title": "Service Tier", + "description": + "Determines whether to use priority capacity (if available) or standard capacity for this request.\n\nAnthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details." + }) + ), + "stop_sequences": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "title": "Stop Sequences", + "description": + "Custom text sequences that will cause the model to stop generating.\n\nOur models will normally stop when they have naturally completed their turn, which will result in a response `stop_reason` of `\"end_turn\"`.\n\nIf you want the model to stop generating when it encounters custom strings of text, you can use the `stop_sequences` parameter. If the model encounters one of the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"` and the response `stop_sequence` value will contain the matched stop sequence." + }) + ), + "stream": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Stream", + "description": + "Whether to incrementally stream the response using server-sent events.\n\nSee [streaming](https://docs.claude.com/en/api/messages-streaming) for details." + }) + ), + "system": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Array(RequestTextBlock)]).annotate({ + "title": "System", + "description": + "System prompt.\n\nA system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts)." + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Temperature", + "description": + "Amount of randomness injected into the response.\n\nDefaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for analytical / multiple choice, and closer to `1.0` for creative and generative tasks.\n\nNote that even with `temperature` of `0.0`, the results will not be fully deterministic." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ), + "thinking": Schema.optionalKey(ThinkingConfigParam), + "tool_choice": Schema.optionalKey(ToolChoice), + "tools": Schema.optionalKey( + Schema.Array( + Schema.Union([ + Tool, + BashTool_20250124, + CodeExecutionTool_20250522, + CodeExecutionTool_20250825, + CodeExecutionTool_20260120, + MemoryTool_20250818, + TextEditor_20250124, + TextEditor_20250429, + TextEditor_20250728, + WebSearchTool_20250305, + WebFetchTool_20250910, + WebSearchTool_20260209, + WebFetchTool_20260209, + ToolSearchToolBM25_20251119, + ToolSearchToolRegex_20251119 + ], { mode: "oneOf" }) + ).annotate({ + "title": "Tools", + "description": + "Definitions of tools that the model may use.\n\nIf you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n\nThere are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n\nEach tool definition includes:\n\n* `name`: Name of the tool.\n* `description`: Optional, but strongly-recommended description of the tool.\n* `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n\nFor example, if you defined `tools` as:\n\n```json\n[\n {\n \"name\": \"get_stock_price\",\n \"description\": \"Get the current stock price for a given ticker symbol.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"ticker\": {\n \"type\": \"string\",\n \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n }\n },\n \"required\": [\"ticker\"]\n }\n }\n]\n```\n\nAnd then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n\n```json\n[\n {\n \"type\": \"tool_use\",\n \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"name\": \"get_stock_price\",\n \"input\": { \"ticker\": \"^GSPC\" }\n }\n]\n```\n\nYou might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n\n```json\n[\n {\n \"type\": \"tool_result\",\n \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"content\": \"259.75 USD\"\n }\n]\n```\n\nTools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n\nSee our [guide](https://docs.claude.com/en/docs/tool-use) for more details." + }) + ), + "top_k": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top K", + "description": + "Only sample from the top K options for each subsequent token.\n\nUsed to remove \"long tail\" low probability responses. [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) + ), + "top_p": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top P", + "description": + "Use nucleus sampling.\n\nIn nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ) +}).annotate({ "title": "CreateMessageParams" }) +export type MessageBatchIndividualRequestParams = { + readonly "custom_id": string + readonly "params": { + readonly "model": Model + readonly "messages": ReadonlyArray + readonly "cache_control"?: CacheControlEphemeral | null + readonly "container"?: string | null + readonly "inference_geo"?: string | null + readonly "max_tokens": number + readonly "metadata"?: { readonly "user_id"?: string | null } + readonly "output_config"?: { readonly "effort"?: EffortLevel | null; readonly "format"?: JsonOutputFormat | null } + readonly "service_tier"?: "auto" | "standard_only" + readonly "stop_sequences"?: ReadonlyArray + readonly "stream"?: boolean + readonly "system"?: string | ReadonlyArray + readonly "temperature"?: number + readonly "thinking"?: ThinkingConfigParam + readonly "tool_choice"?: ToolChoice + readonly "tools"?: ReadonlyArray< + | Tool + | BashTool_20250124 + | CodeExecutionTool_20250522 + | CodeExecutionTool_20250825 + | CodeExecutionTool_20260120 + | MemoryTool_20250818 + | TextEditor_20250124 + | TextEditor_20250429 + | TextEditor_20250728 + | WebSearchTool_20250305 + | WebFetchTool_20250910 + | WebSearchTool_20260209 + | WebFetchTool_20260209 + | ToolSearchToolBM25_20251119 + | ToolSearchToolRegex_20251119 + > + readonly "top_k"?: number + readonly "top_p"?: number + } +} +export const MessageBatchIndividualRequestParams = Schema.Struct({ + "custom_id": Schema.String.annotate({ + "title": "Custom Id", + "description": + "Developer-provided ID created for each request in a Message Batch. Useful for matching results to requests, as results may be given out of request order.\n\nMust be unique for each request within the Message Batch." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)).check( + Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]{1,64}$")) + ), + "params": Schema.Struct({ + "model": Model, + "messages": Schema.Array(InputMessage).annotate({ + "title": "Messages", + "description": + "Input messages.\n\nOur models are trained to operate on alternating `user` and `assistant` conversational turns. When creating a new `Message`, you specify the prior conversational turns with the `messages` parameter, and the model then generates the next `Message` in the conversation. Consecutive `user` or `assistant` turns in your request will be combined into a single turn.\n\nEach input message must be an object with a `role` and `content`. You can specify a single `user`-role message, or you can include multiple `user` and `assistant` messages.\n\nIf the final message uses the `assistant` role, the response content will continue immediately from the content in that message. This can be used to constrain part of the model's response.\n\nExample with a single `user` message:\n\n```json\n[{\"role\": \"user\", \"content\": \"Hello, Claude\"}]\n```\n\nExample with multiple conversational turns:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"Hello there.\"},\n {\"role\": \"assistant\", \"content\": \"Hi, I'm Claude. How can I help you?\"},\n {\"role\": \"user\", \"content\": \"Can you explain LLMs in plain English?\"},\n]\n```\n\nExample with a partially-filled response from Claude:\n\n```json\n[\n {\"role\": \"user\", \"content\": \"What's the Greek name for Sun? (A) Sol (B) Helios (C) Sun\"},\n {\"role\": \"assistant\", \"content\": \"The best answer is (\"},\n]\n```\n\nEach input message `content` may be either a single `string` or an array of content blocks, where each block has a specific `type`. Using a `string` for `content` is shorthand for an array of one content block of type `\"text\"`. The following input messages are equivalent:\n\n```json\n{\"role\": \"user\", \"content\": \"Hello, Claude\"}\n```\n\n```json\n{\"role\": \"user\", \"content\": [{\"type\": \"text\", \"text\": \"Hello, Claude\"}]}\n```\n\nSee [input examples](https://docs.claude.com/en/api/messages-examples).\n\nNote that if you want to include a [system prompt](https://docs.claude.com/en/docs/system-prompts), you can use the top-level `system` parameter — there is no `\"system\"` role for input messages in the Messages API.\n\nThere is a limit of 100,000 messages in a single request." + }), + "cache_control": Schema.optionalKey( + Schema.Union([Schema.Union([CacheControlEphemeral], { mode: "oneOf" }), Schema.Null]).annotate({ + "title": "Cache Control", + "description": + "Top-level cache control automatically applies a cache_control marker to the last cacheable block in the request." + }) + ), + "container": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Container", + "description": "Container identifier for reuse across requests." + }) + ), + "inference_geo": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Inference Geo", + "description": + "Specifies the geographic region for inference processing. If not specified, the workspace's `default_inference_geo` is used." + }) + ), + "max_tokens": Schema.Number.annotate({ + "title": "Max Tokens", + "description": + "The maximum number of tokens to generate before stopping.\n\nNote that our models may stop _before_ reaching this maximum. This parameter only specifies the absolute maximum number of tokens to generate.\n\nDifferent models have different maximum values for this parameter. See [models](https://docs.claude.com/en/docs/models-overview) for details." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + "metadata": Schema.optionalKey( + Schema.Struct({ + "user_id": Schema.optionalKey( + Schema.Union([Schema.String.check(Schema.isMaxLength(256)), Schema.Null]).annotate({ + "title": "User Id", + "description": + "An external identifier for the user who is associated with the request.\n\nThis should be a uuid, hash value, or other opaque identifier. Anthropic may use this id to help detect abuse. Do not include any identifying information such as name, email address, or phone number." + }) + ) + }).annotate({ "title": "Metadata", "description": "An object describing metadata about the request." }) + ), + "output_config": Schema.optionalKey( + Schema.Struct({ + "effort": Schema.optionalKey( + Schema.Union([EffortLevel, Schema.Null]).annotate({ + "description": + "How much effort the model should put into its response. Higher effort levels may result in more thorough analysis but take longer.\n\nValid values are `low`, `medium`, `high`, or `max`." + }) + ), + "format": Schema.optionalKey( + Schema.Union([JsonOutputFormat, Schema.Null]).annotate({ + "description": + "A schema to specify Claude's output format in responses. See [structured outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs)" + }) + ) + }).annotate({ + "title": "OutputConfig", + "description": "Configuration options for the model's output, such as the output format." + }) + ), + "service_tier": Schema.optionalKey( + Schema.Literals(["auto", "standard_only"]).annotate({ + "title": "Service Tier", + "description": + "Determines whether to use priority capacity (if available) or standard capacity for this request.\n\nAnthropic offers different levels of service for your API requests. See [service-tiers](https://docs.claude.com/en/api/service-tiers) for details." + }) + ), + "stop_sequences": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "title": "Stop Sequences", + "description": + "Custom text sequences that will cause the model to stop generating.\n\nOur models will normally stop when they have naturally completed their turn, which will result in a response `stop_reason` of `\"end_turn\"`.\n\nIf you want the model to stop generating when it encounters custom strings of text, you can use the `stop_sequences` parameter. If the model encounters one of the custom sequences, the response `stop_reason` value will be `\"stop_sequence\"` and the response `stop_sequence` value will contain the matched stop sequence." + }) + ), + "stream": Schema.optionalKey( + Schema.Boolean.annotate({ + "title": "Stream", + "description": + "Whether to incrementally stream the response using server-sent events.\n\nSee [streaming](https://docs.claude.com/en/api/messages-streaming) for details." + }) + ), + "system": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Array(RequestTextBlock)]).annotate({ + "title": "System", + "description": + "System prompt.\n\nA system prompt is a way of providing context and instructions to Claude, such as specifying a particular goal or role. See our [guide to system prompts](https://docs.claude.com/en/docs/system-prompts)." + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Temperature", + "description": + "Amount of randomness injected into the response.\n\nDefaults to `1.0`. Ranges from `0.0` to `1.0`. Use `temperature` closer to `0.0` for analytical / multiple choice, and closer to `1.0` for creative and generative tasks.\n\nNote that even with `temperature` of `0.0`, the results will not be fully deterministic." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ), + "thinking": Schema.optionalKey(ThinkingConfigParam), + "tool_choice": Schema.optionalKey(ToolChoice), + "tools": Schema.optionalKey( + Schema.Array( + Schema.Union([ + Tool, + BashTool_20250124, + CodeExecutionTool_20250522, + CodeExecutionTool_20250825, + CodeExecutionTool_20260120, + MemoryTool_20250818, + TextEditor_20250124, + TextEditor_20250429, + TextEditor_20250728, + WebSearchTool_20250305, + WebFetchTool_20250910, + WebSearchTool_20260209, + WebFetchTool_20260209, + ToolSearchToolBM25_20251119, + ToolSearchToolRegex_20251119 + ], { mode: "oneOf" }) + ).annotate({ + "title": "Tools", + "description": + "Definitions of tools that the model may use.\n\nIf you include `tools` in your API request, the model may return `tool_use` content blocks that represent the model's use of those tools. You can then run those tools using the tool input generated by the model and then optionally return results back to the model using `tool_result` content blocks.\n\nThere are two types of tools: **client tools** and **server tools**. The behavior described below applies to client tools. For [server tools](https://docs.claude.com/en/docs/agents-and-tools/tool-use/overview\\#server-tools), see their individual documentation as each has its own behavior (e.g., the [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool)).\n\nEach tool definition includes:\n\n* `name`: Name of the tool.\n* `description`: Optional, but strongly-recommended description of the tool.\n* `input_schema`: [JSON schema](https://json-schema.org/draft/2020-12) for the tool `input` shape that the model will produce in `tool_use` output content blocks.\n\nFor example, if you defined `tools` as:\n\n```json\n[\n {\n \"name\": \"get_stock_price\",\n \"description\": \"Get the current stock price for a given ticker symbol.\",\n \"input_schema\": {\n \"type\": \"object\",\n \"properties\": {\n \"ticker\": {\n \"type\": \"string\",\n \"description\": \"The stock ticker symbol, e.g. AAPL for Apple Inc.\"\n }\n },\n \"required\": [\"ticker\"]\n }\n }\n]\n```\n\nAnd then asked the model \"What's the S&P 500 at today?\", the model might produce `tool_use` content blocks in the response like this:\n\n```json\n[\n {\n \"type\": \"tool_use\",\n \"id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"name\": \"get_stock_price\",\n \"input\": { \"ticker\": \"^GSPC\" }\n }\n]\n```\n\nYou might then run your `get_stock_price` tool with `{\"ticker\": \"^GSPC\"}` as an input, and return the following back to the model in a subsequent `user` message:\n\n```json\n[\n {\n \"type\": \"tool_result\",\n \"tool_use_id\": \"toolu_01D7FLrfh4GYq7yT1ULFeyMV\",\n \"content\": \"259.75 USD\"\n }\n]\n```\n\nTools can be used for workflows that include running client-side tools and functions, or more generally whenever you want the model to produce a particular JSON structure of output.\n\nSee our [guide](https://docs.claude.com/en/docs/tool-use) for more details." + }) + ), + "top_k": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top K", + "description": + "Only sample from the top K options for each subsequent token.\n\nUsed to remove \"long tail\" low probability responses. [Learn more technical details here](https://towardsdatascience.com/how-to-sample-from-language-models-682bceb97277).\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) + ), + "top_p": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Top P", + "description": + "Use nucleus sampling.\n\nIn nucleus sampling, we compute the cumulative distribution over all the options for each subsequent token in decreasing probability order and cut it off once it reaches a particular probability specified by `top_p`. You should either alter `temperature` or `top_p`, but not both.\n\nRecommended for advanced use cases only. You usually only need to use `temperature`." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) + ) + }).annotate({ + "title": "CreateMessageParams", + "description": + "Messages API creation parameters for the individual request.\n\nSee the [Messages API reference](https://docs.claude.com/en/api/messages) for full documentation on available parameters." + }) +}).annotate({ "title": "MessageBatchIndividualRequestParams" }) +export type BetaCreateMessageBatchParams = { + readonly "requests": ReadonlyArray +} +export const BetaCreateMessageBatchParams = Schema.Struct({ + "requests": Schema.Array(BetaMessageBatchIndividualRequestParams).annotate({ + "title": "Requests", + "description": "List of requests for prompt completion. Each is an individual request to create a Message." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(100000)) +}).annotate({ "title": "CreateMessageBatchParams" }) +export type CreateMessageBatchParams = { readonly "requests": ReadonlyArray } +export const CreateMessageBatchParams = Schema.Struct({ + "requests": Schema.Array(MessageBatchIndividualRequestParams).annotate({ + "title": "Requests", + "description": "List of requests for prompt completion. Each is an individual request to create a Message." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(100000)) +}).annotate({ "title": "CreateMessageBatchParams" }) +// schemas +export type MessagesPostParams = { readonly "anthropic-version"?: string } +export const MessagesPostParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type MessagesPostRequestJson = CreateMessageParams +export const MessagesPostRequestJson = CreateMessageParams +export type MessagesPost200 = Message +export const MessagesPost200 = Message +export type MessagesPost4XX = ErrorResponse +export const MessagesPost4XX = ErrorResponse +export type CompletePostParams = { readonly "anthropic-version"?: string; readonly "anthropic-beta"?: string } +export const CompletePostParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ) +}) +export type CompletePostRequestJson = CompletionRequest +export const CompletePostRequestJson = CompletionRequest +export type CompletePost200 = CompletionResponse +export const CompletePost200 = CompletionResponse +export type CompletePost4XX = ErrorResponse +export const CompletePost4XX = ErrorResponse +export type ModelsListParams = { + readonly "before_id"?: string + readonly "after_id"?: string + readonly "limit"?: number + readonly "anthropic-version"?: string + readonly "x-api-key"?: string + readonly "anthropic-beta"?: string +} +export const ModelsListParams = Schema.Struct({ + "before_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "Before Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object." + }) + ), + "after_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "After Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object." + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Limit", + "description": "Number of items to return per page.\n\nDefaults to `20`. Ranges from `1` to `1000`.", + "default": 20 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ) +}) +export type ModelsList200 = ListResponse_ModelInfo_ +export const ModelsList200 = ListResponse_ModelInfo_ +export type ModelsList4XX = ErrorResponse +export const ModelsList4XX = ErrorResponse +export type ModelsGetParams = { + readonly "anthropic-version"?: string + readonly "x-api-key"?: string + readonly "anthropic-beta"?: string +} +export const ModelsGetParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ) +}) +export type ModelsGet200 = ModelInfo +export const ModelsGet200 = ModelInfo +export type ModelsGet4XX = ErrorResponse +export const ModelsGet4XX = ErrorResponse +export type MessageBatchesListParams = { + readonly "before_id"?: string + readonly "after_id"?: string + readonly "limit"?: number + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const MessageBatchesListParams = Schema.Struct({ + "before_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "Before Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object." + }) + ), + "after_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "After Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object." + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Limit", + "description": "Number of items to return per page.\n\nDefaults to `20`. Ranges from `1` to `1000`.", + "default": 20 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type MessageBatchesList200 = ListResponse_MessageBatch_ +export const MessageBatchesList200 = ListResponse_MessageBatch_ +export type MessageBatchesList4XX = ErrorResponse +export const MessageBatchesList4XX = ErrorResponse +export type MessageBatchesPostParams = { readonly "anthropic-version"?: string } +export const MessageBatchesPostParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type MessageBatchesPostRequestJson = CreateMessageBatchParams +export const MessageBatchesPostRequestJson = CreateMessageBatchParams +export type MessageBatchesPost200 = MessageBatch +export const MessageBatchesPost200 = MessageBatch +export type MessageBatchesPost4XX = ErrorResponse +export const MessageBatchesPost4XX = ErrorResponse +export type MessageBatchesRetrieveParams = { readonly "anthropic-version"?: string; readonly "x-api-key"?: string } +export const MessageBatchesRetrieveParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type MessageBatchesRetrieve200 = MessageBatch +export const MessageBatchesRetrieve200 = MessageBatch +export type MessageBatchesRetrieve4XX = ErrorResponse +export const MessageBatchesRetrieve4XX = ErrorResponse +export type MessageBatchesDeleteParams = { readonly "anthropic-version"?: string; readonly "x-api-key"?: string } +export const MessageBatchesDeleteParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type MessageBatchesDelete200 = DeleteMessageBatchResponse +export const MessageBatchesDelete200 = DeleteMessageBatchResponse +export type MessageBatchesDelete4XX = ErrorResponse +export const MessageBatchesDelete4XX = ErrorResponse +export type MessageBatchesCancelParams = { readonly "anthropic-version"?: string } +export const MessageBatchesCancelParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type MessageBatchesCancel200 = MessageBatch +export const MessageBatchesCancel200 = MessageBatch +export type MessageBatchesCancel4XX = ErrorResponse +export const MessageBatchesCancel4XX = ErrorResponse +export type MessageBatchesResultsParams = { readonly "anthropic-version"?: string; readonly "x-api-key"?: string } +export const MessageBatchesResultsParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type MessageBatchesResults4XX = ErrorResponse +export const MessageBatchesResults4XX = ErrorResponse +export type MessagesCountTokensPostParams = { readonly "anthropic-version"?: string } +export const MessagesCountTokensPostParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type MessagesCountTokensPostRequestJson = CountMessageTokensParams +export const MessagesCountTokensPostRequestJson = CountMessageTokensParams +export type MessagesCountTokensPost200 = CountMessageTokensResponse +export const MessagesCountTokensPost200 = CountMessageTokensResponse +export type MessagesCountTokensPost4XX = ErrorResponse +export const MessagesCountTokensPost4XX = ErrorResponse +export type ListFilesV1FilesGetParams = { + readonly "before_id"?: string + readonly "after_id"?: string + readonly "limit"?: number + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const ListFilesV1FilesGetParams = Schema.Struct({ + "before_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "Before Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object." + }) + ), + "after_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "After Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object." + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Limit", + "description": "Number of items to return per page.\n\nDefaults to `20`. Ranges from `1` to `1000`.", + "default": 20 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type ListFilesV1FilesGet200 = FileListResponse +export const ListFilesV1FilesGet200 = FileListResponse +export type ListFilesV1FilesGet4XX = ErrorResponse +export const ListFilesV1FilesGet4XX = ErrorResponse +export type UploadFileV1FilesPostParams = { readonly "anthropic-beta"?: string; readonly "anthropic-version"?: string } +export const UploadFileV1FilesPostParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type UploadFileV1FilesPostRequestFormData = { readonly "file": string } +export const UploadFileV1FilesPostRequestFormData = Schema.Struct({ + "file": Schema.String.annotate({ "description": "The file to upload", "format": "binary" }) +}) +export type UploadFileV1FilesPost200 = FileMetadataSchema +export const UploadFileV1FilesPost200 = FileMetadataSchema +export type UploadFileV1FilesPost4XX = ErrorResponse +export const UploadFileV1FilesPost4XX = ErrorResponse +export type GetFileMetadataV1FilesFileIdGetParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const GetFileMetadataV1FilesFileIdGetParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type GetFileMetadataV1FilesFileIdGet200 = FileMetadataSchema +export const GetFileMetadataV1FilesFileIdGet200 = FileMetadataSchema +export type GetFileMetadataV1FilesFileIdGet4XX = ErrorResponse +export const GetFileMetadataV1FilesFileIdGet4XX = ErrorResponse +export type DeleteFileV1FilesFileIdDeleteParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const DeleteFileV1FilesFileIdDeleteParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type DeleteFileV1FilesFileIdDelete200 = FileDeleteResponse +export const DeleteFileV1FilesFileIdDelete200 = FileDeleteResponse +export type DeleteFileV1FilesFileIdDelete4XX = ErrorResponse +export const DeleteFileV1FilesFileIdDelete4XX = ErrorResponse +export type DownloadFileV1FilesFileIdContentGetParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const DownloadFileV1FilesFileIdContentGetParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type ListSkillsV1SkillsGetParams = { + readonly "page"?: string | null + readonly "limit"?: number + readonly "source"?: string | null + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const ListSkillsV1SkillsGetParams = Schema.Struct({ + "page": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Page", + "description": + "Pagination token for fetching a specific page of results.\n\nPass the value from a previous response's `next_page` field to get the next page of results." + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Limit", + "description": "Number of results to return per page.\n\nMaximum value is 100. Defaults to 20.", + "default": 20 + }).check(Schema.isInt()) + ), + "source": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Source", + "description": + "Filter skills by source.\n\nIf provided, only skills from the specified source will be returned:\n* `\"custom\"`: only return user-created skills\n* `\"anthropic\"`: only return Anthropic-created skills" + }) + ), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type ListSkillsV1SkillsGet200 = ListSkillsResponse +export const ListSkillsV1SkillsGet200 = ListSkillsResponse +export type ListSkillsV1SkillsGet4XX = ErrorResponse +export const ListSkillsV1SkillsGet4XX = ErrorResponse +export type CreateSkillV1SkillsPostParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string +} +export const CreateSkillV1SkillsPostParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type CreateSkillV1SkillsPostRequestFormData = Body_create_skill_v1_skills_post +export const CreateSkillV1SkillsPostRequestFormData = Body_create_skill_v1_skills_post +export type CreateSkillV1SkillsPost200 = CreateSkillResponse +export const CreateSkillV1SkillsPost200 = CreateSkillResponse +export type CreateSkillV1SkillsPost4XX = ErrorResponse +export const CreateSkillV1SkillsPost4XX = ErrorResponse +export type GetSkillV1SkillsSkillIdGetParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const GetSkillV1SkillsSkillIdGetParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type GetSkillV1SkillsSkillIdGet200 = GetSkillResponse +export const GetSkillV1SkillsSkillIdGet200 = GetSkillResponse +export type GetSkillV1SkillsSkillIdGet4XX = ErrorResponse +export const GetSkillV1SkillsSkillIdGet4XX = ErrorResponse +export type DeleteSkillV1SkillsSkillIdDeleteParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const DeleteSkillV1SkillsSkillIdDeleteParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type DeleteSkillV1SkillsSkillIdDelete200 = DeleteSkillResponse +export const DeleteSkillV1SkillsSkillIdDelete200 = DeleteSkillResponse +export type DeleteSkillV1SkillsSkillIdDelete4XX = ErrorResponse +export const DeleteSkillV1SkillsSkillIdDelete4XX = ErrorResponse +export type ListSkillVersionsV1SkillsSkillIdVersionsGetParams = { + readonly "page"?: string | null + readonly "limit"?: number | null + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const ListSkillVersionsV1SkillsSkillIdVersionsGetParams = Schema.Struct({ + "page": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Page", + "description": "Optionally set to the `next_page` token from the previous response." + }) + ), + "limit": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Limit", + "description": "Number of items to return per page.\n\nDefaults to `20`. Ranges from `1` to `1000`." + }) + ), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type ListSkillVersionsV1SkillsSkillIdVersionsGet200 = ListSkillVersionsResponse +export const ListSkillVersionsV1SkillsSkillIdVersionsGet200 = ListSkillVersionsResponse +export type ListSkillVersionsV1SkillsSkillIdVersionsGet4XX = ErrorResponse +export const ListSkillVersionsV1SkillsSkillIdVersionsGet4XX = ErrorResponse +export type CreateSkillVersionV1SkillsSkillIdVersionsPostParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string +} +export const CreateSkillVersionV1SkillsSkillIdVersionsPostParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type CreateSkillVersionV1SkillsSkillIdVersionsPostRequestFormData = + Body_create_skill_version_v1_skills__skill_id__versions_post +export const CreateSkillVersionV1SkillsSkillIdVersionsPostRequestFormData = + Body_create_skill_version_v1_skills__skill_id__versions_post +export type CreateSkillVersionV1SkillsSkillIdVersionsPost200 = CreateSkillVersionResponse +export const CreateSkillVersionV1SkillsSkillIdVersionsPost200 = CreateSkillVersionResponse +export type CreateSkillVersionV1SkillsSkillIdVersionsPost4XX = ErrorResponse +export const CreateSkillVersionV1SkillsSkillIdVersionsPost4XX = ErrorResponse +export type GetSkillVersionV1SkillsSkillIdVersionsVersionGetParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const GetSkillVersionV1SkillsSkillIdVersionsVersionGetParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type GetSkillVersionV1SkillsSkillIdVersionsVersionGet200 = GetSkillVersionResponse +export const GetSkillVersionV1SkillsSkillIdVersionsVersionGet200 = GetSkillVersionResponse +export type GetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX = ErrorResponse +export const GetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX = ErrorResponse +export type DeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const DeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type DeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete200 = DeleteSkillVersionResponse +export const DeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete200 = DeleteSkillVersionResponse +export type DeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX = ErrorResponse +export const DeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX = ErrorResponse +export type BetaMessagesPostParams = { readonly "anthropic-beta"?: string; readonly "anthropic-version"?: string } +export const BetaMessagesPostParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type BetaMessagesPostRequestJson = BetaCreateMessageParams +export const BetaMessagesPostRequestJson = BetaCreateMessageParams +export type BetaMessagesPost200 = BetaMessage +export const BetaMessagesPost200 = BetaMessage +export type BetaMessagesPost4XX = BetaErrorResponse +export const BetaMessagesPost4XX = BetaErrorResponse +export type BetaModelsListParams = { + readonly "before_id"?: string + readonly "after_id"?: string + readonly "limit"?: number + readonly "anthropic-version"?: string + readonly "x-api-key"?: string + readonly "anthropic-beta"?: string +} +export const BetaModelsListParams = Schema.Struct({ + "before_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "Before Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object." + }) + ), + "after_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "After Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object." + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Limit", + "description": "Number of items to return per page.\n\nDefaults to `20`. Ranges from `1` to `1000`.", + "default": 20 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ) +}) +export type BetaModelsList200 = BetaListResponse_ModelInfo_ +export const BetaModelsList200 = BetaListResponse_ModelInfo_ +export type BetaModelsList4XX = BetaErrorResponse +export const BetaModelsList4XX = BetaErrorResponse +export type BetaModelsGetParams = { + readonly "anthropic-version"?: string + readonly "x-api-key"?: string + readonly "anthropic-beta"?: string +} +export const BetaModelsGetParams = Schema.Struct({ + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ) +}) +export type BetaModelsGet200 = BetaModelInfo +export const BetaModelsGet200 = BetaModelInfo +export type BetaModelsGet4XX = BetaErrorResponse +export const BetaModelsGet4XX = BetaErrorResponse +export type BetaMessageBatchesListParams = { + readonly "before_id"?: string + readonly "after_id"?: string + readonly "limit"?: number + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaMessageBatchesListParams = Schema.Struct({ + "before_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "Before Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object." + }) + ), + "after_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "After Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object." + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Limit", + "description": "Number of items to return per page.\n\nDefaults to `20`. Ranges from `1` to `1000`.", + "default": 20 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaMessageBatchesList200 = BetaListResponse_MessageBatch_ +export const BetaMessageBatchesList200 = BetaListResponse_MessageBatch_ +export type BetaMessageBatchesList4XX = BetaErrorResponse +export const BetaMessageBatchesList4XX = BetaErrorResponse +export type BetaMessageBatchesPostParams = { readonly "anthropic-beta"?: string; readonly "anthropic-version"?: string } +export const BetaMessageBatchesPostParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type BetaMessageBatchesPostRequestJson = BetaCreateMessageBatchParams +export const BetaMessageBatchesPostRequestJson = BetaCreateMessageBatchParams +export type BetaMessageBatchesPost200 = BetaMessageBatch +export const BetaMessageBatchesPost200 = BetaMessageBatch +export type BetaMessageBatchesPost4XX = BetaErrorResponse +export const BetaMessageBatchesPost4XX = BetaErrorResponse +export type BetaMessageBatchesRetrieveParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaMessageBatchesRetrieveParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaMessageBatchesRetrieve200 = BetaMessageBatch +export const BetaMessageBatchesRetrieve200 = BetaMessageBatch +export type BetaMessageBatchesRetrieve4XX = BetaErrorResponse +export const BetaMessageBatchesRetrieve4XX = BetaErrorResponse +export type BetaMessageBatchesDeleteParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaMessageBatchesDeleteParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaMessageBatchesDelete200 = BetaDeleteMessageBatchResponse +export const BetaMessageBatchesDelete200 = BetaDeleteMessageBatchResponse +export type BetaMessageBatchesDelete4XX = BetaErrorResponse +export const BetaMessageBatchesDelete4XX = BetaErrorResponse +export type BetaMessageBatchesCancelParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string +} +export const BetaMessageBatchesCancelParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type BetaMessageBatchesCancel200 = BetaMessageBatch +export const BetaMessageBatchesCancel200 = BetaMessageBatch +export type BetaMessageBatchesCancel4XX = BetaErrorResponse +export const BetaMessageBatchesCancel4XX = BetaErrorResponse +export type BetaMessageBatchesResultsParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaMessageBatchesResultsParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaMessageBatchesResults4XX = BetaErrorResponse +export const BetaMessageBatchesResults4XX = BetaErrorResponse +export type BetaMessagesCountTokensPostParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string +} +export const BetaMessagesCountTokensPostParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type BetaMessagesCountTokensPostRequestJson = BetaCountMessageTokensParams +export const BetaMessagesCountTokensPostRequestJson = BetaCountMessageTokensParams +export type BetaMessagesCountTokensPost200 = BetaCountMessageTokensResponse +export const BetaMessagesCountTokensPost200 = BetaCountMessageTokensResponse +export type BetaMessagesCountTokensPost4XX = BetaErrorResponse +export const BetaMessagesCountTokensPost4XX = BetaErrorResponse +export type BetaListFilesV1FilesGetParams = { + readonly "before_id"?: string + readonly "after_id"?: string + readonly "limit"?: number + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaListFilesV1FilesGetParams = Schema.Struct({ + "before_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "Before Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately before this object." + }) + ), + "after_id": Schema.optionalKey( + Schema.String.annotate({ + "title": "After Id", + "description": + "ID of the object to use as a cursor for pagination. When provided, returns the page of results immediately after this object." + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Limit", + "description": "Number of items to return per page.\n\nDefaults to `20`. Ranges from `1` to `1000`.", + "default": 20 + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaListFilesV1FilesGet200 = BetaFileListResponse +export const BetaListFilesV1FilesGet200 = BetaFileListResponse +export type BetaListFilesV1FilesGet4XX = BetaErrorResponse +export const BetaListFilesV1FilesGet4XX = BetaErrorResponse +export type BetaUploadFileV1FilesPostParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string +} +export const BetaUploadFileV1FilesPostParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type BetaUploadFileV1FilesPostRequestFormData = { readonly "file": string } +export const BetaUploadFileV1FilesPostRequestFormData = Schema.Struct({ + "file": Schema.String.annotate({ "description": "The file to upload", "format": "binary" }) +}) +export type BetaUploadFileV1FilesPost200 = BetaFileMetadataSchema +export const BetaUploadFileV1FilesPost200 = BetaFileMetadataSchema +export type BetaUploadFileV1FilesPost4XX = BetaErrorResponse +export const BetaUploadFileV1FilesPost4XX = BetaErrorResponse +export type BetaGetFileMetadataV1FilesFileIdGetParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaGetFileMetadataV1FilesFileIdGetParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaGetFileMetadataV1FilesFileIdGet200 = BetaFileMetadataSchema +export const BetaGetFileMetadataV1FilesFileIdGet200 = BetaFileMetadataSchema +export type BetaGetFileMetadataV1FilesFileIdGet4XX = BetaErrorResponse +export const BetaGetFileMetadataV1FilesFileIdGet4XX = BetaErrorResponse +export type BetaDeleteFileV1FilesFileIdDeleteParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaDeleteFileV1FilesFileIdDeleteParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaDeleteFileV1FilesFileIdDelete200 = BetaFileDeleteResponse +export const BetaDeleteFileV1FilesFileIdDelete200 = BetaFileDeleteResponse +export type BetaDeleteFileV1FilesFileIdDelete4XX = BetaErrorResponse +export const BetaDeleteFileV1FilesFileIdDelete4XX = BetaErrorResponse +export type BetaDownloadFileV1FilesFileIdContentGetParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaDownloadFileV1FilesFileIdContentGetParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaListSkillsV1SkillsGetParams = { + readonly "page"?: string | null + readonly "limit"?: number + readonly "source"?: string | null + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaListSkillsV1SkillsGetParams = Schema.Struct({ + "page": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Page", + "description": + "Pagination token for fetching a specific page of results.\n\nPass the value from a previous response's `next_page` field to get the next page of results." + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ + "title": "Limit", + "description": "Number of results to return per page.\n\nMaximum value is 100. Defaults to 20.", + "default": 20 + }).check(Schema.isInt()) + ), + "source": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Source", + "description": + "Filter skills by source.\n\nIf provided, only skills from the specified source will be returned:\n* `\"custom\"`: only return user-created skills\n* `\"anthropic\"`: only return Anthropic-created skills" + }) + ), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaListSkillsV1SkillsGet200 = BetaListSkillsResponse +export const BetaListSkillsV1SkillsGet200 = BetaListSkillsResponse +export type BetaListSkillsV1SkillsGet4XX = BetaErrorResponse +export const BetaListSkillsV1SkillsGet4XX = BetaErrorResponse +export type BetaCreateSkillV1SkillsPostParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string +} +export const BetaCreateSkillV1SkillsPostParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type BetaCreateSkillV1SkillsPostRequestFormData = BetaBody_create_skill_v1_skills_post +export const BetaCreateSkillV1SkillsPostRequestFormData = BetaBody_create_skill_v1_skills_post +export type BetaCreateSkillV1SkillsPost200 = BetaCreateSkillResponse +export const BetaCreateSkillV1SkillsPost200 = BetaCreateSkillResponse +export type BetaCreateSkillV1SkillsPost4XX = BetaErrorResponse +export const BetaCreateSkillV1SkillsPost4XX = BetaErrorResponse +export type BetaGetSkillV1SkillsSkillIdGetParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaGetSkillV1SkillsSkillIdGetParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaGetSkillV1SkillsSkillIdGet200 = BetaGetSkillResponse +export const BetaGetSkillV1SkillsSkillIdGet200 = BetaGetSkillResponse +export type BetaGetSkillV1SkillsSkillIdGet4XX = BetaErrorResponse +export const BetaGetSkillV1SkillsSkillIdGet4XX = BetaErrorResponse +export type BetaDeleteSkillV1SkillsSkillIdDeleteParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaDeleteSkillV1SkillsSkillIdDeleteParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaDeleteSkillV1SkillsSkillIdDelete200 = BetaDeleteSkillResponse +export const BetaDeleteSkillV1SkillsSkillIdDelete200 = BetaDeleteSkillResponse +export type BetaDeleteSkillV1SkillsSkillIdDelete4XX = BetaErrorResponse +export const BetaDeleteSkillV1SkillsSkillIdDelete4XX = BetaErrorResponse +export type BetaListSkillVersionsV1SkillsSkillIdVersionsGetParams = { + readonly "page"?: string | null + readonly "limit"?: number | null + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaListSkillVersionsV1SkillsSkillIdVersionsGetParams = Schema.Struct({ + "page": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "title": "Page", + "description": "Optionally set to the `next_page` token from the previous response." + }) + ), + "limit": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "title": "Limit", + "description": "Number of items to return per page.\n\nDefaults to `20`. Ranges from `1` to `1000`." + }) + ), + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaListSkillVersionsV1SkillsSkillIdVersionsGet200 = BetaListSkillVersionsResponse +export const BetaListSkillVersionsV1SkillsSkillIdVersionsGet200 = BetaListSkillVersionsResponse +export type BetaListSkillVersionsV1SkillsSkillIdVersionsGet4XX = BetaErrorResponse +export const BetaListSkillVersionsV1SkillsSkillIdVersionsGet4XX = BetaErrorResponse +export type BetaCreateSkillVersionV1SkillsSkillIdVersionsPostParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string +} +export const BetaCreateSkillVersionV1SkillsSkillIdVersionsPostParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ) +}) +export type BetaCreateSkillVersionV1SkillsSkillIdVersionsPostRequestFormData = + BetaBody_create_skill_version_v1_skills__skill_id__versions_post +export const BetaCreateSkillVersionV1SkillsSkillIdVersionsPostRequestFormData = + BetaBody_create_skill_version_v1_skills__skill_id__versions_post +export type BetaCreateSkillVersionV1SkillsSkillIdVersionsPost200 = BetaCreateSkillVersionResponse +export const BetaCreateSkillVersionV1SkillsSkillIdVersionsPost200 = BetaCreateSkillVersionResponse +export type BetaCreateSkillVersionV1SkillsSkillIdVersionsPost4XX = BetaErrorResponse +export const BetaCreateSkillVersionV1SkillsSkillIdVersionsPost4XX = BetaErrorResponse +export type BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGetParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGetParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGet200 = BetaGetSkillVersionResponse +export const BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGet200 = BetaGetSkillVersionResponse +export type BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX = BetaErrorResponse +export const BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX = BetaErrorResponse +export type BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams = { + readonly "anthropic-beta"?: string + readonly "anthropic-version"?: string + readonly "x-api-key"?: string +} +export const BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams = Schema.Struct({ + "anthropic-beta": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Beta", + "description": + "Optional header to specify the beta version(s) you want to use.\n\nTo use multiple betas, use a comma separated list like `beta1,beta2` or specify the header multiple times for each beta." + }) + ), + "anthropic-version": Schema.optionalKey( + Schema.String.annotate({ + "title": "Anthropic-Version", + "description": + "The version of the Claude API you want to use.\n\nRead more about versioning and our version history [here](https://docs.claude.com/en/api/versioning)." + }) + ), + "x-api-key": Schema.optionalKey(Schema.String.annotate({ + "title": "X-Api-Key", + "description": + "Your unique API key for authentication.\n\nThis key is required in the header of all API requests, to authenticate your account and access Anthropic's services. Get your API key through the [Console](https://console.anthropic.com/settings/keys). Each key is scoped to a Workspace." + })) +}) +export type BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete200 = BetaDeleteSkillVersionResponse +export const BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete200 = BetaDeleteSkillVersionResponse +export type BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX = BetaErrorResponse +export const BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX = BetaErrorResponse + +export interface OperationConfig { + /** + * Whether or not the response should be included in the value returned from + * an operation. + * + * If set to `true`, a tuple of `[A, HttpClientResponse]` will be returned, + * where `A` is the success type of the operation. + * + * If set to `false`, only the success type of the operation will be returned. + */ + readonly includeResponse?: boolean | undefined +} + +/** + * A utility type which optionally includes the response in the return result + * of an operation based upon the value of the `includeResponse` configuration + * option. + */ +export type WithOptionalResponse = Config extends { + readonly includeResponse: true +} ? [A, HttpClientResponse.HttpClientResponse] : + A + +export const make = ( + httpClient: HttpClient.HttpClient, + options: { + readonly transformClient?: ((client: HttpClient.HttpClient) => Effect.Effect) | undefined + } = {} +): AnthropicClient => { + const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) => + Effect.flatMap( + Effect.orElseSucceed(response.json, () => "Unexpected status code"), + (description) => + Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.StatusCodeError({ + request: response.request, + response, + description: typeof description === "string" ? description : JSON.stringify(description) + }) + }) + ) + ) + const withResponse = (config: Config | undefined) => + ( + f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect + ): (request: HttpClientRequest.HttpClientRequest) => Effect.Effect => { + const withOptionalResponse = ( + config?.includeResponse + ? (response: HttpClientResponse.HttpClientResponse) => Effect.map(f(response), (a) => [a, response]) + : (response: HttpClientResponse.HttpClientResponse) => f(response) + ) as any + return options?.transformClient + ? (request) => + Effect.flatMap( + Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)), + withOptionalResponse + ) + : (request) => Effect.flatMap(httpClient.execute(request), withOptionalResponse) + } + const binaryRequest = ( + request: HttpClientRequest.HttpClientRequest + ): Stream.Stream => + HttpClient.filterStatusOk(httpClient).execute(request).pipe( + Effect.map((response) => response.stream), + Stream.unwrap + ) + const decodeSuccess = + (schema: Schema) => (response: HttpClientResponse.HttpClientResponse) => + HttpClientResponse.schemaBodyJson(schema)(response) + const decodeError = + (tag: Tag, schema: Schema) => + (response: HttpClientResponse.HttpClientResponse) => + Effect.flatMap( + HttpClientResponse.schemaBodyJson(schema)(response), + (cause) => Effect.fail(AnthropicClientError(tag, cause, response)) + ) + return { + httpClient, + "messagesPost": (options) => + HttpClientRequest.post(`/v1/messages`).pipe( + HttpClientRequest.setHeaders({ "anthropic-version": options.params?.["anthropic-version"] ?? undefined }), + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(MessagesPost200), + "4xx": decodeError("MessagesPost4XX", MessagesPost4XX), + orElse: unexpectedStatus + })) + ), + "completePost": (options) => + HttpClientRequest.post(`/v1/complete`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-version": options.params?.["anthropic-version"] ?? undefined, + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined + }), + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CompletePost200), + "4xx": decodeError("CompletePost4XX", CompletePost4XX), + orElse: unexpectedStatus + })) + ), + "modelsList": (options) => + HttpClientRequest.get(`/v1/models`).pipe( + HttpClientRequest.setUrlParams({ + "before_id": options?.params?.["before_id"] as any, + "after_id": options?.params?.["after_id"] as any, + "limit": options?.params?.["limit"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined, + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModelsList200), + "4xx": decodeError("ModelsList4XX", ModelsList4XX), + orElse: unexpectedStatus + })) + ), + "modelsGet": (modelId, options) => + HttpClientRequest.get(`/v1/models/${modelId}`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined, + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModelsGet200), + "4xx": decodeError("ModelsGet4XX", ModelsGet4XX), + orElse: unexpectedStatus + })) + ), + "messageBatchesList": (options) => + HttpClientRequest.get(`/v1/messages/batches`).pipe( + HttpClientRequest.setUrlParams({ + "before_id": options?.params?.["before_id"] as any, + "after_id": options?.params?.["after_id"] as any, + "limit": options?.params?.["limit"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(MessageBatchesList200), + "4xx": decodeError("MessageBatchesList4XX", MessageBatchesList4XX), + orElse: unexpectedStatus + })) + ), + "messageBatchesPost": (options) => + HttpClientRequest.post(`/v1/messages/batches`).pipe( + HttpClientRequest.setHeaders({ "anthropic-version": options.params?.["anthropic-version"] ?? undefined }), + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(MessageBatchesPost200), + "4xx": decodeError("MessageBatchesPost4XX", MessageBatchesPost4XX), + orElse: unexpectedStatus + })) + ), + "messageBatchesRetrieve": (messageBatchId, options) => + HttpClientRequest.get(`/v1/messages/batches/${messageBatchId}`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(MessageBatchesRetrieve200), + "4xx": decodeError("MessageBatchesRetrieve4XX", MessageBatchesRetrieve4XX), + orElse: unexpectedStatus + })) + ), + "messageBatchesDelete": (messageBatchId, options) => + HttpClientRequest.delete(`/v1/messages/batches/${messageBatchId}`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(MessageBatchesDelete200), + "4xx": decodeError("MessageBatchesDelete4XX", MessageBatchesDelete4XX), + orElse: unexpectedStatus + })) + ), + "messageBatchesCancel": (messageBatchId, options) => + HttpClientRequest.post(`/v1/messages/batches/${messageBatchId}/cancel`).pipe( + HttpClientRequest.setHeaders({ "anthropic-version": options?.params?.["anthropic-version"] ?? undefined }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(MessageBatchesCancel200), + "4xx": decodeError("MessageBatchesCancel4XX", MessageBatchesCancel4XX), + orElse: unexpectedStatus + })) + ), + "messageBatchesResults": (messageBatchId, options) => + HttpClientRequest.get(`/v1/messages/batches/${messageBatchId}/results`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "4xx": decodeError("MessageBatchesResults4XX", MessageBatchesResults4XX), + orElse: unexpectedStatus + })) + ), + "messagesCountTokensPost": (options) => + HttpClientRequest.post(`/v1/messages/count_tokens`).pipe( + HttpClientRequest.setHeaders({ "anthropic-version": options.params?.["anthropic-version"] ?? undefined }), + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(MessagesCountTokensPost200), + "4xx": decodeError("MessagesCountTokensPost4XX", MessagesCountTokensPost4XX), + orElse: unexpectedStatus + })) + ), + "listFilesV1FilesGet": (options) => + HttpClientRequest.get(`/v1/files`).pipe( + HttpClientRequest.setUrlParams({ + "before_id": options?.params?.["before_id"] as any, + "after_id": options?.params?.["after_id"] as any, + "limit": options?.params?.["limit"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListFilesV1FilesGet200), + "4xx": decodeError("ListFilesV1FilesGet4XX", ListFilesV1FilesGet4XX), + orElse: unexpectedStatus + })) + ), + "uploadFileV1FilesPost": (options) => + HttpClientRequest.post(`/v1/files`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? undefined + }), + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UploadFileV1FilesPost200), + "4xx": decodeError("UploadFileV1FilesPost4XX", UploadFileV1FilesPost4XX), + orElse: unexpectedStatus + })) + ), + "getFileMetadataV1FilesFileIdGet": (fileId, options) => + HttpClientRequest.get(`/v1/files/${fileId}`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetFileMetadataV1FilesFileIdGet200), + "4xx": decodeError("GetFileMetadataV1FilesFileIdGet4XX", GetFileMetadataV1FilesFileIdGet4XX), + orElse: unexpectedStatus + })) + ), + "deleteFileV1FilesFileIdDelete": (fileId, options) => + HttpClientRequest.delete(`/v1/files/${fileId}`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteFileV1FilesFileIdDelete200), + "4xx": decodeError("DeleteFileV1FilesFileIdDelete4XX", DeleteFileV1FilesFileIdDelete4XX), + orElse: unexpectedStatus + })) + ), + "downloadFileV1FilesFileIdContentGet": (fileId, options) => + HttpClientRequest.get(`/v1/files/${fileId}/content`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + orElse: unexpectedStatus + })) + ), + "downloadFileV1FilesFileIdContentGetStream": (fileId, options) => + HttpClientRequest.get(`/v1/files/${fileId}/content`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + binaryRequest + ), + "listSkillsV1SkillsGet": (options) => + HttpClientRequest.get(`/v1/skills`).pipe( + HttpClientRequest.setUrlParams({ + "page": options?.params?.["page"] as any, + "limit": options?.params?.["limit"] as any, + "source": options?.params?.["source"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListSkillsV1SkillsGet200), + "4xx": decodeError("ListSkillsV1SkillsGet4XX", ListSkillsV1SkillsGet4XX), + orElse: unexpectedStatus + })) + ), + "createSkillV1SkillsPost": (options) => + HttpClientRequest.post(`/v1/skills`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? undefined + }), + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateSkillV1SkillsPost200), + "4xx": decodeError("CreateSkillV1SkillsPost4XX", CreateSkillV1SkillsPost4XX), + orElse: unexpectedStatus + })) + ), + "getSkillV1SkillsSkillIdGet": (skillId, options) => + HttpClientRequest.get(`/v1/skills/${skillId}`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetSkillV1SkillsSkillIdGet200), + "4xx": decodeError("GetSkillV1SkillsSkillIdGet4XX", GetSkillV1SkillsSkillIdGet4XX), + orElse: unexpectedStatus + })) + ), + "deleteSkillV1SkillsSkillIdDelete": (skillId, options) => + HttpClientRequest.delete(`/v1/skills/${skillId}`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteSkillV1SkillsSkillIdDelete200), + "4xx": decodeError("DeleteSkillV1SkillsSkillIdDelete4XX", DeleteSkillV1SkillsSkillIdDelete4XX), + orElse: unexpectedStatus + })) + ), + "listSkillVersionsV1SkillsSkillIdVersionsGet": (skillId, options) => + HttpClientRequest.get(`/v1/skills/${skillId}/versions`).pipe( + HttpClientRequest.setUrlParams({ + "page": options?.params?.["page"] as any, + "limit": options?.params?.["limit"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListSkillVersionsV1SkillsSkillIdVersionsGet200), + "4xx": decodeError( + "ListSkillVersionsV1SkillsSkillIdVersionsGet4XX", + ListSkillVersionsV1SkillsSkillIdVersionsGet4XX + ), + orElse: unexpectedStatus + })) + ), + "createSkillVersionV1SkillsSkillIdVersionsPost": (skillId, options) => + HttpClientRequest.post(`/v1/skills/${skillId}/versions`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? undefined + }), + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateSkillVersionV1SkillsSkillIdVersionsPost200), + "4xx": decodeError( + "CreateSkillVersionV1SkillsSkillIdVersionsPost4XX", + CreateSkillVersionV1SkillsSkillIdVersionsPost4XX + ), + orElse: unexpectedStatus + })) + ), + "getSkillVersionV1SkillsSkillIdVersionsVersionGet": (skillId, version, options) => + HttpClientRequest.get(`/v1/skills/${skillId}/versions/${version}`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetSkillVersionV1SkillsSkillIdVersionsVersionGet200), + "4xx": decodeError( + "GetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX", + GetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX + ), + orElse: unexpectedStatus + })) + ), + "deleteSkillVersionV1SkillsSkillIdVersionsVersionDelete": (skillId, version, options) => + HttpClientRequest.delete(`/v1/skills/${skillId}/versions/${version}`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete200), + "4xx": decodeError( + "DeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX", + DeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX + ), + orElse: unexpectedStatus + })) + ), + "betaMessagesPost": (options) => + HttpClientRequest.post(`/v1/messages?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? undefined + }), + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaMessagesPost200), + "4xx": decodeError("BetaMessagesPost4XX", BetaMessagesPost4XX), + orElse: unexpectedStatus + })) + ), + "betaModelsList": (options) => + HttpClientRequest.get(`/v1/models?beta=true`).pipe( + HttpClientRequest.setUrlParams({ + "before_id": options?.params?.["before_id"] as any, + "after_id": options?.params?.["after_id"] as any, + "limit": options?.params?.["limit"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined, + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaModelsList200), + "4xx": decodeError("BetaModelsList4XX", BetaModelsList4XX), + orElse: unexpectedStatus + })) + ), + "betaModelsGet": (modelId, options) => + HttpClientRequest.get(`/v1/models/${modelId}?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined, + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaModelsGet200), + "4xx": decodeError("BetaModelsGet4XX", BetaModelsGet4XX), + orElse: unexpectedStatus + })) + ), + "betaMessageBatchesList": (options) => + HttpClientRequest.get(`/v1/messages/batches?beta=true`).pipe( + HttpClientRequest.setUrlParams({ + "before_id": options?.params?.["before_id"] as any, + "after_id": options?.params?.["after_id"] as any, + "limit": options?.params?.["limit"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaMessageBatchesList200), + "4xx": decodeError("BetaMessageBatchesList4XX", BetaMessageBatchesList4XX), + orElse: unexpectedStatus + })) + ), + "betaMessageBatchesPost": (options) => + HttpClientRequest.post(`/v1/messages/batches?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? undefined + }), + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaMessageBatchesPost200), + "4xx": decodeError("BetaMessageBatchesPost4XX", BetaMessageBatchesPost4XX), + orElse: unexpectedStatus + })) + ), + "betaMessageBatchesRetrieve": (messageBatchId, options) => + HttpClientRequest.get(`/v1/messages/batches/${messageBatchId}?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaMessageBatchesRetrieve200), + "4xx": decodeError("BetaMessageBatchesRetrieve4XX", BetaMessageBatchesRetrieve4XX), + orElse: unexpectedStatus + })) + ), + "betaMessageBatchesDelete": (messageBatchId, options) => + HttpClientRequest.delete(`/v1/messages/batches/${messageBatchId}?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaMessageBatchesDelete200), + "4xx": decodeError("BetaMessageBatchesDelete4XX", BetaMessageBatchesDelete4XX), + orElse: unexpectedStatus + })) + ), + "betaMessageBatchesCancel": (messageBatchId, options) => + HttpClientRequest.post(`/v1/messages/batches/${messageBatchId}/cancel?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaMessageBatchesCancel200), + "4xx": decodeError("BetaMessageBatchesCancel4XX", BetaMessageBatchesCancel4XX), + orElse: unexpectedStatus + })) + ), + "betaMessageBatchesResults": (messageBatchId, options) => + HttpClientRequest.get(`/v1/messages/batches/${messageBatchId}/results?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "4xx": decodeError("BetaMessageBatchesResults4XX", BetaMessageBatchesResults4XX), + orElse: unexpectedStatus + })) + ), + "betaMessagesCountTokensPost": (options) => + HttpClientRequest.post(`/v1/messages/count_tokens?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? undefined + }), + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaMessagesCountTokensPost200), + "4xx": decodeError("BetaMessagesCountTokensPost4XX", BetaMessagesCountTokensPost4XX), + orElse: unexpectedStatus + })) + ), + "betaListFilesV1FilesGet": (options) => + HttpClientRequest.get(`/v1/files?beta=true`).pipe( + HttpClientRequest.setUrlParams({ + "before_id": options?.params?.["before_id"] as any, + "after_id": options?.params?.["after_id"] as any, + "limit": options?.params?.["limit"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaListFilesV1FilesGet200), + "4xx": decodeError("BetaListFilesV1FilesGet4XX", BetaListFilesV1FilesGet4XX), + orElse: unexpectedStatus + })) + ), + "betaUploadFileV1FilesPost": (options) => + HttpClientRequest.post(`/v1/files?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? undefined + }), + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaUploadFileV1FilesPost200), + "4xx": decodeError("BetaUploadFileV1FilesPost4XX", BetaUploadFileV1FilesPost4XX), + orElse: unexpectedStatus + })) + ), + "betaGetFileMetadataV1FilesFileIdGet": (fileId, options) => + HttpClientRequest.get(`/v1/files/${fileId}?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaGetFileMetadataV1FilesFileIdGet200), + "4xx": decodeError("BetaGetFileMetadataV1FilesFileIdGet4XX", BetaGetFileMetadataV1FilesFileIdGet4XX), + orElse: unexpectedStatus + })) + ), + "betaDeleteFileV1FilesFileIdDelete": (fileId, options) => + HttpClientRequest.delete(`/v1/files/${fileId}?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaDeleteFileV1FilesFileIdDelete200), + "4xx": decodeError("BetaDeleteFileV1FilesFileIdDelete4XX", BetaDeleteFileV1FilesFileIdDelete4XX), + orElse: unexpectedStatus + })) + ), + "betaDownloadFileV1FilesFileIdContentGet": (fileId, options) => + HttpClientRequest.get(`/v1/files/${fileId}/content?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + orElse: unexpectedStatus + })) + ), + "betaDownloadFileV1FilesFileIdContentGetStream": (fileId, options) => + HttpClientRequest.get(`/v1/files/${fileId}/content?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + binaryRequest + ), + "betaListSkillsV1SkillsGet": (options) => + HttpClientRequest.get(`/v1/skills?beta=true`).pipe( + HttpClientRequest.setUrlParams({ + "page": options?.params?.["page"] as any, + "limit": options?.params?.["limit"] as any, + "source": options?.params?.["source"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaListSkillsV1SkillsGet200), + "4xx": decodeError("BetaListSkillsV1SkillsGet4XX", BetaListSkillsV1SkillsGet4XX), + orElse: unexpectedStatus + })) + ), + "betaCreateSkillV1SkillsPost": (options) => + HttpClientRequest.post(`/v1/skills?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? undefined + }), + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaCreateSkillV1SkillsPost200), + "4xx": decodeError("BetaCreateSkillV1SkillsPost4XX", BetaCreateSkillV1SkillsPost4XX), + orElse: unexpectedStatus + })) + ), + "betaGetSkillV1SkillsSkillIdGet": (skillId, options) => + HttpClientRequest.get(`/v1/skills/${skillId}?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaGetSkillV1SkillsSkillIdGet200), + "4xx": decodeError("BetaGetSkillV1SkillsSkillIdGet4XX", BetaGetSkillV1SkillsSkillIdGet4XX), + orElse: unexpectedStatus + })) + ), + "betaDeleteSkillV1SkillsSkillIdDelete": (skillId, options) => + HttpClientRequest.delete(`/v1/skills/${skillId}?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaDeleteSkillV1SkillsSkillIdDelete200), + "4xx": decodeError("BetaDeleteSkillV1SkillsSkillIdDelete4XX", BetaDeleteSkillV1SkillsSkillIdDelete4XX), + orElse: unexpectedStatus + })) + ), + "betaListSkillVersionsV1SkillsSkillIdVersionsGet": (skillId, options) => + HttpClientRequest.get(`/v1/skills/${skillId}/versions?beta=true`).pipe( + HttpClientRequest.setUrlParams({ + "page": options?.params?.["page"] as any, + "limit": options?.params?.["limit"] as any + }), + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaListSkillVersionsV1SkillsSkillIdVersionsGet200), + "4xx": decodeError( + "BetaListSkillVersionsV1SkillsSkillIdVersionsGet4XX", + BetaListSkillVersionsV1SkillsSkillIdVersionsGet4XX + ), + orElse: unexpectedStatus + })) + ), + "betaCreateSkillVersionV1SkillsSkillIdVersionsPost": (skillId, options) => + HttpClientRequest.post(`/v1/skills/${skillId}/versions?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options.params?.["anthropic-version"] ?? undefined + }), + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaCreateSkillVersionV1SkillsSkillIdVersionsPost200), + "4xx": decodeError( + "BetaCreateSkillVersionV1SkillsSkillIdVersionsPost4XX", + BetaCreateSkillVersionV1SkillsSkillIdVersionsPost4XX + ), + orElse: unexpectedStatus + })) + ), + "betaGetSkillVersionV1SkillsSkillIdVersionsVersionGet": (skillId, version, options) => + HttpClientRequest.get(`/v1/skills/${skillId}/versions/${version}?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGet200), + "4xx": decodeError( + "BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX", + BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX + ), + orElse: unexpectedStatus + })) + ), + "betaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete": (skillId, version, options) => + HttpClientRequest.delete(`/v1/skills/${skillId}/versions/${version}?beta=true`).pipe( + HttpClientRequest.setHeaders({ + "anthropic-beta": options?.params?.["anthropic-beta"] ?? undefined, + "anthropic-version": options?.params?.["anthropic-version"] ?? undefined, + "x-api-key": options?.params?.["x-api-key"] ?? undefined + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete200), + "4xx": decodeError( + "BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX", + BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX + ), + orElse: unexpectedStatus + })) + ) + } +} + +export interface AnthropicClient { + readonly httpClient: HttpClient.HttpClient + /** + * Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation. + * + * The Messages API can be used for either single queries or stateless multi-turn conversations. + * + * Learn more about the Messages API in our [user guide](https://docs.claude.com/en/docs/initial-setup) + */ + readonly "messagesPost": ( + options: { + readonly params?: typeof MessagesPostParams.Encoded | undefined + readonly payload: typeof MessagesPostRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError | AnthropicClientError<"MessagesPost4XX", typeof MessagesPost4XX.Type> + > + /** + * [Legacy] Create a Text Completion. + * + * The Text Completions API is a legacy API. We recommend using the [Messages API](https://docs.claude.com/en/api/messages) going forward. + * + * Future models and features will not be compatible with Text Completions. See our [migration guide](https://docs.claude.com/en/api/migrating-from-text-completions-to-messages) for guidance in migrating from Text Completions to Messages. + */ + readonly "completePost": ( + options: { + readonly params?: typeof CompletePostParams.Encoded | undefined + readonly payload: typeof CompletePostRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError | AnthropicClientError<"CompletePost4XX", typeof CompletePost4XX.Type> + > + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the API. More recently released models are listed first. + */ + readonly "modelsList": ( + options: + | { readonly params?: typeof ModelsListParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError | AnthropicClientError<"ModelsList4XX", typeof ModelsList4XX.Type> + > + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or resolve a model alias to a model ID. + */ + readonly "modelsGet": ( + modelId: string, + options: + | { readonly params?: typeof ModelsGetParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError | AnthropicClientError<"ModelsGet4XX", typeof ModelsGet4XX.Type> + > + /** + * List all Message Batches within a Workspace. Most recently created batches are returned first. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "messageBatchesList": ( + options: { + readonly params?: typeof MessageBatchesListParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"MessageBatchesList4XX", typeof MessageBatchesList4XX.Type> + > + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at once. Once a Message Batch is created, it begins processing immediately. Batches can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "messageBatchesPost": ( + options: { + readonly params?: typeof MessageBatchesPostParams.Encoded | undefined + readonly payload: typeof MessageBatchesPostRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"MessageBatchesPost4XX", typeof MessageBatchesPost4XX.Type> + > + /** + * This endpoint is idempotent and can be used to poll for Message Batch completion. To access the results of a Message Batch, make a request to the `results_url` field in the response. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "messageBatchesRetrieve": ( + messageBatchId: string, + options: { + readonly params?: typeof MessageBatchesRetrieveParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"MessageBatchesRetrieve4XX", typeof MessageBatchesRetrieve4XX.Type> + > + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "messageBatchesDelete": ( + messageBatchId: string, + options: { + readonly params?: typeof MessageBatchesDeleteParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"MessageBatchesDelete4XX", typeof MessageBatchesDelete4XX.Type> + > + /** + * Batches may be canceled any time before processing ends. Once cancellation is initiated, the batch enters a `canceling` state, at which time the system may complete any in-progress, non-interruptible requests before finalizing cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine which requests were canceled, check the individual results within the batch. Note that cancellation may not result in any canceled requests if they were non-interruptible. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "messageBatchesCancel": ( + messageBatchId: string, + options: { + readonly params?: typeof MessageBatchesCancelParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"MessageBatchesCancel4XX", typeof MessageBatchesCancel4XX.Type> + > + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request in the Message Batch. Results are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "messageBatchesResults": ( + messageBatchId: string, + options: { + readonly params?: typeof MessageBatchesResultsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"MessageBatchesResults4XX", typeof MessageBatchesResults4XX.Type> + > + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, including tools, images, and documents, without creating it. + * + * Learn more about token counting in our [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) + */ + readonly "messagesCountTokensPost": ( + options: { + readonly params?: typeof MessagesCountTokensPostParams.Encoded | undefined + readonly payload: typeof MessagesCountTokensPostRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"MessagesCountTokensPost4XX", typeof MessagesCountTokensPost4XX.Type> + > + /** + * List Files + */ + readonly "listFilesV1FilesGet": ( + options: { + readonly params?: typeof ListFilesV1FilesGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"ListFilesV1FilesGet4XX", typeof ListFilesV1FilesGet4XX.Type> + > + /** + * Upload File + */ + readonly "uploadFileV1FilesPost": ( + options: { + readonly params?: typeof UploadFileV1FilesPostParams.Encoded | undefined + readonly payload: typeof UploadFileV1FilesPostRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"UploadFileV1FilesPost4XX", typeof UploadFileV1FilesPost4XX.Type> + > + /** + * Get File Metadata + */ + readonly "getFileMetadataV1FilesFileIdGet": ( + fileId: string, + options: { + readonly params?: typeof GetFileMetadataV1FilesFileIdGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"GetFileMetadataV1FilesFileIdGet4XX", typeof GetFileMetadataV1FilesFileIdGet4XX.Type> + > + /** + * Delete File + */ + readonly "deleteFileV1FilesFileIdDelete": ( + fileId: string, + options: { + readonly params?: typeof DeleteFileV1FilesFileIdDeleteParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"DeleteFileV1FilesFileIdDelete4XX", typeof DeleteFileV1FilesFileIdDelete4XX.Type> + > + /** + * Download File + */ + readonly "downloadFileV1FilesFileIdContentGet": ( + fileId: string, + options: { + readonly params?: typeof DownloadFileV1FilesFileIdContentGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Download File + */ + readonly "downloadFileV1FilesFileIdContentGetStream": ( + fileId: string, + options: { readonly params?: typeof DownloadFileV1FilesFileIdContentGetParams.Encoded | undefined } | undefined + ) => Stream.Stream + /** + * List Skills + */ + readonly "listSkillsV1SkillsGet": ( + options: { + readonly params?: typeof ListSkillsV1SkillsGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"ListSkillsV1SkillsGet4XX", typeof ListSkillsV1SkillsGet4XX.Type> + > + /** + * Create Skill + */ + readonly "createSkillV1SkillsPost": ( + options: { + readonly params?: typeof CreateSkillV1SkillsPostParams.Encoded | undefined + readonly payload: typeof CreateSkillV1SkillsPostRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"CreateSkillV1SkillsPost4XX", typeof CreateSkillV1SkillsPost4XX.Type> + > + /** + * Get Skill + */ + readonly "getSkillV1SkillsSkillIdGet": ( + skillId: string, + options: { + readonly params?: typeof GetSkillV1SkillsSkillIdGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"GetSkillV1SkillsSkillIdGet4XX", typeof GetSkillV1SkillsSkillIdGet4XX.Type> + > + /** + * Delete Skill + */ + readonly "deleteSkillV1SkillsSkillIdDelete": ( + skillId: string, + options: { + readonly params?: typeof DeleteSkillV1SkillsSkillIdDeleteParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"DeleteSkillV1SkillsSkillIdDelete4XX", typeof DeleteSkillV1SkillsSkillIdDelete4XX.Type> + > + /** + * List Skill Versions + */ + readonly "listSkillVersionsV1SkillsSkillIdVersionsGet": ( + skillId: string, + options: { + readonly params?: typeof ListSkillVersionsV1SkillsSkillIdVersionsGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError< + "ListSkillVersionsV1SkillsSkillIdVersionsGet4XX", + typeof ListSkillVersionsV1SkillsSkillIdVersionsGet4XX.Type + > + > + /** + * Create Skill Version + */ + readonly "createSkillVersionV1SkillsSkillIdVersionsPost": ( + skillId: string, + options: { + readonly params?: typeof CreateSkillVersionV1SkillsSkillIdVersionsPostParams.Encoded | undefined + readonly payload: typeof CreateSkillVersionV1SkillsSkillIdVersionsPostRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError< + "CreateSkillVersionV1SkillsSkillIdVersionsPost4XX", + typeof CreateSkillVersionV1SkillsSkillIdVersionsPost4XX.Type + > + > + /** + * Get Skill Version + */ + readonly "getSkillVersionV1SkillsSkillIdVersionsVersionGet": ( + skillId: string, + version: string, + options: { + readonly params?: typeof GetSkillVersionV1SkillsSkillIdVersionsVersionGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError< + "GetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX", + typeof GetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX.Type + > + > + /** + * Delete Skill Version + */ + readonly "deleteSkillVersionV1SkillsSkillIdVersionsVersionDelete": ( + skillId: string, + version: string, + options: { + readonly params?: typeof DeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError< + "DeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX", + typeof DeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX.Type + > + > + /** + * Send a structured list of input messages with text and/or image content, and the model will generate the next message in the conversation. + * + * The Messages API can be used for either single queries or stateless multi-turn conversations. + * + * Learn more about the Messages API in our [user guide](https://docs.claude.com/en/docs/initial-setup) + */ + readonly "betaMessagesPost": ( + options: { + readonly params?: typeof BetaMessagesPostParams.Encoded | undefined + readonly payload: typeof BetaMessagesPostRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaMessagesPost4XX", typeof BetaMessagesPost4XX.Type> + > + /** + * List available models. + * + * The Models API response can be used to determine which models are available for use in the API. More recently released models are listed first. + */ + readonly "betaModelsList": ( + options: + | { readonly params?: typeof BetaModelsListParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaModelsList4XX", typeof BetaModelsList4XX.Type> + > + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific model or resolve a model alias to a model ID. + */ + readonly "betaModelsGet": ( + modelId: string, + options: + | { readonly params?: typeof BetaModelsGetParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaModelsGet4XX", typeof BetaModelsGet4XX.Type> + > + /** + * List all Message Batches within a Workspace. Most recently created batches are returned first. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "betaMessageBatchesList": ( + options: { + readonly params?: typeof BetaMessageBatchesListParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaMessageBatchesList4XX", typeof BetaMessageBatchesList4XX.Type> + > + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at once. Once a Message Batch is created, it begins processing immediately. Batches can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "betaMessageBatchesPost": ( + options: { + readonly params?: typeof BetaMessageBatchesPostParams.Encoded | undefined + readonly payload: typeof BetaMessageBatchesPostRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaMessageBatchesPost4XX", typeof BetaMessageBatchesPost4XX.Type> + > + /** + * This endpoint is idempotent and can be used to poll for Message Batch completion. To access the results of a Message Batch, make a request to the `results_url` field in the response. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "betaMessageBatchesRetrieve": ( + messageBatchId: string, + options: { + readonly params?: typeof BetaMessageBatchesRetrieveParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaMessageBatchesRetrieve4XX", typeof BetaMessageBatchesRetrieve4XX.Type> + > + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "betaMessageBatchesDelete": ( + messageBatchId: string, + options: { + readonly params?: typeof BetaMessageBatchesDeleteParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaMessageBatchesDelete4XX", typeof BetaMessageBatchesDelete4XX.Type> + > + /** + * Batches may be canceled any time before processing ends. Once cancellation is initiated, the batch enters a `canceling` state, at which time the system may complete any in-progress, non-interruptible requests before finalizing cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine which requests were canceled, check the individual results within the batch. Note that cancellation may not result in any canceled requests if they were non-interruptible. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "betaMessageBatchesCancel": ( + messageBatchId: string, + options: { + readonly params?: typeof BetaMessageBatchesCancelParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaMessageBatchesCancel4XX", typeof BetaMessageBatchesCancel4XX.Type> + > + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request in the Message Batch. Results are not guaranteed to be in the same order as requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + */ + readonly "betaMessageBatchesResults": ( + messageBatchId: string, + options: { + readonly params?: typeof BetaMessageBatchesResultsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaMessageBatchesResults4XX", typeof BetaMessageBatchesResults4XX.Type> + > + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, including tools, images, and documents, without creating it. + * + * Learn more about token counting in our [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) + */ + readonly "betaMessagesCountTokensPost": ( + options: { + readonly params?: typeof BetaMessagesCountTokensPostParams.Encoded | undefined + readonly payload: typeof BetaMessagesCountTokensPostRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaMessagesCountTokensPost4XX", typeof BetaMessagesCountTokensPost4XX.Type> + > + /** + * List Files + */ + readonly "betaListFilesV1FilesGet": ( + options: { + readonly params?: typeof BetaListFilesV1FilesGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaListFilesV1FilesGet4XX", typeof BetaListFilesV1FilesGet4XX.Type> + > + /** + * Upload File + */ + readonly "betaUploadFileV1FilesPost": ( + options: { + readonly params?: typeof BetaUploadFileV1FilesPostParams.Encoded | undefined + readonly payload: typeof BetaUploadFileV1FilesPostRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaUploadFileV1FilesPost4XX", typeof BetaUploadFileV1FilesPost4XX.Type> + > + /** + * Get File Metadata + */ + readonly "betaGetFileMetadataV1FilesFileIdGet": ( + fileId: string, + options: { + readonly params?: typeof BetaGetFileMetadataV1FilesFileIdGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaGetFileMetadataV1FilesFileIdGet4XX", typeof BetaGetFileMetadataV1FilesFileIdGet4XX.Type> + > + /** + * Delete File + */ + readonly "betaDeleteFileV1FilesFileIdDelete": ( + fileId: string, + options: { + readonly params?: typeof BetaDeleteFileV1FilesFileIdDeleteParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaDeleteFileV1FilesFileIdDelete4XX", typeof BetaDeleteFileV1FilesFileIdDelete4XX.Type> + > + /** + * Download File + */ + readonly "betaDownloadFileV1FilesFileIdContentGet": ( + fileId: string, + options: { + readonly params?: typeof BetaDownloadFileV1FilesFileIdContentGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Download File + */ + readonly "betaDownloadFileV1FilesFileIdContentGetStream": ( + fileId: string, + options: { readonly params?: typeof BetaDownloadFileV1FilesFileIdContentGetParams.Encoded | undefined } | undefined + ) => Stream.Stream + /** + * List Skills + */ + readonly "betaListSkillsV1SkillsGet": ( + options: { + readonly params?: typeof BetaListSkillsV1SkillsGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaListSkillsV1SkillsGet4XX", typeof BetaListSkillsV1SkillsGet4XX.Type> + > + /** + * Create Skill + */ + readonly "betaCreateSkillV1SkillsPost": ( + options: { + readonly params?: typeof BetaCreateSkillV1SkillsPostParams.Encoded | undefined + readonly payload: typeof BetaCreateSkillV1SkillsPostRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaCreateSkillV1SkillsPost4XX", typeof BetaCreateSkillV1SkillsPost4XX.Type> + > + /** + * Get Skill + */ + readonly "betaGetSkillV1SkillsSkillIdGet": ( + skillId: string, + options: { + readonly params?: typeof BetaGetSkillV1SkillsSkillIdGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError<"BetaGetSkillV1SkillsSkillIdGet4XX", typeof BetaGetSkillV1SkillsSkillIdGet4XX.Type> + > + /** + * Delete Skill + */ + readonly "betaDeleteSkillV1SkillsSkillIdDelete": ( + skillId: string, + options: { + readonly params?: typeof BetaDeleteSkillV1SkillsSkillIdDeleteParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError< + "BetaDeleteSkillV1SkillsSkillIdDelete4XX", + typeof BetaDeleteSkillV1SkillsSkillIdDelete4XX.Type + > + > + /** + * List Skill Versions + */ + readonly "betaListSkillVersionsV1SkillsSkillIdVersionsGet": ( + skillId: string, + options: { + readonly params?: typeof BetaListSkillVersionsV1SkillsSkillIdVersionsGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError< + "BetaListSkillVersionsV1SkillsSkillIdVersionsGet4XX", + typeof BetaListSkillVersionsV1SkillsSkillIdVersionsGet4XX.Type + > + > + /** + * Create Skill Version + */ + readonly "betaCreateSkillVersionV1SkillsSkillIdVersionsPost": ( + skillId: string, + options: { + readonly params?: typeof BetaCreateSkillVersionV1SkillsSkillIdVersionsPostParams.Encoded | undefined + readonly payload: typeof BetaCreateSkillVersionV1SkillsSkillIdVersionsPostRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError< + "BetaCreateSkillVersionV1SkillsSkillIdVersionsPost4XX", + typeof BetaCreateSkillVersionV1SkillsSkillIdVersionsPost4XX.Type + > + > + /** + * Get Skill Version + */ + readonly "betaGetSkillVersionV1SkillsSkillIdVersionsVersionGet": ( + skillId: string, + version: string, + options: { + readonly params?: typeof BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGetParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError< + "BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX", + typeof BetaGetSkillVersionV1SkillsSkillIdVersionsVersionGet4XX.Type + > + > + /** + * Delete Skill Version + */ + readonly "betaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete": ( + skillId: string, + version: string, + options: { + readonly params?: typeof BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDeleteParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | AnthropicClientError< + "BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX", + typeof BetaDeleteSkillVersionV1SkillsSkillIdVersionsVersionDelete4XX.Type + > + > +} + +export interface AnthropicClientError { + readonly _tag: Tag + readonly request: HttpClientRequest.HttpClientRequest + readonly response: HttpClientResponse.HttpClientResponse + readonly cause: E +} + +class AnthropicClientErrorImpl extends Data.Error<{ + _tag: string + cause: any + request: HttpClientRequest.HttpClientRequest + response: HttpClientResponse.HttpClientResponse +}> {} + +export const AnthropicClientError = ( + tag: Tag, + cause: E, + response: HttpClientResponse.HttpClientResponse +): AnthropicClientError => + new AnthropicClientErrorImpl({ + _tag: tag, + cause, + response, + request: response.request + }) as any diff --git a/packages/effect-ai-anthropic/src/index.ts b/packages/effect-ai-anthropic/src/index.ts new file mode 100644 index 0000000..48af730 --- /dev/null +++ b/packages/effect-ai-anthropic/src/index.ts @@ -0,0 +1,40 @@ +/** + * @since 4.0.0 + */ + +// @barrel: Auto-generated exports. Do not edit manually. + +/** + * @since 4.0.0 + */ +export * as AnthropicClient from "./AnthropicClient.ts" + +/** + * @since 4.0.0 + */ +export * as AnthropicConfig from "./AnthropicConfig.ts" + +/** + * @since 4.0.0 + */ +export * as AnthropicError from "./AnthropicError.ts" + +/** + * @since 4.0.0 + */ +export * as AnthropicLanguageModel from "./AnthropicLanguageModel.ts" + +/** + * @since 4.0.0 + */ +export * as AnthropicTelemetry from "./AnthropicTelemetry.ts" + +/** + * @since 4.0.0 + */ +export * as AnthropicTool from "./AnthropicTool.ts" + +/** + * @since 4.0.0 + */ +export * as Generated from "./Generated.ts" diff --git a/packages/effect-ai-anthropic/src/internal/errors.ts b/packages/effect-ai-anthropic/src/internal/errors.ts new file mode 100644 index 0000000..e0b2e95 --- /dev/null +++ b/packages/effect-ai-anthropic/src/internal/errors.ts @@ -0,0 +1,347 @@ +import * as Duration from "effect/Duration" +import * as Effect from "effect/Effect" +import { dual } from "effect/Function" +import * as Number from "effect/Number" +import * as Option from "effect/Option" +import * as Predicate from "effect/Predicate" +import * as Redactable from "effect/Redactable" +import * as Schema from "effect/Schema" +import * as AiError from "effect/unstable/ai/AiError" +import type * as Response from "effect/unstable/ai/Response" +import type * as Sse from "effect/unstable/encoding/Sse" +import type * as HttpClientError from "effect/unstable/http/HttpClientError" +import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import type { AnthropicErrorMetadata } from "../AnthropicError.ts" +import type * as Generated from "../Generated.ts" + +// ============================================================================= +// Anthropic Error Body Schema +// ============================================================================= + +/** @internal */ +export const AnthropicErrorBody = Schema.Struct({ + type: Schema.Literal("error"), + error: Schema.Struct({ + type: Schema.String, + message: Schema.String + }) +}) + +/** @internal */ +export type AnthropicClientErrorBody = { + readonly type: "error" + readonly error: { + readonly type: string + readonly message: string + } + readonly request_id: string | null +} + +// ============================================================================= +// Error Mappers +// ============================================================================= + +/** @internal */ +export const mapSchemaError = dual< + (method: string) => (error: Schema.SchemaError) => AiError.AiError, + (error: Schema.SchemaError, method: string) => AiError.AiError +>(2, (error, method) => + AiError.make({ + module: "AnthropicClient", + method, + reason: AiError.InvalidOutputError.fromSchemaError(error) + })) + +/** @internal */ +export const mapSseError = dual< + (method: string) => (error: Sse.SseError) => AiError.AiError, + (error: Sse.SseError, method: string) => AiError.AiError +>(2, (error, method) => + AiError.make({ + module: "AnthropicClient", + method, + reason: new AiError.InvalidOutputError({ description: error.message }) + })) + +/** @internal */ +export const mapClientError = dual< + (method: string) => (error: Generated.AnthropicClientError) => AiError.AiError, + (error: Generated.AnthropicClientError, method: string) => AiError.AiError +>(2, (error, method) => { + const { request, response, cause } = error + const status = response.status + const headers = response.headers as Record + const metadata: AnthropicErrorMetadata = { + errorType: cause.error.type, + requestId: cause.request_id + } + const http = buildHttpContext({ request, response, body: JSON.stringify(cause) }) + const reason = mapStatusCodeToReason({ + status, + headers, + message: cause.error.message, + metadata, + http + }) + return AiError.make({ module: "AnthropicClient", method, reason }) +}) + +/** @internal */ +export const mapHttpClientError = dual< + (method: string) => (error: HttpClientError.HttpClientError) => Effect.Effect, + (error: HttpClientError.HttpClientError, method: string) => Effect.Effect +>(2, (error, method) => { + const reason = error.reason + switch (reason._tag) { + case "TransportError": { + return Effect.fail(AiError.make({ + module: "AnthropicClient", + method, + reason: new AiError.NetworkError({ + reason: "TransportError", + description: reason.description, + request: buildHttpRequestDetails(reason.request) + }) + })) + } + case "EncodeError": { + return Effect.fail(AiError.make({ + module: "AnthropicClient", + method, + reason: new AiError.NetworkError({ + reason: "EncodeError", + description: reason.description, + request: buildHttpRequestDetails(reason.request) + }) + })) + } + case "InvalidUrlError": { + return Effect.fail(AiError.make({ + module: "AnthropicClient", + method, + reason: new AiError.NetworkError({ + reason: "InvalidUrlError", + description: reason.description, + request: buildHttpRequestDetails(reason.request) + }) + })) + } + case "StatusCodeError": { + return mapStatusCodeError(reason, method) + } + case "DecodeError": { + return Effect.fail(AiError.make({ + module: "AnthropicClient", + method, + reason: new AiError.InvalidOutputError({ + description: reason.description ?? "Failed to decode response" + }) + })) + } + case "EmptyBodyError": { + return Effect.fail(AiError.make({ + module: "AnthropicClient", + method, + reason: new AiError.InvalidOutputError({ + description: reason.description ?? "Response body was empty" + }) + })) + } + } +}) + +/** @internal */ +const mapStatusCodeError = Effect.fnUntraced(function*( + error: HttpClientError.StatusCodeError, + method: string +) { + const { request, response, description } = error + const status = response.status + const headers = response.headers as Record + const requestId = headers["request-id"] + + let body: string | undefined = description + if (!description || !description.startsWith("{")) { + const responseBody = yield* Effect.option(response.text) + if (Option.isSome(responseBody) && responseBody.value) { + body = responseBody.value + } + } + + let json: unknown = undefined + // @effect-diagnostics effect/tryCatchInEffectGen:off + try { + json = Predicate.isNotUndefined(body) ? JSON.parse(body) : undefined + } catch { + json = undefined + } + const decoded = Schema.decodeUnknownOption(AnthropicErrorBody)(json) + + const reason = mapStatusCodeToReason({ + status, + headers, + message: Option.isSome(decoded) ? decoded.value.error.message : undefined, + http: buildHttpContext({ request, response, body }), + metadata: { + errorType: Option.isSome(decoded) ? decoded.value.error.type : null, + requestId: requestId ?? null + } + }) + + return yield* AiError.make({ module: "AnthropicClient", method, reason }) +}) + +// ============================================================================= +// Rate Limits +// ============================================================================= + +/** @internal */ +export const parseRateLimitHeaders = (headers: Record) => { + const retryAfterRaw = headers["retry-after"] + let retryAfter: Duration.Duration | undefined + if (Predicate.isNotUndefined(retryAfterRaw)) { + const parsed = Number.parse(retryAfterRaw) + if (Option.isSome(parsed)) { + retryAfter = Duration.seconds(parsed.value) + } + } + const requestsLimitRaw = headers["anthropic-ratelimit-requests-limit"] + const requestsRemainingRaw = headers["anthropic-ratelimit-requests-remaining"] + const tokensLimitRaw = headers["anthropic-ratelimit-tokens-limit"] + const tokensRemainingRaw = headers["anthropic-ratelimit-tokens-remaining"] + return { + retryAfter, + requestsLimit: Predicate.isNotUndefined(requestsLimitRaw) ? Option.getOrNull(Number.parse(requestsLimitRaw)) : null, + requestsRemaining: Predicate.isNotUndefined(requestsRemainingRaw) + ? Option.getOrNull(Number.parse(requestsRemainingRaw)) + : null, + requestsReset: headers["anthropic-ratelimit-requests-reset"] ?? null, + tokensLimit: Predicate.isNotUndefined(tokensLimitRaw) ? Option.getOrNull(Number.parse(tokensLimitRaw)) : null, + tokensRemaining: Predicate.isNotUndefined(tokensRemainingRaw) + ? Option.getOrNull(Number.parse(tokensRemainingRaw)) + : null, + tokensReset: headers["anthropic-ratelimit-tokens-reset"] ?? null + } +} + +// ============================================================================= +// HTTP Context +// ============================================================================= + +/** @internal */ +export const buildHttpRequestDetails = ( + request: HttpClientRequest.HttpClientRequest +): typeof Response.HttpRequestDetails.Type => ({ + method: request.method, + url: request.url, + urlParams: Array.from(request.urlParams), + hash: Option.getOrUndefined(request.hash), + headers: Redactable.redact(request.headers) as Record +}) + +/** @internal */ +export const buildHttpContext = (params: { + readonly request: HttpClientRequest.HttpClientRequest + readonly response?: HttpClientResponse.HttpClientResponse + readonly body?: string | undefined +}): typeof AiError.HttpContext.Type => ({ + request: buildHttpRequestDetails(params.request), + response: Predicate.isNotUndefined(params.response) + ? { + status: params.response.status, + headers: Redactable.redact(params.response.headers) as Record + } + : undefined, + body: params.body +}) + +// ============================================================================= +// HTTP Status Code +// ============================================================================= + +/** @internal */ +export const mapStatusCodeToReason = ({ status, headers, message, metadata, http }: { + readonly status: number + readonly headers: Record + readonly message: string | undefined + readonly metadata: AnthropicErrorMetadata + readonly http: typeof AiError.HttpContext.Type +}): AiError.AiErrorReason => { + const errorDescription = AiError.buildErrorDescription({ + status, + message, + method: http.request.method, + url: http.request.url, + errorType: metadata.errorType, + requestId: metadata.requestId, + body: http.body + }) + + switch (status) { + case 400: + return new AiError.InvalidRequestError({ + description: errorDescription, + metadata: { anthropic: metadata }, + http + }) + case 401: + return new AiError.AuthenticationError({ + kind: "InvalidKey", + description: errorDescription, + metadata: { anthropic: metadata }, + http + }) + case 403: + return new AiError.AuthenticationError({ + kind: "InsufficientPermissions", + description: errorDescription, + metadata: { anthropic: metadata }, + http + }) + case 404: + return new AiError.InvalidRequestError({ + description: errorDescription, + metadata: { anthropic: metadata }, + http + }) + case 422: + return new AiError.InvalidRequestError({ + description: errorDescription, + metadata: { anthropic: metadata }, + http + }) + case 429: { + const { retryAfter, ...rateLimitMetadata } = parseRateLimitHeaders(headers) + return new AiError.RateLimitError({ + retryAfter, + metadata: { + anthropic: { + ...metadata, + ...rateLimitMetadata + } + }, + http + }) + } + case 529: + return new AiError.InternalProviderError({ + description: message ?? "Anthropic API is overloaded", + metadata: { anthropic: metadata }, + http + }) + default: + if (status >= 500) { + return new AiError.InternalProviderError({ + description: message ?? "Server error", + metadata: { anthropic: metadata }, + http + }) + } + return new AiError.UnknownError({ + description: message, + metadata: { anthropic: metadata }, + http + }) + } +} diff --git a/packages/effect-ai-anthropic/src/internal/utilities.ts b/packages/effect-ai-anthropic/src/internal/utilities.ts new file mode 100644 index 0000000..322b035 --- /dev/null +++ b/packages/effect-ai-anthropic/src/internal/utilities.ts @@ -0,0 +1,26 @@ +import * as Predicate from "effect/Predicate" +import type * as Response from "effect/unstable/ai/Response" + +const finishReasonMap: Record = { + end_turn: "stop", + max_tokens: "length", + pause_turn: "pause", + refusal: "content-filter", + stop_sequence: "stop", + tool_use: "tool-calls" +} + +/** @internal */ +export const resolveFinishReason = ( + finishReason: string, + isJsonResponse: boolean = false +): Response.FinishReason => { + const reason = Object.hasOwn(finishReasonMap, finishReason) ? finishReasonMap[finishReason] : undefined + if (Predicate.isUndefined(reason)) { + return "unknown" + } + if (isJsonResponse && reason === "tool-calls") { + return "stop" + } + return reason +} diff --git a/packages/effect-ai-anthropic/test/HumanlayerFork.test.ts b/packages/effect-ai-anthropic/test/HumanlayerFork.test.ts new file mode 100644 index 0000000..057e273 --- /dev/null +++ b/packages/effect-ai-anthropic/test/HumanlayerFork.test.ts @@ -0,0 +1,146 @@ +import { assert, describe, it } from '@effect/vitest' +import { AnthropicClient, AnthropicLanguageModel } from '@humanlayer/effect-ai-anthropic' +import { Effect, Layer, Predicate, Redacted, Schema } from 'effect' +import { LanguageModel, Prompt } from 'effect/unstable/ai' +import { HttpClient, type HttpClientError, HttpClientResponse } from 'effect/unstable/http' + +const CapturedRequest = Schema.Struct({ + messages: Schema.Array( + Schema.Struct({ + role: Schema.String, + content: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), + }), + ), +}) + +describe('@humanlayer/effect-ai-anthropic', () => { + it('uses HumanLayer-specific Effect service keys', () => { + assert.strictEqual(AnthropicClient.AnthropicClient.key, '@humanlayer/effect-ai-anthropic/AnthropicClient') + assert.strictEqual( + AnthropicLanguageModel.Config.key, + '@humanlayer/effect-ai-anthropic/AnthropicLanguageModel/Config', + ) + }) + + it.effect('preserves string and ordered multipart tool results while retaining JSON fallback', () => + Effect.gen(function* () { + let requestBody: unknown = null + const preprocess: HttpClient.HttpClient.Preprocess = Effect.succeed + const httpClient = HttpClient.makeWith( + Effect.fnUntraced(function* (requestEffect) { + const request = yield* requestEffect + if (!Predicate.isTagged(request.body, 'Uint8Array')) { + return yield* Effect.die('Expected request bytes') + } + requestBody = JSON.parse(new TextDecoder().decode(request.body.body)) + return HttpClientResponse.fromWeb( + request, + new Response( + JSON.stringify({ + id: 'msg_humanlayer_provider_test', + type: 'message', + role: 'assistant', + model: 'claude-test', + content: [{ type: 'text', text: 'ok' }], + stop_reason: 'end_turn', + stop_sequence: null, + usage: { + cache_creation: null, + cache_creation_input_tokens: null, + cache_read_input_tokens: null, + inference_geo: null, + input_tokens: 1, + output_tokens: 1, + service_tier: null, + }, + }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ), + ) + }), + preprocess, + ) + const clientLayer = AnthropicClient.layer({ apiKey: Redacted.make('sk-test') }).pipe( + Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient)), + ) + const modelLayer = AnthropicLanguageModel.model('claude-test').pipe(Layer.provide(clientLayer)) + const prompt = Prompt.fromMessages([ + Prompt.assistantMessage({ + content: [ + Prompt.toolCallPart({ + id: 'call_text', + name: 'text_tool', + params: {}, + providerExecuted: false, + }), + Prompt.toolCallPart({ + id: 'call_multipart', + name: 'multipart_tool', + params: {}, + providerExecuted: false, + }), + Prompt.toolCallPart({ + id: 'call_object', + name: 'object_tool', + params: {}, + providerExecuted: false, + }), + ], + }), + Prompt.toolMessage({ + content: [ + Prompt.toolResultPart({ + id: 'call_text', + name: 'text_tool', + result: 'PLAIN_TEXT_SENTINEL\n', + isFailure: false, + providerExecuted: false, + }), + Prompt.toolResultPart({ + id: 'call_multipart', + name: 'multipart_tool', + result: [ + Prompt.textPart({ text: 'BEFORE_IMAGE' }), + Prompt.filePart({ mediaType: 'image/png', data: 'iVBORw==' }), + Prompt.textPart({ text: 'AFTER_IMAGE' }), + ], + isFailure: false, + providerExecuted: false, + }), + Prompt.toolResultPart({ + id: 'call_object', + name: 'object_tool', + result: { answer: 42 }, + isFailure: false, + providerExecuted: false, + }), + ], + }), + ]) + + yield* LanguageModel.generateText({ prompt }).pipe(Effect.provide(modelLayer)) + + const body = Schema.decodeUnknownSync(CapturedRequest)(requestBody) + const toolResults = body.messages.flatMap((message) => + message.content.filter((block) => block['type'] === 'tool_result'), + ) + const textOutput = toolResults.find((block) => block['tool_use_id'] === 'call_text') + const multipartOutput = toolResults.find((block) => block['tool_use_id'] === 'call_multipart') + const objectOutput = toolResults.find((block) => block['tool_use_id'] === 'call_object') + + assert.isDefined(textOutput) + assert.isDefined(multipartOutput) + assert.isDefined(objectOutput) + assert.strictEqual(textOutput['content'], 'PLAIN_TEXT_SENTINEL\n') + assert.deepStrictEqual(multipartOutput['content'], [ + { type: 'text', text: 'BEFORE_IMAGE' }, + { + type: 'image', + source: { type: 'base64', media_type: 'image/png', data: 'iVBORw==' }, + }, + { type: 'text', text: 'AFTER_IMAGE' }, + ]) + assert.strictEqual(objectOutput['content'], JSON.stringify({ answer: 42 })) + }), + ) +}) diff --git a/packages/effect-ai-anthropic/tsconfig.json b/packages/effect-ai-anthropic/tsconfig.json new file mode 100644 index 0000000..75fb0eb --- /dev/null +++ b/packages/effect-ai-anthropic/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noUncheckedIndexedAccess": false, + "noImplicitReturns": false + }, + "include": ["src"] +} diff --git a/packages/effect-ai-anthropic/vitest.config.ts b/packages/effect-ai-anthropic/vitest.config.ts new file mode 100644 index 0000000..62216b1 --- /dev/null +++ b/packages/effect-ai-anthropic/vitest.config.ts @@ -0,0 +1,3 @@ +import { base } from '@humanlayer/fold-vitest-config' + +export default base diff --git a/packages/effect-ai-openai-compat/LICENSE b/packages/effect-ai-openai-compat/LICENSE new file mode 100644 index 0000000..be1f5c1 --- /dev/null +++ b/packages/effect-ai-openai-compat/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Effectful Technologies Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/effect-ai-openai-compat/README.md b/packages/effect-ai-openai-compat/README.md new file mode 100644 index 0000000..dfae504 --- /dev/null +++ b/packages/effect-ai-openai-compat/README.md @@ -0,0 +1,14 @@ +# @humanlayer/effect-ai-openai-compat + +Connects the Effect AI modules to any OpenAI-compatible API, with support for chat completions and embeddings. + +## Installation + +```sh +npm install effect@4.0.0-rc.112 @humanlayer/effect-ai-openai-compat +``` + +## Documentation + +- [Effect website](https://effect.website) +- [API reference](https://effect.website/docs/v4/api/ai-openai-compat) diff --git a/packages/effect-ai-openai-compat/UPSTREAM.md b/packages/effect-ai-openai-compat/UPSTREAM.md new file mode 100644 index 0000000..29c26cc --- /dev/null +++ b/packages/effect-ai-openai-compat/UPSTREAM.md @@ -0,0 +1,28 @@ +# Upstream provenance + +This directory is a vendored source snapshot of the published Effect OpenAI-compatible provider. It does not contain +upstream `dist/` output. + +| Field | Value | +| ---------------- | ---------------------------------------------------------------------------------------------------- | +| Upstream package | `@effect/ai-openai-compat@4.0.0-rc.112` | +| Source artifact | `https://registry.npmjs.org/@effect/ai-openai-compat/-/ai-openai-compat-4.0.0-rc.112.tgz` | +| npm integrity | `sha512-bfNYHgfjhzKhD7E1j1g2wPqAIucH6xiFylpT7YGVjF8SuF4i7TY5iLzfHp9Hr1RvF8fwiSGHt9nvnzrixGOkG9YZw==` | +| Tarball SHA-256 | `add1fb7a94bfcb8cd1e16ce2f8ba40296bba7d6eab55b9b230af3e3e53d12489` | +| Imported at | `2026-09-03` | +| Imported inputs | `src/**`, `README.md`, and `LICENSE` | +| License | MIT; copied to [`LICENSE`](./LICENSE) | + +This initial import preserves upstream provider behavior. Its Effect service/config keys use the +`@humanlayer/effect-ai-openai-compat` namespace, so upstream and forked layers cannot satisfy one another accidentally +in the same Effect context. It is vendored with the OpenAI and Anthropic providers so Fold and Riptide use one +HumanLayer-owned provider family. + +[`UPSTREAM.sha256`](./UPSTREAM.sha256) records the checksum of each unmodified imported provider source and metadata +file. Its regression test also verifies the deliberate HumanLayer service-key delta. + +## Refresh rule + +Refresh from a released npm package or an explicit immutable upstream commit that has been verified against the +supported `effect` peer runtime. Update this table and review the full source diff; do not sync from a moving branch +reference. diff --git a/packages/effect-ai-openai-compat/UPSTREAM.sha256 b/packages/effect-ai-openai-compat/UPSTREAM.sha256 new file mode 100644 index 0000000..d079aa5 --- /dev/null +++ b/packages/effect-ai-openai-compat/UPSTREAM.sha256 @@ -0,0 +1,6 @@ +774c3bc5924ad8ae6c5a75f1c53db13feb238ade15989625c513d07b60dedf30 LICENSE +7679c41fbb174be989187819f03e8e2ca96bae7e53d237445d534904ba610840 src/index.ts +c2c89a577e793ae7c9f337497fc76166bb3ef0a1745ed945d1260876c09814bb src/internal/errors.ts +ae0e49c772a58d474a9b07498f7e46f895f56da35b02c5c076901a7724bd8c38 src/internal/utilities.ts +a74a18141785d1db63fde9010bba4fbb12d6fc0d9948c3e57c4df460dfe6abea src/OpenAiError.ts +1cd5cecd963395d5f12f721481ea7b4bdc37b2f63ba1ff85a82e52fe4b155dbc src/OpenAiTelemetry.ts diff --git a/packages/effect-ai-openai-compat/package.json b/packages/effect-ai-openai-compat/package.json new file mode 100644 index 0000000..4b27ed2 --- /dev/null +++ b/packages/effect-ai-openai-compat/package.json @@ -0,0 +1,37 @@ +{ + "name": "@humanlayer/effect-ai-openai-compat", + "version": "0.0.0", + "private": true, + "license": "MIT", + "type": "module", + "description": "HumanLayer's vendored OpenAI-compatible provider for Effect AI SDK", + "sideEffects": [], + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./dist/index.d.ts", + "import": "./src/index.ts", + "default": "./src/index.ts" + }, + "./*": { + "types": "./dist/*.d.ts", + "import": "./src/*.ts", + "default": "./src/*.ts" + }, + "./internal/*": null, + "./index": null, + "./*/index": null + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun vitest run test/UpstreamParity.test.ts" + }, + "peerDependencies": { + "effect": "catalog:" + }, + "devDependencies": { + "@effect/vitest": "catalog:", + "@humanlayer/fold-vitest-config": "workspace:*", + "effect": "catalog:" + } +} diff --git a/packages/effect-ai-openai-compat/src/OpenAiClient.ts b/packages/effect-ai-openai-compat/src/OpenAiClient.ts new file mode 100644 index 0000000..0f83229 --- /dev/null +++ b/packages/effect-ai-openai-compat/src/OpenAiClient.ts @@ -0,0 +1,1250 @@ +/** + * The `OpenAiClient` module provides an Effect service for OpenAI-compatible + * chat completions and embeddings APIs. It builds on the Effect HTTP client, + * adds authentication and OpenAI organization or project headers, and exposes + * typed helpers for non-streaming chat completions, streaming chat completions, + * and embedding requests. + * + * @since 4.0.0 + */ +import * as Array from "effect/Array" +import type * as Config from "effect/Config" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { identity } from "effect/Function" +import * as Layer from "effect/Layer" +import * as Redacted from "effect/Redacted" +import * as Schema from "effect/Schema" +import * as Stream from "effect/Stream" +import type * as AiError from "effect/unstable/ai/AiError" +import * as Sse from "effect/unstable/encoding/Sse" +import * as Headers from "effect/unstable/http/Headers" +import * as HttpClient from "effect/unstable/http/HttpClient" +import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import * as Errors from "./internal/errors.ts" +import { OpenAiConfig } from "./OpenAiConfig.ts" + +/** + * Effect service interface for OpenAI-compatible chat completions and embeddings. + * + * **Details** + * + * Exposes the configured HTTP client plus helpers for non-streaming chat + * completions, streaming chat completions, and embeddings. Transport and + * schema decoding failures are mapped to `AiError`. + * + * @category services + * @since 4.0.0 + */ +export interface Service { + readonly client: HttpClient.HttpClient + readonly createResponse: ( + options: CreateResponseRequestJson + ) => Effect.Effect< + [body: CreateResponse200, response: HttpClientResponse.HttpClientResponse], + AiError.AiError + > + readonly createResponseStream: ( + options: Omit + ) => Effect.Effect< + [ + response: HttpClientResponse.HttpClientResponse, + stream: Stream.Stream + ], + AiError.AiError + > + readonly createEmbedding: ( + options: CreateEmbeddingRequestJson + ) => Effect.Effect +} + +/** + * Service tag for the OpenAI-compatible chat completions and embeddings client. + * + * **When to use** + * + * Use when building effects that depend on the low-level OpenAI-compatible + * client through context rather than receiving the client as a value. + * + * **Details** + * + * The tagged service is the `Service` interface produced by `make` and provided + * by `layer` or `layerConfig`. + * + * @see {@link Service} for the operations provided by the service + * @see {@link make} for constructing the service from explicit options + * @see {@link layer} for providing the service from explicit options + * @see {@link layerConfig} for loading client settings from `Config` + * + * @category services + * @since 4.0.0 + */ +export class OpenAiClient extends Context.Service()( + "@humanlayer/effect-ai-openai-compat/OpenAiClient" +) {} + +/** + * Configuration options used to construct an OpenAI-compatible client. + * + * @category options + * @since 4.0.0 + */ +export type Options = { + readonly apiKey?: Redacted.Redacted | undefined + readonly apiUrl?: string | undefined + readonly organizationId?: Redacted.Redacted | undefined + readonly projectId?: Redacted.Redacted | undefined + readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined +} + +const RedactedOpenAiHeaders = { + OpenAiOrganization: "openai-organization", + OpenAiProject: "openai-project" +} + +const withRedactedHeaders = Effect.updateService( + Headers.CurrentRedactedNames, + Array.appendAll(Object.values(RedactedOpenAiHeaders)) +) + +/** + * Constructs an OpenAI-compatible client service from explicit options. + * + * **When to use** + * + * Use when you need the OpenAI-compatible client service value inside an effect. + * + * **Details** + * + * The returned service uses the current `HttpClient`, prepends `apiUrl` or + * `https://api.openai.com/v1`, adds authentication and OpenAI + * organization/project headers, accepts JSON responses, and applies + * `transformClient` when provided. + * + * **Gotchas** + * + * A scoped `OpenAiConfig.withClientTransform` is applied when request helpers + * run, after the `transformClient` option supplied to `make`. + * + * @see {@link layer} for providing this client from explicit options + * @see {@link layerConfig} for loading client settings from `Config` + * + * @category constructors + * @since 4.0.0 + */ +export const make = Effect.fnUntraced( + function*(options: Options): Effect.fn.Return { + const baseClient = yield* HttpClient.HttpClient + + const httpClient = baseClient.pipe( + HttpClient.mapRequest((request) => + request.pipe( + HttpClientRequest.prependUrl(options.apiUrl ?? "https://api.openai.com/v1"), + options.apiKey !== undefined + ? HttpClientRequest.bearerToken(Redacted.value(options.apiKey)) + : identity, + options.organizationId !== undefined + ? HttpClientRequest.setHeader( + RedactedOpenAiHeaders.OpenAiOrganization, + Redacted.value(options.organizationId) + ) + : identity, + options.projectId !== undefined + ? HttpClientRequest.setHeader( + RedactedOpenAiHeaders.OpenAiProject, + Redacted.value(options.projectId) + ) + : identity, + HttpClientRequest.acceptJson + ) + ), + options.transformClient !== undefined + ? options.transformClient + : identity + ) + + const resolveHttpClient = Effect.map( + OpenAiConfig.getOrUndefined, + (config) => + config?.transformClient !== undefined + ? config.transformClient(httpClient) + : httpClient + ) + + const decodeResponse = HttpClientResponse.schemaBodyJson(ChatCompletionResponse) + + const createResponse = ( + payload: CreateResponseRequestJson + ): Effect.Effect< + [body: CreateResponse200, response: HttpClientResponse.HttpClientResponse], + AiError.AiError + > => + resolveHttpClient.pipe( + Effect.flatMap((client) => + HttpClientRequest.post("/chat/completions").pipe( + HttpClientRequest.bodyJsonUnsafe(payload), + HttpClient.filterStatusOk(client).execute, + Effect.flatMap((response) => + Effect.map(decodeResponse(response), ( + body + ): [CreateResponse200, HttpClientResponse.HttpClientResponse] => [ + body, + response + ]) + ), + Effect.catchTags({ + HttpClientError: (error) => Errors.mapHttpClientError(error, "createResponse"), + SchemaError: (error) => Effect.fail(Errors.mapSchemaError(error, "createResponse")) + }) + ) + ), + withRedactedHeaders + ) + + const buildResponseStream = ( + response: HttpClientResponse.HttpClientResponse + ): [ + HttpClientResponse.HttpClientResponse, + Stream.Stream + ] => { + const stream = response.stream.pipe( + Stream.decodeText(), + Stream.pipeThroughChannel(Sse.decode()), + Stream.flatMap((event) => { + const data = decodeChatCompletionSseData(event.data) + return Stream.fromIterable(data !== undefined ? [data] : []) + }), + Stream.takeUntil((event) => event === "[DONE]"), + Stream.catchTags({ + Retry: (error) => Stream.die(error), + SseError: (error) => Stream.fail(Errors.mapSseError(error, "createResponseStream")), + HttpClientError: (error) => Stream.fromEffect(Errors.mapHttpClientError(error, "createResponseStream")) + }) + ) as any + return [response, stream] + } + + const createResponseStream: Service["createResponseStream"] = (payload) => + resolveHttpClient.pipe( + Effect.flatMap((client) => + HttpClientRequest.post("/chat/completions").pipe( + HttpClientRequest.bodyJsonUnsafe({ + ...payload, + stream: true, + stream_options: { + include_usage: true + } + }), + HttpClient.filterStatusOk(client).execute, + Effect.map(buildResponseStream), + Effect.catchTag( + "HttpClientError", + (error) => Errors.mapHttpClientError(error, "createResponseStream") + ) + ) + ), + withRedactedHeaders + ) + + const decodeEmbedding = HttpClientResponse.schemaBodyJson(CreateEmbeddingResponseSchema) + + const createEmbedding = ( + payload: CreateEmbeddingRequestJson + ): Effect.Effect => + resolveHttpClient.pipe( + Effect.flatMap((client) => + HttpClientRequest.post("/embeddings").pipe( + HttpClientRequest.bodyJsonUnsafe(payload), + HttpClient.filterStatusOk(client).execute, + Effect.flatMap(decodeEmbedding), + Effect.catchTags({ + HttpClientError: (error) => Errors.mapHttpClientError(error, "createEmbedding"), + SchemaError: (error) => Effect.fail(Errors.mapSchemaError(error, "createEmbedding")) + }) + ) + ), + withRedactedHeaders + ) + + return OpenAiClient.of({ + client: httpClient, + createResponse, + createResponseStream, + createEmbedding + }) + }, + withRedactedHeaders +) + +/** + * Creates a layer that provides an OpenAI-compatible client from explicit options. + * + * **When to use** + * + * Use to install `OpenAiClient` in an application layer when the client options + * are already available as values rather than loaded from `Config`. + * + * @see {@link make} for constructing the client service effectfully + * @see {@link layerConfig} for loading client settings from `Config` + * + * @category layers + * @since 4.0.0 + */ +export const layer = (options: Options): Layer.Layer => + Layer.effect(OpenAiClient, make(options)) + +/** + * Creates a layer that loads OpenAI-compatible client settings from `Config` + * values before constructing the service. + * + * **When to use** + * + * Use when you need client settings for OpenAI-compatible APIs to be read from + * Effect `Config` values while providing `OpenAiClient` as a layer. + * + * **Details** + * + * Only config values supplied in `options` are loaded. Omitted fields are + * passed to `make` as `undefined`, and `transformClient` is forwarded as a + * plain option. + * + * @see {@link make} for constructing the client service effectfully + * @see {@link layer} for providing the client from already-resolved options + * + * @category layers + * @since 4.0.0 + */ +export const layerConfig = (options?: { + readonly apiKey?: Config.Config | undefined> | undefined + readonly apiUrl?: Config.Config | undefined + readonly organizationId?: Config.Config | undefined> | undefined + readonly projectId?: Config.Config | undefined> | undefined + readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined +}): Layer.Layer => + Layer.effect( + OpenAiClient, + Effect.gen(function*() { + const apiKey = options?.apiKey !== undefined + ? yield* options.apiKey : + undefined + const apiUrl = options?.apiUrl !== undefined + ? yield* options.apiUrl : + undefined + const organizationId = options?.organizationId !== undefined + ? yield* options.organizationId + : undefined + const projectId = options?.projectId !== undefined + ? yield* options.projectId : + undefined + return yield* make({ + apiKey, + apiUrl, + organizationId, + projectId, + transformClient: options?.transformClient + }) + }) + ) + +type JsonObject = { readonly [x: string]: Schema.Json } + +/** + * Optional response fields that can be requested with the `include` parameter. + * + * @category models + * @since 4.0.0 + */ +export type IncludeEnum = + | "message.input_image.image_url" + | "reasoning.encrypted_content" + | "message.output_text.logprobs" + +/** + * Lifecycle status shared by message, reasoning, and tool-call items. + * + * @category models + * @since 4.0.0 + */ +export type MessageStatus = "in_progress" | "completed" | "incomplete" + +type InputTextContent = { + readonly type: "input_text" + readonly text: string +} + +type InputImageContent = { + readonly type: "input_image" + readonly image_url?: string | null | undefined + readonly file_id?: string | null | undefined + readonly detail?: "low" | "high" | "auto" | null | undefined +} + +type InputFileContent = { + readonly type: "input_file" + readonly file_id?: string | null | undefined + readonly filename?: string | undefined + readonly file_url?: string | undefined + readonly file_data?: string | undefined +} + +/** + * Content blocks accepted in input messages. + * + * @category models + * @since 4.0.0 + */ +export type InputContent = InputTextContent | InputImageContent | InputFileContent + +/** + * Text content block used for model-provided reasoning summaries. + * + * @category models + * @since 4.0.0 + */ +export type SummaryTextContent = { + readonly type: "summary_text" + readonly text: string +} + +type ReasoningTextContent = { + readonly type: "reasoning_text" + readonly text: string +} + +type RefusalContent = { + readonly type: "refusal" + readonly refusal: string +} + +type TextContent = { + readonly type: "text" + readonly text: string +} + +type ComputerScreenshotContent = { + readonly type: "computer_screenshot" + readonly image_url: string | null + readonly file_id: string | null +} + +type FileCitationAnnotation = { + readonly type: "file_citation" + readonly file_id: string + readonly index: number + readonly filename: string +} + +type UrlCitationAnnotation = { + readonly type: "url_citation" + readonly url: string + readonly start_index: number + readonly end_index: number + readonly title: string +} + +type ContainerFileCitationAnnotation = { + readonly type: "container_file_citation" + readonly container_id: string + readonly file_id: string + readonly start_index: number + readonly end_index: number + readonly filename: string +} + +type FilePathAnnotation = { + readonly type: "file_path" + readonly file_id: string + readonly index: number +} + +/** + * Citation and file-path annotations attached to output text content. + * + * @category models + * @since 4.0.0 + */ +export type Annotation = + | FileCitationAnnotation + | UrlCitationAnnotation + | ContainerFileCitationAnnotation + | FilePathAnnotation + +type OutputTextContent = { + readonly type: "output_text" + readonly text: string + readonly annotations?: ReadonlyArray | undefined + readonly logprobs?: ReadonlyArray | undefined +} + +type OutputMessageContent = + | InputTextContent + | OutputTextContent + | TextContent + | SummaryTextContent + | ReasoningTextContent + | RefusalContent + | InputImageContent + | ComputerScreenshotContent + | InputFileContent + +type OutputMessage = { + readonly id: string + readonly type: "message" + readonly role: "assistant" + readonly content: ReadonlyArray + readonly status: MessageStatus +} + +/** + * Reasoning output item containing encrypted reasoning content, summaries, and + * optional reasoning text. + * + * @category models + * @since 4.0.0 + */ +export type ReasoningItem = { + readonly type: "reasoning" + readonly id: string + readonly encrypted_content?: string | null | undefined + readonly summary: ReadonlyArray + readonly content?: ReadonlyArray | undefined + readonly status?: MessageStatus | undefined +} + +type FunctionCall = { + readonly id?: string | undefined + readonly type: "function_call" + readonly call_id: string + readonly name: string + readonly arguments: string + readonly status?: MessageStatus | undefined +} + +type FunctionCallOutput = { + readonly id?: string | null | undefined + readonly call_id: string + readonly type: "function_call_output" + readonly output: string | ReadonlyArray + readonly status?: MessageStatus | null | undefined +} + +type CustomToolCall = { + readonly type: "custom_tool_call" + readonly id?: string | undefined + readonly call_id: string + readonly name: string + readonly input: string +} + +type CustomToolCallOutput = { + readonly type: "custom_tool_call_output" + readonly id?: string | undefined + readonly call_id: string + readonly output: string | ReadonlyArray +} + +type ItemReference = { + readonly type?: "item_reference" | null | undefined + readonly id: string +} + +/** + * Item shapes accepted by a Responses-style `input` field. + * + * **Details** + * + * Supports input messages, output messages, tool calls, tool outputs, reasoning + * items, custom tool interactions, and item references. + * + * @category models + * @since 4.0.0 + */ +export type InputItem = + | { + readonly role: "user" | "assistant" | "system" | "developer" + readonly content: string | ReadonlyArray + readonly type?: "message" | undefined + } + | { + readonly type?: "message" | undefined + readonly role: "user" | "system" | "developer" + readonly status?: MessageStatus | undefined + readonly content: ReadonlyArray + } + | OutputMessage + | FunctionCall + | FunctionCallOutput + | ReasoningItem + | CustomToolCallOutput + | CustomToolCall + | ItemReference + +type FunctionTool = { + readonly type: "function" + readonly name: string + readonly description?: string | null | undefined + readonly parameters?: JsonObject | null | undefined + readonly strict?: boolean | null | undefined +} + +type CustomToolParam = { + readonly type: "custom" + readonly name: string + readonly description?: string | undefined + readonly format?: unknown +} + +/** + * Tool definitions that can be supplied to a Responses-style request. + * + * @category models + * @since 4.0.0 + */ +export type Tool = + | FunctionTool + | CustomToolParam + +type ToolChoice = + | "none" + | "auto" + | "required" + | { + readonly type: "allowed_tools" + readonly mode: "auto" | "required" + readonly tools: ReadonlyArray + } + | { + readonly type: "function" + readonly name: string + } + | { + readonly type: "custom" + readonly name: string + } + +/** + * Text output format configuration for plain text, JSON object, or JSON Schema + * responses. + * + * @category configuration + * @since 4.0.0 + */ +export type TextResponseFormatConfiguration = + | { + readonly type: "text" + } + | { + readonly type: "json_schema" + readonly description?: string | undefined + readonly name: string + readonly schema: JsonObject + readonly strict?: boolean | null | undefined + } + | { + readonly type: "json_object" + } + +/** + * Request options for creating a Responses-style response with an + * OpenAI-compatible provider. + * + * @category models + * @since 4.0.0 + */ +export type CreateResponse = { + readonly metadata?: Readonly> | null | undefined + readonly top_logprobs?: number | undefined + readonly temperature?: number | null | undefined + readonly top_p?: number | null | undefined + readonly user?: string | null | undefined + readonly safety_identifier?: string | null | undefined + readonly prompt_cache_key?: string | null | undefined + readonly service_tier?: string | undefined + readonly prompt_cache_retention?: "in-memory" | "24h" | null | undefined + readonly previous_response_id?: string | null | undefined + readonly model?: string | undefined + readonly reasoning?: unknown + readonly background?: boolean | null | undefined + readonly max_output_tokens?: number | null | undefined + readonly max_tool_calls?: number | null | undefined + readonly text?: { + readonly format?: TextResponseFormatConfiguration | undefined + readonly verbosity?: "low" | "medium" | "high" | null | undefined + } | undefined + readonly tools?: ReadonlyArray | undefined + readonly tool_choice?: ToolChoice | undefined + readonly truncation?: "auto" | "disabled" | null | undefined + readonly input?: string | ReadonlyArray | undefined + readonly include?: ReadonlyArray | null | undefined + readonly parallel_tool_calls?: boolean | null | undefined + readonly store?: boolean | null | undefined + readonly instructions?: string | null | undefined + readonly stream?: boolean | null | undefined + readonly conversation?: string | null | undefined + readonly modalities?: ReadonlyArray<"text" | "audio"> | undefined + readonly seed?: number | undefined +} + +/** + * Token accounting reported on Responses-style response objects. + * + * @category models + * @since 4.0.0 + */ +export type ResponseUsage = { + readonly input_tokens: number + readonly output_tokens: number + readonly total_tokens: number + readonly input_tokens_details?: unknown + readonly output_tokens_details?: unknown +} + +type OutputItem = + | OutputMessage + | FunctionCall + | ReasoningItem + | CustomToolCall + +/** + * Responses-style response object returned by compatible providers or embedded + * in response stream lifecycle events. + * + * @category models + * @since 4.0.0 + */ +export type Response = { + readonly id: string + readonly object?: "response" | undefined + readonly model: string + readonly status?: "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete" | undefined + readonly created_at: number + readonly output: ReadonlyArray + readonly usage?: ResponseUsage | null | undefined + readonly incomplete_details?: + | { + readonly reason?: "max_output_tokens" | "content_filter" | undefined + } + | null + | undefined + readonly service_tier?: string | undefined +} + +type ResponseCreatedEvent = { + readonly type: "response.created" + readonly response: Response + readonly sequence_number: number +} + +type ResponseCompletedEvent = { + readonly type: "response.completed" + readonly response: Response + readonly sequence_number: number +} + +type ResponseIncompleteEvent = { + readonly type: "response.incomplete" + readonly response: Response + readonly sequence_number: number +} + +type ResponseFailedEvent = { + readonly type: "response.failed" + readonly response: Response + readonly sequence_number: number +} + +type ResponseOutputItemAddedEvent = { + readonly type: "response.output_item.added" + readonly output_index: number + readonly sequence_number: number + readonly item: OutputItem +} + +type ResponseOutputItemDoneEvent = { + readonly type: "response.output_item.done" + readonly output_index: number + readonly sequence_number: number + readonly item: OutputItem +} + +type ResponseTextDeltaEvent = { + readonly type: "response.output_text.delta" + readonly item_id: string + readonly output_index: number + readonly content_index: number + readonly delta: string + readonly sequence_number: number + readonly logprobs?: ReadonlyArray | undefined +} + +type ResponseOutputTextAnnotationAddedEvent = { + readonly type: "response.output_text.annotation.added" + readonly item_id: string + readonly output_index: number + readonly content_index: number + readonly annotation_index: number + readonly sequence_number: number + readonly annotation: Annotation +} + +type ResponseFunctionCallArgumentsDeltaEvent = { + readonly type: "response.function_call_arguments.delta" + readonly item_id: string + readonly output_index: number + readonly sequence_number: number + readonly delta: string +} + +type ResponseReasoningSummaryPartAddedEvent = { + readonly type: "response.reasoning_summary_part.added" + readonly item_id: string + readonly output_index: number + readonly summary_index: number + readonly sequence_number: number + readonly part: SummaryTextContent +} + +type ResponseReasoningSummaryPartDoneEvent = { + readonly type: "response.reasoning_summary_part.done" + readonly item_id: string + readonly output_index: number + readonly summary_index: number + readonly sequence_number: number + readonly part: SummaryTextContent +} + +type ResponseReasoningSummaryTextDeltaEvent = { + readonly type: "response.reasoning_summary_text.delta" + readonly item_id: string + readonly output_index: number + readonly summary_index: number + readonly delta: string + readonly sequence_number: number +} + +type ResponseErrorEvent = { + readonly type: "error" + readonly code: string | null + readonly message: string + readonly param: string | null + readonly sequence_number: number +} + +type UnknownResponseStreamEvent = { + readonly type: string + readonly [key: string]: unknown +} + +/** + * Server-sent event shapes emitted by Responses-style response streams. + * + * @category streaming + * @since 4.0.0 + */ +export type ResponseStreamEvent = + | ResponseCreatedEvent + | ResponseCompletedEvent + | ResponseIncompleteEvent + | ResponseFailedEvent + | ResponseOutputItemAddedEvent + | ResponseOutputItemDoneEvent + | ResponseTextDeltaEvent + | ResponseOutputTextAnnotationAddedEvent + | ResponseFunctionCallArgumentsDeltaEvent + | ResponseReasoningSummaryPartAddedEvent + | ResponseReasoningSummaryPartDoneEvent + | ResponseReasoningSummaryTextDeltaEvent + | ResponseErrorEvent + | UnknownResponseStreamEvent + +/** + * Represents one embedding item returned by an OpenAI-compatible embeddings API. + * + * **Details** + * + * The embedding can be returned either as a numeric vector or as a base64-encoded + * string. The `index` field identifies the input item that produced this + * embedding. + * + * @category models + * @since 4.0.0 + */ +export type Embedding = { + readonly embedding: ReadonlyArray | string + readonly index: number + readonly object?: string | undefined +} + +/** + * Request payload for the embeddings endpoint. + * + * @category models + * @since 4.0.0 + */ +export type CreateEmbeddingRequest = { + readonly input: string | ReadonlyArray | ReadonlyArray | ReadonlyArray> + readonly model: string + readonly encoding_format?: "float" | "base64" | undefined + readonly dimensions?: number | undefined + readonly user?: string | undefined +} + +/** + * Successful response payload returned by the embeddings endpoint. + * + * @category models + * @since 4.0.0 + */ +export type CreateEmbeddingResponse = { + readonly data: ReadonlyArray + readonly model: string + readonly object?: "list" | undefined + readonly usage?: { + readonly prompt_tokens: number + readonly total_tokens: number + } | undefined +} + +/** + * JSON request body accepted by the embeddings endpoint. + * + * @category models + * @since 4.0.0 + */ +export type CreateEmbeddingRequestJson = CreateEmbeddingRequest +/** + * Decoded successful embeddings response body. + * + * @category models + * @since 4.0.0 + */ +export type CreateEmbedding200 = CreateEmbeddingResponse +/** + * Structured content parts accepted in chat completion messages. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionContentPart = + | { + readonly type: "text" + readonly text: string + } + | { + readonly type: "image_url" + readonly image_url: { + readonly url: string + readonly detail?: "low" | "high" | "auto" | undefined + } + } +/** + * Tool call data attached to an assistant chat completion message. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionRequestToolCall = { + readonly id: string + readonly type: "function" + readonly function: { + readonly name: string + readonly arguments: string + } +} +/** + * Message shapes accepted by the chat completions endpoint. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionRequestMessage = + | { + readonly role: "system" | "developer" | "user" | "assistant" + readonly content: string | ReadonlyArray | null + readonly tool_calls?: ReadonlyArray | undefined + } + | { + readonly role: "tool" + readonly tool_call_id: string + readonly content: string + } +/** + * Function tool definition accepted by the chat completions endpoint. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionTool = { + readonly type: "function" + readonly function: { + readonly name: string + readonly description?: string | null | undefined + readonly parameters?: JsonObject | undefined + readonly strict?: boolean | undefined + } +} +/** + * Controls whether the model may call tools and can force a specific function. + * + * @category configuration + * @since 4.0.0 + */ +export type ChatCompletionToolChoice = + | "none" + | "auto" + | "required" + | { + readonly type: "function" + readonly function: { + readonly name: string + } + } +/** + * JSON response format configuration for chat completion requests. + * + * @category configuration + * @since 4.0.0 + */ +export type ChatCompletionResponseFormat = + | { + readonly type: "json_object" + } + | { + readonly type: "json_schema" + readonly json_schema: { + readonly name: string + readonly schema: JsonObject + readonly description?: string | undefined + readonly strict?: boolean | undefined + } + } +/** + * Request payload for the OpenAI-compatible chat completions endpoint. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionRequest = { + readonly model: string + readonly messages: ReadonlyArray + readonly temperature?: number | null | undefined + readonly top_p?: number | null | undefined + readonly max_tokens?: number | null | undefined + readonly user?: string | null | undefined + readonly seed?: number | undefined + readonly parallel_tool_calls?: boolean | null | undefined + readonly response_format?: ChatCompletionResponseFormat | undefined + readonly tools?: ReadonlyArray | undefined + readonly tool_choice?: ChatCompletionToolChoice | undefined + readonly service_tier?: string | undefined + readonly reasoning?: unknown + readonly stream?: boolean | undefined + readonly stream_options?: { + readonly include_usage?: boolean | undefined + } | undefined + readonly [x: string]: unknown +} +/** + * JSON request body used by this client when creating a chat completion response. + * + * @category models + * @since 4.0.0 + */ +export type CreateResponseRequestJson = ChatCompletionRequest +/** + * Decoded successful chat completion response body returned by `createResponse`. + * + * @category models + * @since 4.0.0 + */ +export type CreateResponse200 = ChatCompletionResponse +/** + * Decoded server-sent event payload emitted by `createResponseStream`. + * + * @category streaming + * @since 4.0.0 + */ +export type CreateResponse200Sse = ChatCompletionStreamEvent + +const EmbeddingSchema = Schema.Struct({ + embedding: Schema.Union([Schema.Array(Schema.Finite), Schema.String]), + index: Schema.Int, + object: Schema.optionalKey(Schema.String) +}) + +const CreateEmbeddingResponseSchema = Schema.Struct({ + data: Schema.Array(EmbeddingSchema), + model: Schema.String, + object: Schema.optionalKey(Schema.Literal("list")), + usage: Schema.optionalKey(Schema.Struct({ + prompt_tokens: Schema.Int, + total_tokens: Schema.Int + })) +}) + +const ChatCompletionToolFunction = Schema.Struct({ + name: Schema.String, + arguments: Schema.optionalKey(Schema.String) +}) + +const ChatCompletionToolFunctionDelta = Schema.Struct({ + // Some OpenAI-compatible providers (e.g. Fireworks) send `name: null` on + // streamed tool-call continuation fragments. `name` must be nullable, else + // the whole chunk fails validation and its argument delta is dropped. + name: Schema.optionalKey(Schema.NullOr(Schema.String)), + arguments: Schema.optionalKey(Schema.String) +}) + +const ChatCompletionToolCall = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + index: Schema.optionalKey(Schema.Int), + type: Schema.optionalKey(Schema.String), + function: Schema.optionalKey(ChatCompletionToolFunction) +}) + +const ChatCompletionToolCallDelta = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + index: Schema.optionalKey(Schema.Int), + type: Schema.optionalKey(Schema.String), + function: Schema.optionalKey(ChatCompletionToolFunctionDelta) +}) + +const ChatCompletionMessage = Schema.Struct({ + role: Schema.optionalKey(Schema.String), + content: Schema.optionalKey(Schema.NullOr(Schema.String)), + reasoning: Schema.optionalKey(Schema.NullOr(Schema.String)), + reasoning_content: Schema.optionalKey(Schema.NullOr(Schema.String)), + tool_calls: Schema.optionalKey(Schema.Array(ChatCompletionToolCall)) +}) + +const ChatCompletionDelta = Schema.Struct({ + role: Schema.optionalKey(Schema.String), + content: Schema.optionalKey(Schema.NullOr(Schema.String)), + reasoning: Schema.optionalKey(Schema.NullOr(Schema.String)), + reasoning_content: Schema.optionalKey(Schema.NullOr(Schema.String)), + // Some OpenAI-compatible providers send `tool_calls: null` when a streamed + // chunk contains only text. Accepting null keeps the text-bearing chunk from + // being classified as an unknown event. + tool_calls: Schema.optionalKey(Schema.NullOr(Schema.Array(ChatCompletionToolCallDelta))) +}) + +const ChatCompletionChoice = Schema.Struct({ + index: Schema.Int, + finish_reason: Schema.optionalKey(Schema.NullOr(Schema.String)), + message: Schema.optionalKey(ChatCompletionMessage), + delta: Schema.optionalKey(ChatCompletionDelta) +}) + +const ChatCompletionUsage = Schema.Struct({ + prompt_tokens: Schema.Int, + completion_tokens: Schema.Int, + total_tokens: Schema.Int, + prompt_tokens_details: Schema.optionalKey(Schema.Any), + completion_tokens_details: Schema.optionalKey(Schema.Any) +}) + +const ChatCompletionResponse = Schema.Struct({ + id: Schema.String, + model: Schema.String, + created: Schema.Int, + choices: Schema.Array(ChatCompletionChoice), + usage: Schema.optionalKey(Schema.NullOr(ChatCompletionUsage)), + service_tier: Schema.optionalKey(Schema.String) +}) + +const ChatCompletionChunk = Schema.Struct({ + id: Schema.String, + model: Schema.String, + created: Schema.Int, + choices: Schema.Array(ChatCompletionChoice), + usage: Schema.optionalKey(Schema.NullOr(ChatCompletionUsage)), + service_tier: Schema.optionalKey(Schema.String) +}) + +/** + * Decoded tool-call object from a chat completion response or streaming chunk. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionToolCall = typeof ChatCompletionToolCall.Type +/** + * Decoded message object from a non-streaming chat completion choice. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionMessage = typeof ChatCompletionMessage.Type +/** + * Decoded choice object returned by chat completion responses and chunks. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionChoice = typeof ChatCompletionChoice.Type +/** + * Decoded token usage summary returned by chat completions. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionUsage = typeof ChatCompletionUsage.Type +/** + * Decoded successful response from the chat completions endpoint. + * + * @category models + * @since 4.0.0 + */ +export type ChatCompletionResponse = typeof ChatCompletionResponse.Type +/** + * Decoded streaming chunk emitted by the chat completions endpoint. + * + * @category streaming + * @since 4.0.0 + */ +export type ChatCompletionChunk = typeof ChatCompletionChunk.Type +/** + * A parsed chat completion event that does not match the expected chunk schema. + * + * @category streaming + * @since 4.0.0 + */ +export interface UnknownChatCompletionEvent { + readonly _tag: "UnknownChatCompletionEvent" + readonly data: unknown +} +/** + * Streaming chat completion event, including decoded chunks, unknown parsed + * events, and the `[DONE]` sentinel. + * + * @category streaming + * @since 4.0.0 + */ +export type ChatCompletionStreamEvent = ChatCompletionChunk | UnknownChatCompletionEvent | "[DONE]" + +const parseJson = (value: string): unknown => { + try { + return JSON.parse(value) + } catch { + return undefined + } +} + +const isChatCompletionChunk = Schema.is(ChatCompletionChunk) + +const decodeChatCompletionSseData = ( + data: string +): ChatCompletionStreamEvent | undefined => { + if (data === "[DONE]") { + return data + } + const parsed = parseJson(data) + if (parsed === undefined) { + return undefined + } + return isChatCompletionChunk(parsed) ? parsed : { + _tag: "UnknownChatCompletionEvent", + data: parsed + } +} diff --git a/packages/effect-ai-openai-compat/src/OpenAiConfig.ts b/packages/effect-ai-openai-compat/src/OpenAiConfig.ts new file mode 100644 index 0000000..0392b38 --- /dev/null +++ b/packages/effect-ai-openai-compat/src/OpenAiConfig.ts @@ -0,0 +1,122 @@ +/** + * The `OpenAiConfig` module lets a workflow temporarily customize the HTTP + * client used by OpenAI-compatible request helpers. Model, embedding, and + * tool-calling code can use this scoped configuration to add middleware, + * instrumentation, or routing without rebuilding the client layer. + * + * @since 4.0.0 + */ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { dual } from "effect/Function" +import type { HttpClient } from "effect/unstable/http/HttpClient" + +/** + * Context service for OpenAI-compatible client configuration in the current + * Effect scope. + * + * **When to use** + * + * Use as the context service for scoped OpenAI-compatible client configuration + * and HTTP client transforms. + * + * @see {@link withClientTransform} for scoping an HTTP client transformation + * + * @category services + * @since 4.0.0 + */ +export class OpenAiConfig extends Context.Service< + OpenAiConfig, + OpenAiConfig.Service +>()("@humanlayer/effect-ai-openai-compat/OpenAiConfig") { + /** + * Gets the configured OpenAI-compatible service from the current context when present. + * + * @since 4.0.0 + */ + static readonly getOrUndefined: Effect.Effect = Effect.map( + Effect.context(), + Context.getOrUndefined(OpenAiConfig) + ) +} + +/** + * Types associated with the `OpenAiConfig` context service. + * + * @since 4.0.0 + */ +export declare namespace OpenAiConfig { + /** + * Configuration consumed by OpenAI-compatible clients when they build or + * resolve the underlying HTTP client. + * + * @category services + * @since 4.0.0 + */ + export interface Service { + readonly transformClient?: ((client: HttpClient) => HttpClient) | undefined + } +} + +/** + * Provides an HTTP client transform for the supplied effect. + * + * **When to use** + * + * Use to add provider-specific OpenAI-compatible HTTP behavior, such as + * headers, retries, instrumentation, or proxy routing. + * + * **Details** + * + * OpenAI-compatible provider services read the transform from the + * `OpenAiConfig` context. + * + * @category configuration + * @since 4.0.0 + */ +export const withClientTransform: { + /** + * Provides an HTTP client transform for the supplied effect. + * + * **When to use** + * + * Use to add provider-specific OpenAI-compatible HTTP behavior, such as + * headers, retries, instrumentation, or proxy routing. + * + * **Details** + * + * OpenAI-compatible provider services read the transform from the + * `OpenAiConfig` context. + * + * @category configuration + * @since 4.0.0 + */ + (transform: (client: HttpClient) => HttpClient): (self: Effect.Effect) => Effect.Effect + /** + * Provides an HTTP client transform for the supplied effect. + * + * **When to use** + * + * Use to add provider-specific OpenAI-compatible HTTP behavior, such as + * headers, retries, instrumentation, or proxy routing. + * + * **Details** + * + * OpenAI-compatible provider services read the transform from the + * `OpenAiConfig` context. + * + * @category configuration + * @since 4.0.0 + */ + ( + self: Effect.Effect, + transform: (client: HttpClient) => HttpClient + ): Effect.Effect +} = dual(2, ( + self: Effect.Effect, + transformClient: (client: HttpClient) => HttpClient +) => + Effect.flatMap( + OpenAiConfig.getOrUndefined, + (config) => Effect.provideService(self, OpenAiConfig, { ...config, transformClient }) + )) diff --git a/packages/effect-ai-openai-compat/src/OpenAiEmbeddingModel.ts b/packages/effect-ai-openai-compat/src/OpenAiEmbeddingModel.ts new file mode 100644 index 0000000..130f1dd --- /dev/null +++ b/packages/effect-ai-openai-compat/src/OpenAiEmbeddingModel.ts @@ -0,0 +1,321 @@ +/** + * The `OpenAiEmbeddingModel` module adapts OpenAI-compatible embeddings + * endpoints to Effect's embedding model service. It sends embedding requests + * through {@link OpenAiClient}, exposes constructors for layers and `AiModel` + * values, supports scoped request configuration overrides, and checks that the + * provider returns one numeric vector for each requested input. + * + * @since 4.0.0 + */ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { dual } from "effect/Function" +import * as Layer from "effect/Layer" +import type { Simplify } from "effect/Types" +import * as AiError from "effect/unstable/ai/AiError" +import * as EmbeddingModel from "effect/unstable/ai/EmbeddingModel" +import * as AiModel from "effect/unstable/ai/Model" +import type { CreateEmbedding200, CreateEmbeddingRequestJson } from "./OpenAiClient.ts" +import { OpenAiClient } from "./OpenAiClient.ts" + +/** + * A model identifier accepted by an OpenAI-compatible embeddings endpoint. + * + * @category models + * @since 4.0.0 + */ +export type Model = string + +type ConfigOptions = Simplify>> +type ModelConfig = Omit & { readonly [x: string]: unknown } + +/** + * Context service for OpenAI embedding model configuration. + * + * **When to use** + * + * Use when you need to provide shared default request options for + * OpenAI-compatible embedding operations through the Effect context, such as + * `dimensions`, `encoding_format`, or `user`. + * + * **Details** + * + * The service stores the embedding request payload without `input`. Requests + * combine the selected model, layer or constructor config, and scoped context + * config, with scoped context config taking precedence. + * + * @see {@link withConfigOverride} for scoping embedding request overrides + * + * @category services + * @since 4.0.0 + */ +export class Config extends Context.Service< + Config, + ConfigOptions & { readonly [x: string]: unknown } +>()("@humanlayer/effect-ai-openai-compat/OpenAiEmbeddingModel/Config") {} + +/** + * Creates an `AiModel` for an OpenAI-compatible embedding model with its configured vector dimensions. + * + * **When to use** + * + * Use to provide an OpenAI-compatible `EmbeddingModel` and its `Dimensions` + * service to an Effect program. + * + * @see {@link layer} for providing only the embedding model service + * @see {@link withConfigOverride} for scoped request configuration overrides + * + * @category constructors + * @since 4.0.0 + */ +export const model = ( + model: string, + options: Omit & { + readonly dimensions: number + readonly [x: string]: unknown + } +): AiModel.Model<"openai", EmbeddingModel.EmbeddingModel | EmbeddingModel.Dimensions, OpenAiClient> => + AiModel.make( + "openai", + model, + Layer.merge( + layer({ + model, + config: options + }), + Layer.succeed(EmbeddingModel.Dimensions, options.dimensions) + ) + ) + +/** + * Creates an OpenAI-compatible embedding model service backed by `OpenAiClient`. + * + * **When to use** + * + * Use when you need to build or provide an `EmbeddingModel` service directly + * from an existing `OpenAiClient`. + * + * **Details** + * + * The service sends embedding requests through `OpenAiClient.createEmbedding`. + * Request config is merged as the selected model, constructor config, then + * scoped `Config`, so scoped overrides take precedence. Provider usage + * `prompt_tokens` is exposed as `usage.inputTokens`. + * + * **Gotchas** + * + * Provider responses must contain one numeric vector for every requested input + * with unique, in-range `index` values; otherwise embedding operations fail with + * `AiError.InvalidOutputError`. + * + * @see {@link model} for the higher-level `AiModel` descriptor that also provides `EmbeddingModel.Dimensions` + * @see {@link layer} for providing the service as a `Layer` + * @see {@link withConfigOverride} for scoping embedding request overrides + * + * @category constructors + * @since 4.0.0 + */ +export const make = Effect.fnUntraced(function*({ model, config: providerConfig }: { + readonly model: string + readonly config?: ModelConfig | undefined +}): Effect.fn.Return { + const client = yield* OpenAiClient + + const makeConfig = Effect.contextWith((services: Context.Context) => + Effect.succeed({ model, ...providerConfig, ...Context.getOrUndefined(services, Config) }) + ) + + return yield* EmbeddingModel.make({ + embedMany: Effect.fnUntraced(function*({ inputs }) { + const config = yield* makeConfig + const response = yield* client.createEmbedding({ ...config, input: inputs }) + return yield* mapProviderResponse(inputs.length, response) + }) + }) +}) + +/** + * Creates a layer for an OpenAI-compatible embedding model service. + * + * **When to use** + * + * Use when composing application layers and you want an OpenAI-compatible + * embeddings endpoint to satisfy `EmbeddingModel.EmbeddingModel` while + * supplying `OpenAiClient` from another layer. + * + * @see {@link make} for constructing the embedding model service effectfully + * @see {@link model} for creating an `AiModel` with configured dimensions + * + * @category layers + * @since 4.0.0 + */ +export const layer = (options: { + readonly model: string + readonly config?: ModelConfig | undefined +}): Layer.Layer => + Layer.effect(EmbeddingModel.EmbeddingModel, make(options)) + +/** + * Provides scoped request config overrides for OpenAI-compatible embedding model operations. + * + * **When to use** + * + * Use to apply embedding request options to one effect without changing the + * model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available OpenAI-compatible embedding request configuration fields + * + * @category configuration + * @since 4.0.0 + */ +export const withConfigOverride: { + /** + * Provides scoped request config overrides for OpenAI-compatible embedding model operations. + * + * **When to use** + * + * Use to apply embedding request options to one effect without changing the + * model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available OpenAI-compatible embedding request configuration fields + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service): (self: Effect.Effect) => Effect.Effect> + /** + * Provides scoped request config overrides for OpenAI-compatible embedding model operations. + * + * **When to use** + * + * Use to apply embedding request options to one effect without changing the + * model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available OpenAI-compatible embedding request configuration fields + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service): Effect.Effect> +} = dual< + /** + * Provides scoped request config overrides for OpenAI-compatible embedding model operations. + * + * **When to use** + * + * Use to apply embedding request options to one effect without changing the + * model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available OpenAI-compatible embedding request configuration fields + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service) => (self: Effect.Effect) => Effect.Effect>, + /** + * Provides scoped request config overrides for OpenAI-compatible embedding model operations. + * + * **When to use** + * + * Use to apply embedding request options to one effect without changing the + * model's default configuration. + * + * **Details** + * + * The overrides are merged with any existing `Config` service for the duration + * of the supplied effect. Fields in `overrides` take precedence over existing + * config, and the helper supports both `effect.pipe(withConfigOverride(overrides))` + * and `withConfigOverride(effect, overrides)`. + * + * @see {@link Config} for available OpenAI-compatible embedding request configuration fields + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service) => Effect.Effect> +>(2, (self, overrides) => + Effect.flatMap( + Effect.serviceOption(Config), + (config) => + Effect.provideService(self, Config, { + ...(config._tag === "Some" ? config.value : {}), + ...overrides + }) + )) + +const mapProviderResponse = ( + inputLength: number, + response: CreateEmbedding200 +): Effect.Effect => { + if (response.data.length !== inputLength) { + return Effect.fail( + invalidOutput(`Provider returned ${response.data.length} embeddings but expected ${inputLength}`) + ) + } + + const results = new Array>(inputLength) + const seen = new Set() + + for (const entry of response.data) { + if (!Number.isInteger(entry.index) || entry.index < 0 || entry.index >= inputLength) { + return Effect.fail(invalidOutput(`Provider returned invalid embedding index: ${entry.index}`)) + } + if (seen.has(entry.index)) { + return Effect.fail(invalidOutput(`Provider returned duplicate embedding index: ${entry.index}`)) + } + if (!Array.isArray(entry.embedding)) { + return Effect.fail(invalidOutput(`Provider returned non-vector embedding at index ${entry.index}`)) + } + + seen.add(entry.index) + results[entry.index] = [...entry.embedding] + } + + if (seen.size !== inputLength) { + return Effect.fail( + invalidOutput(`Provider returned embeddings for ${seen.size} inputs but expected ${inputLength}`) + ) + } + + return Effect.succeed({ + results, + usage: { + inputTokens: response.usage?.prompt_tokens + } + }) +} + +const invalidOutput = (description: string): AiError.AiError => + AiError.make({ + module: "OpenAiEmbeddingModel", + method: "embedMany", + reason: new AiError.InvalidOutputError({ description }) + }) diff --git a/packages/effect-ai-openai-compat/src/OpenAiError.ts b/packages/effect-ai-openai-compat/src/OpenAiError.ts new file mode 100644 index 0000000..88ba2dd --- /dev/null +++ b/packages/effect-ai-openai-compat/src/OpenAiError.ts @@ -0,0 +1,178 @@ +/** + * The `OpenAiError` module defines OpenAI-specific metadata that can be + * attached to the shared `AiError` error types used by the AI packages. It is + * primarily used by OpenAI-compatible clients to preserve provider details + * such as error codes, error types, request IDs, and rate limit headers while + * still exposing errors through the provider-neutral Effect AI error model. + * + * Use this module when mapping OpenAI API failures into `AiError` values and + * when consumers need enough structured metadata to debug failed requests, + * inspect quota or rate limit responses, or correlate an error with OpenAI + * support. The exported types are metadata shapes only; the module augmentation + * makes those shapes available on the corresponding shared AI error metadata + * interfaces without defining new runtime error classes. + * + * @since 4.0.0 + */ + +/** + * OpenAI-specific error metadata fields. + * + * @category models + * @since 4.0.0 + */ +export type OpenAiErrorMetadata = { + /** + * The OpenAI error code returned by the API. + */ + readonly errorCode: string | null + /** + * The OpenAI error type returned by the API. + */ + readonly errorType: string | null + /** + * The unique request ID for debugging with OpenAI support. + */ + readonly requestId: string | null +} + +/** + * OpenAI-specific rate limit metadata fields. + * + * **Details** + * + * Extends base error metadata with rate limit specific information from + * OpenAI's rate limit headers. + * + * @category models + * @since 4.0.0 + */ +export type OpenAiRateLimitMetadata = OpenAiErrorMetadata & { + /** + * The rate limit type (e.g. "requests", "tokens"). + */ + readonly limit: string | null + /** + * Number of remaining requests in the current window. + */ + readonly remaining: number | null + /** + * Time until the request rate limit resets. + */ + readonly resetRequests: string | null + /** + * Time until the token rate limit resets. + */ + readonly resetTokens: string | null +} + +declare module "effect/unstable/ai/AiError" { + /** + * Metadata attached to rate limit errors returned by OpenAI-compatible APIs. + * + * @category models + * @since 4.0.0 + */ + export interface RateLimitErrorMetadata { + readonly openai?: OpenAiRateLimitMetadata | null + } + + /** + * Metadata attached when an OpenAI-compatible provider reports that quota or + * billing limits have been exhausted. + * + * @category models + * @since 4.0.0 + */ + export interface QuotaExhaustedErrorMetadata { + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * Metadata attached to authentication failures from OpenAI-compatible APIs, + * such as invalid, missing, or unauthorized API credentials. + * + * @category models + * @since 4.0.0 + */ + export interface AuthenticationErrorMetadata { + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * Metadata attached when an OpenAI-compatible provider rejects content because + * it violates a safety or usage policy. + * + * @category models + * @since 4.0.0 + */ + export interface ContentPolicyErrorMetadata { + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * Metadata attached to malformed or unsupported requests rejected by an + * OpenAI-compatible API before model execution. + * + * @category models + * @since 4.0.0 + */ + export interface InvalidRequestErrorMetadata { + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * Metadata attached to unexpected server-side failures reported by an + * OpenAI-compatible provider. + * + * @category models + * @since 4.0.0 + */ + export interface InternalProviderErrorMetadata { + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * Metadata attached when an OpenAI-compatible response cannot be converted + * into the expected AI package output shape. + * + * @category models + * @since 4.0.0 + */ + export interface InvalidOutputErrorMetadata { + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * Metadata attached when an OpenAI-compatible structured output response does + * not satisfy the requested schema or parsing constraints. + * + * @category models + * @since 4.0.0 + */ + export interface StructuredOutputErrorMetadata { + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * Metadata attached when an OpenAI-compatible provider cannot support the + * schema supplied for structured output or tool definitions. + * + * @category models + * @since 4.0.0 + */ + export interface UnsupportedSchemaErrorMetadata { + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * Metadata attached when an OpenAI-compatible error response cannot be mapped + * to a more specific shared AI error category. + * + * @category models + * @since 4.0.0 + */ + export interface UnknownErrorMetadata { + readonly openai?: OpenAiErrorMetadata | null + } +} diff --git a/packages/effect-ai-openai-compat/src/OpenAiLanguageModel.ts b/packages/effect-ai-openai-compat/src/OpenAiLanguageModel.ts new file mode 100644 index 0000000..1c5a2fd --- /dev/null +++ b/packages/effect-ai-openai-compat/src/OpenAiLanguageModel.ts @@ -0,0 +1,2105 @@ +/** + * The `OpenAiLanguageModel` module adapts OpenAI-compatible chat completions + * providers to Effect AI's `LanguageModel` service. It builds a model service + * from a model id, translates prompts, files, tools, structured output schemas, + * and provider-specific options into `OpenAiClient` requests, and maps normal + * or streaming chat completion results back into Effect AI response content and + * metadata. + * + * @since 4.0.0 + */ +import * as Context from "effect/Context" +import * as DateTime from "effect/DateTime" +import * as Effect from "effect/Effect" +import * as Encoding from "effect/Encoding" +import { dual } from "effect/Function" +import * as Layer from "effect/Layer" +import * as Option from "effect/Option" +import * as Predicate from "effect/Predicate" +import * as Rec from "effect/Record" +import * as Redactable from "effect/Redactable" +import * as Schema from "effect/Schema" +import * as AST from "effect/SchemaAST" +import * as SchemaIssue from "effect/SchemaIssue" +import * as Stream from "effect/Stream" +import type { Span } from "effect/Tracer" +import type { DeepMutable, Simplify } from "effect/Types" +import * as AiError from "effect/unstable/ai/AiError" +import * as LanguageModel from "effect/unstable/ai/LanguageModel" +import * as AiModel from "effect/unstable/ai/Model" +import { toCodecOpenAI } from "effect/unstable/ai/OpenAiStructuredOutput" +import type * as Prompt from "effect/unstable/ai/Prompt" +import type * as Response from "effect/unstable/ai/Response" +import * as Tool from "effect/unstable/ai/Tool" +import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import * as InternalUtilities from "./internal/utilities.ts" +import { + type Annotation, + type ChatCompletionContentPart, + type ChatCompletionRequestToolCall, + type CreateResponse, + type CreateResponse200, + type CreateResponse200Sse, + type CreateResponseRequestJson, + type IncludeEnum, + type InputContent, + type InputItem, + type MessageStatus, + OpenAiClient, + type ReasoningItem, + type SummaryTextContent, + type TextResponseFormatConfiguration, + type Tool as OpenAiClientTool, + type UnknownChatCompletionEvent +} from "./OpenAiClient.ts" +import { addGenAIAnnotations } from "./OpenAiTelemetry.ts" + +const formatIssue = SchemaIssue.makeFormatterDefault() + +/** + * Image detail level for vision requests. + */ +type ImageDetail = "auto" | "low" | "high" + +// ============================================================================= +// Configuration +// ============================================================================= + +type ConfigOptions = Simplify< + & Partial< + Omit + > + & { + /** + * File ID prefixes used to identify file IDs in Responses API. + * When undefined, all file data is treated as base64 content. + * + * Examples: + * - OpenAI: ['file-'] for IDs like 'file-abc123' + * - Azure OpenAI: ['assistant-'] for IDs like 'assistant-abc123' + */ + readonly fileIdPrefixes?: ReadonlyArray | undefined + /** + * Configuration options for a text response from the model. + */ + readonly text?: { + /** + * Constrains the verbosity of the model's response. Lower values will + * result in more concise responses, while higher values will result in + * more verbose responses. + * + * Defaults to `"medium"`. + */ + readonly verbosity?: "low" | "medium" | "high" | undefined + } | undefined + /** + * Whether to use strict JSON schema validation. + * + * Defaults to `true`. + */ + readonly strictJsonSchema?: boolean | undefined + } +> +type ModelConfig = Omit & { readonly [x: string]: unknown } + +/** + * Context service for OpenAI language model configuration. + * + * **When to use** + * + * Use as the context service for OpenAI-compatible language model request + * configuration, especially when a scoped operation should override the defaults + * supplied to `model`, `make`, or `layer`. + * + * @see {@link withConfigOverride} for scoping language model request overrides + * + * @category services + * @since 4.0.0 + */ +export class Config extends Context.Service< + Config, + ConfigOptions & { readonly [x: string]: unknown } +>()("@humanlayer/effect-ai-openai-compat/OpenAiLanguageModel/Config") {} + +// ============================================================================= +// Provider Options / Metadata +// ============================================================================= + +declare module "effect/unstable/ai/Prompt" { + /** + * OpenAI-compatible options for file prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface FilePartOptions extends ProviderOptions { + /** + * Provider-specific file options for OpenAI-compatible APIs. + */ + readonly openai?: { + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. + */ + readonly imageDetail?: ImageDetail | null + } | null + } + + /** + * OpenAI-compatible options for reasoning prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningPartOptions extends ProviderOptions { + /** + * Provider-specific reasoning options for OpenAI-compatible APIs. + */ + readonly openai?: { + /** + * The ID of the item to reference. + */ + readonly itemId?: string | null + /** + * The encrypted content of the reasoning item - populated when a response + * is generated with `reasoning.encrypted_content` in the `include` + * parameter. + */ + readonly encryptedContent?: string | null + } | null + } + + /** + * OpenAI-compatible options for assistant tool-call prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface ToolCallPartOptions extends ProviderOptions { + /** + * Provider-specific tool-call options for OpenAI-compatible APIs. + */ + readonly openai?: { + /** + * The ID of the item to reference. + */ + readonly itemId?: string | null + /** + * The status to send for the tool-call item. + */ + readonly status?: MessageStatus | null + } | null + } + + /** + * OpenAI-compatible options for tool-result prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface ToolResultPartOptions extends ProviderOptions { + /** + * Provider-specific tool-result options for OpenAI-compatible APIs. + */ + readonly openai?: { + /** + * The ID of the item to reference. + */ + readonly itemId?: string | null + /** + * The status to send for the tool-result item. + */ + readonly status?: MessageStatus | null + } | null + } + + /** + * OpenAI-compatible options for text prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface TextPartOptions extends ProviderOptions { + /** + * Provider-specific text options for OpenAI-compatible APIs. + */ + readonly openai?: { + /** + * The ID of the item to reference. + */ + readonly itemId?: string | null + /** + * The status to send for the text item. + */ + readonly status?: MessageStatus | null + /** + * A list of annotations that apply to the output text. + */ + readonly annotations?: ReadonlyArray | null + } | null + } +} + +declare module "effect/unstable/ai/Response" { + /** + * OpenAI-compatible metadata attached to a complete text response part. + * + * @category models + * @since 4.0.0 + */ + export interface TextPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the text part. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the text part. + */ + readonly itemId?: string | null + /** + * If the model emits a refusal content part, the refusal explanation + * from the model will be contained in the metadata of an empty text + * part. + */ + readonly refusal?: string | null + /** + * The status returned for the text item. + */ + readonly status?: MessageStatus | null + /** + * The text content part annotations. + */ + readonly annotations?: ReadonlyArray | null + } + } + + /** + * OpenAI-compatible metadata emitted when a streamed text part starts. + * + * @category models + * @since 4.0.0 + */ + export interface TextStartPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed text start. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the streamed text part. + */ + readonly itemId?: string | null + } | null + } + + /** + * OpenAI-compatible metadata emitted when a streamed text part ends. + * + * @category models + * @since 4.0.0 + */ + export interface TextEndPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed text end. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the streamed text part. + */ + readonly itemId?: string | null + /** + * The annotations collected for the completed streamed text part. + */ + readonly annotations?: ReadonlyArray | null + } | null + } + + /** + * OpenAI-compatible metadata attached to a complete reasoning response part. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the reasoning part. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the reasoning part. + */ + readonly itemId?: string | null + /** + * Encrypted reasoning content that can be sent back in later requests. + */ + readonly encryptedContent?: string | null + } | null + } + + /** + * OpenAI-compatible metadata emitted when a streamed reasoning part starts. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningStartPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed reasoning start. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the reasoning part. + */ + readonly itemId?: string | null + /** + * Encrypted reasoning content that can be sent back in later requests. + */ + readonly encryptedContent?: string | null + } | null + } + + /** + * OpenAI-compatible metadata emitted for a streamed reasoning delta. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningDeltaPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed reasoning delta. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the reasoning part. + */ + readonly itemId?: string | null + } | null + } + + /** + * OpenAI-compatible metadata emitted when a streamed reasoning part ends. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningEndPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed reasoning end. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the reasoning part. + */ + readonly itemId?: string | null + /** + * Encrypted reasoning content that can be sent back in later requests. + */ + readonly encryptedContent?: string + } | null + } + + /** + * OpenAI-compatible metadata attached to tool-call response parts. + * + * @category models + * @since 4.0.0 + */ + export interface ToolCallPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the tool call. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the tool call. + */ + readonly itemId?: string | null + } | null + } + + /** + * OpenAI-compatible metadata attached to document source citations. + * + * @category models + * @since 4.0.0 + */ + export interface DocumentSourcePartMetadata extends ProviderMetadata { + /** + * Provider-specific citation metadata for OpenAI-compatible APIs. + */ + readonly openai?: + | { + /** + * Identifies a citation to an uploaded file. + */ + readonly type: "file_citation" + /** + * The index of the file in the list of files. + */ + readonly index: number + /** + * The ID of the file. + */ + readonly fileId: string + } + | { + /** + * Identifies a citation to a generated file path. + */ + readonly type: "file_path" + /** + * The index of the file in the list of files. + */ + readonly index: number + /** + * The ID of the file. + */ + readonly fileId: string + } + | { + /** + * Identifies a citation to a file inside a container. + */ + readonly type: "container_file_citation" + /** + * The ID of the file. + */ + readonly fileId: string + /** + * The ID of the container file. + */ + readonly containerId: string + } + | null + } + + /** + * OpenAI-compatible metadata attached to URL source citations. + * + * @category models + * @since 4.0.0 + */ + export interface UrlSourcePartMetadata extends ProviderMetadata { + /** + * Provider-specific URL citation metadata for OpenAI-compatible APIs. + */ + readonly openai?: { + /** + * Identifies a citation to a URL. + */ + readonly type: "url_citation" + /** + * The index of the first character of the URL citation in the message. + */ + readonly startIndex: number + /** + * The index of the last character of the URL citation in the message. + */ + readonly endIndex: number + } | null + } + + /** + * OpenAI-compatible metadata attached to finish response parts. + * + * @category models + * @since 4.0.0 + */ + export interface FinishPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned when generation finishes. + */ + readonly openai?: { + /** + * The service tier reported by the OpenAI-compatible provider. + */ + readonly serviceTier?: "default" | "auto" | "flex" | "scale" | "priority" | null + } | null + } +} + +// ============================================================================= +// Language Model +// ============================================================================= + +/** + * Creates an OpenAI-compatible model descriptor that can be provided with `Effect.provide`. + * + * **When to use** + * + * Use when you want an OpenAI-compatible language model value that carries + * provider and model metadata and can be supplied directly to an Effect program. + * + * @see {@link layer} for creating a `LanguageModel.LanguageModel` layer directly + * @see {@link make} for constructing the language model service effectfully + * + * @category constructors + * @since 4.0.0 + */ +export const model = ( + model: string, + config?: ModelConfig +): AiModel.Model<"openai", LanguageModel.LanguageModel, OpenAiClient> => + AiModel.make("openai", model, layer({ model, config })) + +// TODO +// /** +// * @since 4.0.0 +// * @category constructors +// */ +// export const modelWithTokenizer = ( +// model: string, +// config?: Omit +// ): AiModel.Model<"openai", LanguageModel.LanguageModel | Tokenizer.Tokenizer, OpenAiClient> => +// AiModel.make("openai", model, layerWithTokenizer({ model, config })) + +/** + * Creates an OpenAI-compatible `LanguageModel` service from a model identifier and optional request defaults. + * + * **When to use** + * + * Use to construct an OpenAI-compatible chat-completions language model service + * backed by `OpenAiClient`. + * + * **Details** + * + * The returned effect requires `OpenAiClient`. Request defaults from the + * `config` option are merged with any `Config` service in the context, with + * context values taking precedence. The service supports both `generateText` and + * `streamText`. + * + * @see {@link layer} for providing the service as a `Layer` + * @see {@link model} for creating a model descriptor for `AiModel.provide` + * + * @category constructors + * @since 4.0.0 + */ +export const make = Effect.fnUntraced(function*({ model, config: providerConfig }: { + readonly model: string + readonly config?: ModelConfig | undefined +}): Effect.fn.Return { + const client = yield* OpenAiClient + + const makeConfig = Effect.contextWith((services: Context.Context) => + Effect.succeed({ model, ...providerConfig, ...Context.getOrUndefined(services, Config) }) + ) + + const makeRequest = Effect.fnUntraced( + function*>({ config, options, toolNameMapper }: { + readonly config: typeof Config.Service + readonly options: LanguageModel.ProviderOptions + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return { + const include = new Set() + const capabilities = getModelCapabilities(config.model!) + const messages = yield* prepareMessages({ + config, + options, + capabilities, + include, + toolNameMapper + }) + const { toolChoice, tools } = yield* prepareTools({ + config, + options, + toolNameMapper + }) + const responseFormat = yield* prepareResponseFormat({ + config, + options + }) + const { fileIdPrefixes: _fip, strictJsonSchema: _sjs, ...apiConfig } = config + const request: CreateResponse = { + ...apiConfig, + input: messages, + include: include.size > 0 ? Array.from(include) : null, + text: { + verbosity: config.text?.verbosity ?? null, + format: responseFormat + }, + ...(tools !== undefined ? { tools } : undefined), + ...(toolChoice !== undefined ? { tool_choice: toolChoice } : undefined) + } + return toChatCompletionsRequest(request) + } + ) + + return yield* LanguageModel.make({ + codecTransformer: toCodecOpenAI, + generateText: Effect.fnUntraced( + function*(options) { + const config = yield* makeConfig + const toolNameMapper = new Tool.NameMapper(options.tools) + const request = yield* makeRequest({ config, options, toolNameMapper }) + annotateRequest(options.span, request) + const [rawResponse, response] = yield* client.createResponse(request) + annotateResponse(options.span, rawResponse) + return yield* makeResponse({ + options, + rawResponse, + response, + toolNameMapper + }) + } + ), + streamText: Effect.fnUntraced( + function*(options) { + const config = yield* makeConfig + const toolNameMapper = new Tool.NameMapper(options.tools) + const request = yield* makeRequest({ config, options, toolNameMapper }) + annotateRequest(options.span, request) + const [response, stream] = yield* client.createResponseStream(request) + return yield* makeStreamResponse({ + options, + stream, + response, + toolNameMapper + }) + }, + (effect, options) => + effect.pipe( + Stream.unwrap, + Stream.map((response) => { + annotateStreamResponse(options.span, response) + return response + }) + ) + ) + }) +}) + +/** + * Creates a layer for the OpenAI-compatible language model. + * + * **When to use** + * + * Use when composing application layers and you want OpenAI-compatible APIs to + * satisfy `LanguageModel.LanguageModel` while supplying `OpenAiClient` from + * another layer. + * + * @see {@link make} for constructing the language model service effectfully + * @see {@link model} for creating an AI model descriptor + * + * @category layers + * @since 4.0.0 + */ +export const layer = (options: { + readonly model: string + readonly config?: ModelConfig | undefined +}): Layer.Layer => + Layer.effect(LanguageModel.LanguageModel, make(options)) + +/** + * Provides scoped config overrides for OpenAI-compatible language model operations. + * + * **When to use** + * + * Use to override request configuration for a single language model effect + * without changing the defaults supplied to `model`, `make`, or `layer`. + * + * **Details** + * + * Existing `Config` values from the Effect context are merged with `overrides`, + * and the override values take precedence. + * + * @see {@link Config} for the configuration shape + * + * @category configuration + * @since 4.0.0 + */ +export const withConfigOverride: { + /** + * Provides scoped config overrides for OpenAI-compatible language model operations. + * + * **When to use** + * + * Use to override request configuration for a single language model effect + * without changing the defaults supplied to `model`, `make`, or `layer`. + * + * **Details** + * + * Existing `Config` values from the Effect context are merged with `overrides`, + * and the override values take precedence. + * + * @see {@link Config} for the configuration shape + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service): (self: Effect.Effect) => Effect.Effect> + /** + * Provides scoped config overrides for OpenAI-compatible language model operations. + * + * **When to use** + * + * Use to override request configuration for a single language model effect + * without changing the defaults supplied to `model`, `make`, or `layer`. + * + * **Details** + * + * Existing `Config` values from the Effect context are merged with `overrides`, + * and the override values take precedence. + * + * @see {@link Config} for the configuration shape + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service): Effect.Effect> +} = dual< + /** + * Provides scoped config overrides for OpenAI-compatible language model operations. + * + * **When to use** + * + * Use to override request configuration for a single language model effect + * without changing the defaults supplied to `model`, `make`, or `layer`. + * + * **Details** + * + * Existing `Config` values from the Effect context are merged with `overrides`, + * and the override values take precedence. + * + * @see {@link Config} for the configuration shape + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service) => (self: Effect.Effect) => Effect.Effect>, + /** + * Provides scoped config overrides for OpenAI-compatible language model operations. + * + * **When to use** + * + * Use to override request configuration for a single language model effect + * without changing the defaults supplied to `model`, `make`, or `layer`. + * + * **Details** + * + * Existing `Config` values from the Effect context are merged with `overrides`, + * and the override values take precedence. + * + * @see {@link Config} for the configuration shape + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service) => Effect.Effect> +>(2, (self, overrides) => + Effect.flatMap( + Effect.serviceOption(Config), + (config) => + Effect.provideService(self, Config, { + ...(config._tag === "Some" ? config.value : {}), + ...overrides + }) + )) + +// ============================================================================= +// Prompt Conversion +// ============================================================================= + +const getSystemMessageMode = (model: string): "system" | "developer" => + model.startsWith("o") || + model.startsWith("gpt-5") || + model.startsWith("codex-") || + model.startsWith("computer-use") + ? "developer" + : "system" + +const prepareMessages = Effect.fnUntraced( + function*>({ + config, + options, + capabilities, + include, + toolNameMapper + }: { + readonly config: typeof Config.Service + readonly options: LanguageModel.ProviderOptions + readonly include: Set + readonly capabilities: ModelCapabilities + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return, AiError.AiError> { + const hasConversation = Predicate.isNotNullish(config.conversation) + + // Handle Included Features + if (config.top_logprobs !== undefined) { + include.add("message.output_text.logprobs") + } + if (config.store === false && capabilities.isReasoningModel) { + include.add("reasoning.encrypted_content") + } + + const messages: Array = [] + + for (const message of options.prompt.content) { + switch (message.role) { + case "system": { + messages.push({ + role: getSystemMessageMode(config.model!), + content: message.content + }) + break + } + + case "user": { + const content: Array = [] + + for (let index = 0; index < message.content.length; index++) { + const part = message.content[index] + + switch (part.type) { + case "text": { + content.push({ type: "input_text", text: part.text }) + break + } + + case "file": { + if (part.mediaType.startsWith("image/")) { + const detail = getImageDetail(part) + const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType + + if (typeof part.data === "string" && isFileId(part.data, config)) { + content.push({ type: "input_image", file_id: part.data, detail }) + } + + if (part.data instanceof URL) { + content.push({ type: "input_image", image_url: part.data.toString(), detail }) + } + + if (part.data instanceof Uint8Array) { + const base64 = Encoding.encodeBase64(part.data) + const imageUrl = `data:${mediaType};base64,${base64}` + content.push({ type: "input_image", image_url: imageUrl, detail }) + } + } else if (part.mediaType === "application/pdf") { + if (typeof part.data === "string" && isFileId(part.data, config)) { + content.push({ type: "input_file", file_id: part.data }) + } + + if (part.data instanceof URL) { + content.push({ type: "input_file", file_url: part.data.toString() }) + } + + if (part.data instanceof Uint8Array) { + const base64 = Encoding.encodeBase64(part.data) + const fileName = part.fileName ?? `part-${index}.pdf` + const fileData = `data:application/pdf;base64,${base64}` + content.push({ type: "input_file", filename: fileName, file_data: fileData }) + } + } else { + return yield* AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareMessages", + reason: new AiError.InvalidRequestError({ + description: `Detected unsupported media type for file: '${part.mediaType}'` + }) + }) + } + } + } + } + + messages.push({ role: "user", content }) + + break + } + + case "assistant": { + const reasoningMessages: Record> = Object.create(null) + + for (const part of message.content) { + switch (part.type) { + case "text": { + const id = getItemId(part) + + // When in conversation mode, skip items that already exist in the + // conversation context to avoid "Duplicate item found" errors + if (hasConversation && Predicate.isNotNull(id)) { + break + } + + if (config.store === true && Predicate.isNotNull(id)) { + messages.push({ type: "item_reference", id }) + break + } + + messages.push({ + id: id!, + type: "message", + role: "assistant", + status: part.options.openai?.status ?? "completed", + content: [{ + type: "output_text", + text: part.text, + annotations: part.options.openai?.annotations ?? [], + logprobs: [] + }] + }) + + break + } + + case "reasoning": { + const id = getItemId(part) + const encryptedContent = getEncryptedContent(part) + + if (hasConversation && Predicate.isNotNull(id)) { + break + } + + if (Predicate.isNotNull(id)) { + const message = reasoningMessages[id] + + if (config.store === true) { + // Use item references to refer to reasoning (single reference) + // when the first part is encountered + if (Predicate.isUndefined(message)) { + messages.push({ type: "item_reference", id }) + + // Store unused reasoning message to mark its id as used + reasoningMessages[id] = { + type: "reasoning", + id, + summary: [] + } + } + } else { + const summaryParts: Array = [] + + if (part.text.length > 0) { + summaryParts.push({ type: "summary_text", text: part.text }) + } + + if (Predicate.isUndefined(message)) { + reasoningMessages[id] = { + type: "reasoning", + id, + summary: summaryParts, + encrypted_content: encryptedContent ?? null + } + + messages.push(reasoningMessages[id]) + } else { + message.summary.push(...summaryParts) + + // Update encrypted content to enable setting it in the + // last summary part + if (Predicate.isNotNull(encryptedContent)) { + message.encrypted_content = encryptedContent + } + } + } + } + + break + } + + case "tool-call": { + const id = getItemId(part) + const status = getStatus(part) + + if (hasConversation && Predicate.isNotNull(id)) { + break + } + + if (config.store && Predicate.isNotNull(id)) { + messages.push({ type: "item_reference", id }) + break + } + + if (part.providerExecuted) { + break + } + + const toolName = toolNameMapper.getProviderName(part.name) + + messages.push({ + type: "function_call", + name: toolName, + call_id: part.id, + arguments: JSON.stringify(part.params), + ...(Predicate.isNotNull(id) ? { id } : {}), + ...(Predicate.isNotNull(status) ? { status } : {}) + }) + + break + } + + // Assistant tool-result parts are always provider executed + case "tool-result": { + // Skip execution denied results - these have no corresponding + // item in OpenAI's store + if ( + Predicate.hasProperty(part.result, "type") && + part.result.type === "execution-denied" + ) { + break + } + + if (hasConversation) { + break + } + + if (config.store === true) { + const id = getItemId(part) ?? part.id + messages.push({ type: "item_reference", id }) + } + } + } + } + + break + } + + case "tool": { + for (const part of message.content) { + if (part.type === "tool-approval-response") { + continue + } + + const status = getStatus(part) + + messages.push({ + type: "function_call_output", + call_id: part.id, + output: typeof part.result === "string" ? part.result : JSON.stringify(part.result), + ...(Predicate.isNotNull(status) ? { status } : {}) + }) + } + + break + } + } + } + + return messages + } +) + +// ============================================================================= +// HTTP Details +// ============================================================================= + +const buildHttpRequestDetails = ( + request: HttpClientRequest.HttpClientRequest +): typeof Response.HttpRequestDetails.Type => ({ + method: request.method, + url: request.url, + urlParams: Array.from(request.urlParams), + hash: Option.getOrUndefined(request.hash), + headers: Redactable.redact(request.headers) as Record +}) + +const buildHttpResponseDetails = ( + response: HttpClientResponse.HttpClientResponse +): typeof Response.HttpResponseDetails.Type => ({ + status: response.status, + headers: Redactable.redact(response.headers) as Record +}) + +// ============================================================================= +// Response Conversion +// ============================================================================= + +type ResponseStreamEvent = CreateResponse200Sse + +const isUnknownChatCompletionEvent = ( + event: ResponseStreamEvent +): event is UnknownChatCompletionEvent => + typeof event !== "string" && "_tag" in event && event._tag === "UnknownChatCompletionEvent" + +type ActiveToolCall = { + readonly id: string + name: string + arguments: string +} + +const makeResponse = Effect.fnUntraced( + function*>({ + options, + rawResponse, + response, + toolNameMapper + }: { + readonly options: LanguageModel.ProviderOptions + readonly rawResponse: CreateResponse200 + readonly response: HttpClientResponse.HttpClientResponse + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return< + Array, + AiError.AiError + > { + let hasToolCalls = false + const parts: Array = [] + + const createdAt = new Date(rawResponse.created * 1000) + parts.push({ + type: "response-metadata", + id: rawResponse.id, + modelId: rawResponse.model as string, + timestamp: DateTime.formatIso(DateTime.fromDateUnsafe(createdAt)), + request: buildHttpRequestDetails(response.request) + }) + + const choice = rawResponse.choices[0] + const message = choice?.message + + if (message !== undefined) { + const reasoning = message.reasoning ?? message.reasoning_content + if (Predicate.isNotNullish(reasoning) && reasoning.length > 0) { + parts.push({ type: "reasoning", text: reasoning }) + } + + if ( + message.content !== undefined && Predicate.isNotNull(message.content) && message.content.length > 0 + ) { + parts.push({ type: "text", text: message.content }) + } + + if (message.tool_calls !== undefined) { + for (const [index, toolCall] of message.tool_calls.entries()) { + const toolId = toolCall.id ?? `${rawResponse.id}_tool_${index}` + const toolName = toolNameMapper.getCustomName(toolCall.function?.name ?? "unknown_tool") + const toolParamsJson = toolCall.function?.arguments ?? "{}" + const toolParams = yield* Effect.try({ + try: () => Tool.unsafeSecureJsonParse(toolParamsJson), + catch: (cause) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "makeResponse", + reason: new AiError.ToolParameterValidationError({ + toolName, + toolParams: {}, + description: `Failed to securely JSON parse tool parameters: ${cause}` + }) + }) + }) + const params = yield* transformToolCallParams(options.tools, toolName, toolParams) + hasToolCalls = true + parts.push({ + type: "tool-call", + id: toolId, + name: toolName, + params, + metadata: { openai: { ...makeItemIdMetadata(toolCall.id) } } + }) + } + } + } + + const finishReason = InternalUtilities.resolveFinishReason( + choice?.finish_reason, + hasToolCalls + ) + const serviceTier = normalizeServiceTier(rawResponse.service_tier) + + parts.push({ + type: "finish", + reason: finishReason, + usage: getUsage(rawResponse.usage), + response: buildHttpResponseDetails(response), + ...(serviceTier !== undefined && { metadata: { openai: { serviceTier } } }) + }) + + return parts + } +) + +const makeStreamResponse = Effect.fnUntraced( + function*>({ + options, + stream, + response, + toolNameMapper + }: { + readonly options: LanguageModel.ProviderOptions + readonly stream: Stream.Stream + readonly response: HttpClientResponse.HttpClientResponse + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return< + Stream.Stream, + AiError.AiError + > { + let serviceTier: string | undefined = undefined + let usage: CreateResponse200["usage"] = undefined + let finishReason: string | null | undefined = undefined + let metadataEmitted = false + let textStarted = false + let textId = "" + let reasoningStarted = false + let reasoningId = "" + let hasToolCalls = false + const activeToolCalls: Record = {} + + return stream.pipe( + Stream.mapEffect(Effect.fnUntraced(function*(event) { + const parts: Array = [] + + if (event === "[DONE]") { + if (reasoningStarted) { + parts.push({ + type: "reasoning-end", + id: reasoningId, + metadata: { openai: { ...makeItemIdMetadata(reasoningId) } } + }) + } + + if (textStarted) { + parts.push({ + type: "text-end", + id: textId, + metadata: { openai: { ...makeItemIdMetadata(textId) } } + }) + } + + for (const toolCall of Object.values(activeToolCalls)) { + const toolParams = toolCall.arguments.length > 0 ? toolCall.arguments : "{}" + const parsedParams = yield* Effect.try({ + try: () => Tool.unsafeSecureJsonParse(toolParams), + catch: (cause) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "makeStreamResponse", + reason: new AiError.ToolParameterValidationError({ + toolName: toolCall.name, + toolParams: {}, + description: `Failed to securely JSON parse tool parameters: ${cause}` + }) + }) + }) + const params = yield* transformToolCallParams(options.tools, toolCall.name, parsedParams) + parts.push({ type: "tool-params-end", id: toolCall.id }) + parts.push({ + type: "tool-call", + id: toolCall.id, + name: toolCall.name, + params, + metadata: { openai: { ...makeItemIdMetadata(toolCall.id) } } + }) + hasToolCalls = true + } + + const normalizedServiceTier = normalizeServiceTier(serviceTier) + parts.push({ + type: "finish", + reason: InternalUtilities.resolveFinishReason(finishReason, hasToolCalls), + usage: getUsage(usage), + response: buildHttpResponseDetails(response), + ...(normalizedServiceTier !== undefined + ? { metadata: { openai: { serviceTier: normalizedServiceTier } } } + : undefined) + }) + return parts + } + + // Keep unknown events available to direct client consumers; this layer + // cannot translate provider-specific data into portable stream parts. + if (isUnknownChatCompletionEvent(event)) { + return parts + } + + if (event.service_tier !== undefined) { + serviceTier = event.service_tier + } + if (event.usage !== undefined && Predicate.isNotNull(event.usage)) { + usage = event.usage + } + + if (!metadataEmitted) { + metadataEmitted = true + textId = `${event.id}_message` + reasoningId = `${event.id}_reasoning` + parts.push({ + type: "response-metadata", + id: event.id, + modelId: event.model, + timestamp: DateTime.formatIso(DateTime.fromDateUnsafe(new Date(event.created * 1000))), + request: buildHttpRequestDetails(response.request) + }) + } + + const choice = event.choices[0] + if (Predicate.isUndefined(choice)) { + return parts + } + + const reasoningDelta = choice.delta?.reasoning ?? choice.delta?.reasoning_content + if (Predicate.isNotNullish(reasoningDelta) && reasoningDelta.length > 0) { + if (!reasoningStarted) { + reasoningStarted = true + parts.push({ + type: "reasoning-start", + id: reasoningId, + metadata: { openai: { ...makeItemIdMetadata(reasoningId) } } + }) + } + parts.push({ type: "reasoning-delta", id: reasoningId, delta: reasoningDelta }) + } + + if (choice.delta?.content !== undefined && Predicate.isNotNull(choice.delta.content)) { + if (reasoningStarted) { + reasoningStarted = false + parts.push({ + type: "reasoning-end", + id: reasoningId, + metadata: { openai: { ...makeItemIdMetadata(reasoningId) } } + }) + } + + if (!textStarted) { + textStarted = true + parts.push({ + type: "text-start", + id: textId, + metadata: { openai: { ...makeItemIdMetadata(textId) } } + }) + } + parts.push({ type: "text-delta", id: textId, delta: choice.delta.content }) + } + + if (Predicate.isNotNullish(choice.delta?.tool_calls)) { + hasToolCalls = hasToolCalls || choice.delta.tool_calls.length > 0 + choice.delta.tool_calls.forEach((deltaTool, indexInChunk) => { + const toolIndex = deltaTool.index ?? indexInChunk + const activeToolCall = activeToolCalls[toolIndex] + const toolId = activeToolCall?.id ?? deltaTool.id ?? `${event.id}_tool_${toolIndex}` + const providerToolName = deltaTool.function?.name + const toolName = Predicate.isNotNullish(providerToolName) + ? toolNameMapper.getCustomName(providerToolName) + : activeToolCall?.name ?? toolNameMapper.getCustomName("unknown_tool") + const argumentsDelta = deltaTool.function?.arguments ?? "" + + if (Predicate.isUndefined(activeToolCall)) { + activeToolCalls[toolIndex] = { + id: toolId, + name: toolName, + arguments: argumentsDelta + } + parts.push({ type: "tool-params-start", id: toolId, name: toolName }) + } else { + activeToolCall.name = toolName + activeToolCall.arguments = `${activeToolCall.arguments}${argumentsDelta}` + } + + if (argumentsDelta.length > 0) { + parts.push({ type: "tool-params-delta", id: toolId, delta: argumentsDelta }) + } + }) + } + + if (choice.finish_reason !== undefined && Predicate.isNotNull(choice.finish_reason)) { + finishReason = choice.finish_reason + } + + return parts + })), + Stream.flattenIterable + ) + } +) + +// ============================================================================= +// Telemetry +// ============================================================================= + +const annotateRequest = ( + span: Span, + request: CreateResponseRequestJson +): void => { + addGenAIAnnotations(span, { + system: "openai", + operation: { name: "chat" }, + request: { + model: request.model as string, + temperature: request.temperature as number | undefined, + topP: request.top_p as number | undefined, + maxTokens: request.max_tokens as number | undefined + }, + openai: { + request: { + responseFormat: request.response_format?.type, + serviceTier: request.service_tier as string | undefined + } + } + }) +} + +const annotateResponse = (span: Span, response: CreateResponse200): void => { + const finishReason = response.choices[0]?.finish_reason ?? undefined + addGenAIAnnotations(span, { + response: { + id: response.id, + model: response.model as string, + finishReasons: finishReason !== undefined ? [finishReason] : undefined + }, + usage: { + inputTokens: response.usage?.prompt_tokens, + outputTokens: response.usage?.completion_tokens + }, + openai: { + response: { + serviceTier: response.service_tier as string | undefined + } + } + }) +} + +const annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => { + if (part.type === "response-metadata") { + addGenAIAnnotations(span, { + response: { + id: part.id, + model: part.modelId + } + }) + } + if (part.type === "finish") { + const serviceTier = (part.metadata as any)?.openai?.serviceTier as string | undefined + addGenAIAnnotations(span, { + response: { + finishReasons: [part.reason] + }, + usage: { + inputTokens: part.usage.inputTokens.total, + outputTokens: part.usage.outputTokens.total + }, + openai: { + response: { serviceTier } + } + }) + } +} + +// ============================================================================= +// Tool Conversion +// ============================================================================= + +type OpenAiToolChoice = CreateResponse["tool_choice"] + +const unsupportedSchemaError = (error: unknown, method: string): AiError.AiError => + AiError.make({ + module: "OpenAiLanguageModel", + method, + reason: new AiError.UnsupportedSchemaError({ + description: error instanceof Error ? error.message : String(error) + }) + }) + +const tryCodecTransform = (schema: S, method: string) => + Effect.try({ + try: () => toCodecOpenAI(schema), + catch: (error) => unsupportedSchemaError(error, method) + }) + +const tryJsonSchema = (schema: S, method: string) => + Effect.try({ + try: () => Tool.getJsonSchemaFromSchema(schema, { transformer: toCodecOpenAI }), + catch: (error) => unsupportedSchemaError(error, method) + }) + +const tryToolJsonSchema = (tool: T, method: string) => + Effect.try({ + try: () => Tool.getJsonSchema(tool, { transformer: toCodecOpenAI }), + catch: (error) => unsupportedSchemaError(error, method) + }) + +const transformToolCallParams = Effect.fnUntraced(function*>( + tools: Tools, + toolName: string, + toolParams: unknown +): Effect.fn.Return { + const tool = tools.find((tool) => tool.name === toolName) + + if (Predicate.isUndefined(tool)) { + return yield* AiError.make({ + module: "OpenAiLanguageModel", + method: "makeResponse", + reason: new AiError.ToolNotFoundError({ + toolName, + availableTools: tools.map((tool) => tool.name) + }) + }) + } + + const { codec } = yield* tryCodecTransform(tool.parametersSchema, "makeResponse") + const transform = Schema.decodeEffect(codec) + + return yield* ( + transform(toolParams) as Effect.Effect + ).pipe(Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "makeResponse", + reason: new AiError.ToolParameterValidationError({ + toolName, + toolParams, + description: formatIssue(error.issue) + }) + }) + )) +}) + +const prepareTools = Effect.fnUntraced(function*>({ + config, + options, + toolNameMapper +}: { + readonly config: typeof Config.Service + readonly options: LanguageModel.ProviderOptions + readonly toolNameMapper: Tool.NameMapper +}): Effect.fn.Return<{ + readonly tools: ReadonlyArray | undefined + readonly toolChoice: OpenAiToolChoice | undefined +}, AiError.AiError> { + // Return immediately if no tools are in the toolkit + if (options.tools.length === 0) { + return { tools: undefined, toolChoice: undefined } + } + + const tools: Array = [] + let toolChoice: OpenAiToolChoice | undefined = undefined + + // Filter the incoming tools down to the set of allowed tools as indicated by + // the tool choice. This must be done here given that there is no tool name + // in OpenAI's provider-defined tools, so there would be no way to perform + // this filter otherwise + let allowedTools = options.tools + if (typeof options.toolChoice === "object" && "oneOf" in options.toolChoice) { + const allowedToolNames = new Set(options.toolChoice.oneOf) + allowedTools = options.tools.filter((tool) => allowedToolNames.has(tool.name)) + toolChoice = options.toolChoice.mode === "required" ? "required" : "auto" + } + + // Convert the tools in the toolkit to the provider-defined format + for (const tool of allowedTools) { + if (Tool.isUserDefined(tool) || Tool.isDynamic(tool)) { + const strict = Tool.getStrictMode(tool) ?? config.strictJsonSchema ?? true + const parameters = yield* tryToolJsonSchema(tool, "prepareTools") + tools.push({ + type: "function", + name: tool.name, + description: Tool.getDescription(tool) ?? null, + parameters: parameters as { readonly [x: string]: Schema.Json }, + strict + }) + } + + if (Tool.isProviderDefined(tool)) { + tools.push({ + type: "function", + name: tool.providerName, + description: Tool.getDescription(tool) ?? null, + parameters: Tool.getJsonSchema(tool) as { readonly [x: string]: Schema.Json }, + strict: config.strictJsonSchema ?? true + }) + } + } + + if (options.toolChoice === "auto" || options.toolChoice === "none" || options.toolChoice === "required") { + toolChoice = options.toolChoice + } + + if (typeof options.toolChoice === "object" && "tool" in options.toolChoice) { + const toolName = toolNameMapper.getProviderName(options.toolChoice.tool) + const providerNames = toolNameMapper.providerNames + if (providerNames.includes(toolName)) { + toolChoice = { type: "function", name: toolName } + } else { + toolChoice = { type: "function", name: options.toolChoice.tool } + } + } + + return { tools, toolChoice } +}) + +const toChatCompletionsRequest = (payload: CreateResponse): CreateResponseRequestJson => { + const messages = toChatMessages(payload.input) + const responseFormat = toChatResponseFormat(payload.text?.format) + const tools = payload.tools !== undefined + ? payload.tools.map(toChatTool).filter((tool): tool is NonNullable> => + tool !== undefined + ) + : [] + const toolChoice = toChatToolChoice(payload.tool_choice) + + return { + ...extractCustomRequestProperties(payload), + model: payload.model ?? "", + messages: messages.length > 0 ? messages : [{ role: "user", content: "" }], + ...(payload.temperature !== undefined ? { temperature: payload.temperature } : undefined), + ...(payload.top_p !== undefined ? { top_p: payload.top_p } : undefined), + ...(payload.max_output_tokens !== undefined ? { max_tokens: payload.max_output_tokens } : undefined), + ...(payload.user !== undefined ? { user: payload.user } : undefined), + ...(payload.seed !== undefined ? { seed: payload.seed } : undefined), + ...(payload.parallel_tool_calls !== undefined + ? { parallel_tool_calls: payload.parallel_tool_calls } + : undefined), + ...(payload.service_tier !== undefined ? { service_tier: payload.service_tier } : undefined), + ...(payload.reasoning !== undefined ? { reasoning: payload.reasoning } : undefined), + ...(responseFormat !== undefined ? { response_format: responseFormat } : undefined), + ...(tools.length > 0 ? { tools } : undefined), + ...(toolChoice !== undefined ? { tool_choice: toolChoice } : undefined) + } +} + +const createResponseKnownProperties = new Set([ + "metadata", + "top_logprobs", + "temperature", + "top_p", + "user", + "safety_identifier", + "prompt_cache_key", + "service_tier", + "prompt_cache_retention", + "previous_response_id", + "model", + "reasoning", + "background", + "max_output_tokens", + "max_tool_calls", + "text", + "tools", + "tool_choice", + "truncation", + "input", + "include", + "parallel_tool_calls", + "store", + "instructions", + "stream", + "conversation", + "modalities", + "seed" +]) + +const extractCustomRequestProperties = (payload: CreateResponse): Record => { + const customProperties: Record = {} + for (const [key, value] of Object.entries(payload)) { + if (!createResponseKnownProperties.has(key)) { + Rec.assignProperty(customProperties, key, value) + } + } + return customProperties +} + +const toChatResponseFormat = ( + format: TextResponseFormatConfiguration | undefined +): CreateResponseRequestJson["response_format"] | undefined => { + if (Predicate.isUndefined(format) || Predicate.isNull(format)) { + return undefined + } + + switch (format.type) { + case "json_object": { + return { type: "json_object" } + } + case "json_schema": { + return { + type: "json_schema", + json_schema: { + name: format.name, + schema: format.schema, + ...(format.description !== undefined ? { description: format.description } : undefined), + ...(Predicate.isNotNullish(format.strict) ? { strict: format.strict } : undefined) + } + } + } + default: { + return undefined + } + } +} + +const toChatToolChoice = ( + toolChoice: OpenAiToolChoice +): CreateResponseRequestJson["tool_choice"] | undefined => { + if (Predicate.isUndefined(toolChoice)) { + return undefined + } + + if (typeof toolChoice === "string") { + return toolChoice + } + + if (toolChoice.type === "allowed_tools") { + return toolChoice.mode + } + + if (toolChoice.type === "function") { + return { + type: "function", + function: { + name: toolChoice.name + } + } + } + + const functionName = Predicate.hasProperty(toolChoice, "name") && typeof toolChoice.name === "string" + ? toolChoice.name + : toolChoice.type + + return { + type: "function", + function: { + name: functionName + } + } +} + +const toChatTool = ( + tool: OpenAiClientTool +): NonNullable[number] | undefined => { + if (tool.type === "function") { + return { + type: "function", + function: { + name: tool.name, + ...(tool.description !== undefined ? { description: tool.description } : undefined), + ...(Predicate.isNotNullish(tool.parameters) ? { parameters: tool.parameters } : undefined), + ...(Predicate.isNotNullish(tool.strict) ? { strict: tool.strict } : undefined) + } + } + } + + if (tool.type === "custom") { + return { + type: "function", + function: { + name: tool.name, + parameters: { type: "object", additionalProperties: true } + } + } + } + + return undefined +} + +const toChatMessages = ( + input: CreateResponse["input"] +): Array => { + if (Predicate.isUndefined(input)) { + return [] + } + + if (typeof input === "string") { + return [{ role: "user", content: input }] + } + + const messages: Array = [] + + for (const item of input) { + if (Predicate.hasProperty(item, "type") && item.type === "function_call") { + const previous = messages.at(-1) + const toolCall = toChatToolCall(item) + if (previous?.role === "assistant" && previous.tool_calls !== undefined) { + messages[messages.length - 1] = { + ...previous, + tool_calls: [...previous.tool_calls, toolCall] + } + } else { + messages.push({ + role: "assistant", + content: null, + tool_calls: [toolCall] + }) + } + } else { + messages.push(...toChatMessagesFromItem(item)) + } + } + + return messages +} + +const toChatMessagesFromItem = ( + item: InputItem +): Array => { + if (Predicate.hasProperty(item, "type") && item.type === "message") { + return [{ + role: item.role, + content: toAssistantChatMessageContent(item.content) + }] + } + + if (Predicate.hasProperty(item, "role")) { + return [{ + role: item.role, + content: toChatMessageContent(item.content) + }] + } + + switch (item.type) { + case "function_call": { + return [{ + role: "assistant", + content: null, + tool_calls: [toChatToolCall(item)] + }] + } + + case "function_call_output": { + return [{ + role: "tool", + tool_call_id: item.call_id, + content: stringifyJson(item.output) + }] + } + + default: { + return [] + } + } +} + +const toChatToolCall = ( + item: Extract +): ChatCompletionRequestToolCall => ({ + id: item.call_id, + type: "function", + function: { + name: item.name, + arguments: item.arguments + } +}) + +const toAssistantChatMessageContent = ( + content: ReadonlyArray<{ + readonly type: string + readonly [x: string]: unknown + }> +): string => { + let text = "" + for (const part of content) { + if (part.type === "output_text" && typeof part.text === "string") { + text += part.text + } + if (part.type === "refusal" && typeof part.refusal === "string") { + text += part.refusal + } + } + return text +} + +const toChatMessageContent = ( + content: string | ReadonlyArray +): string | ReadonlyArray => { + if (typeof content === "string") { + return content + } + + const parts: Array = [] + + for (const part of content) { + switch (part.type) { + case "input_text": { + parts.push({ type: "text", text: part.text }) + break + } + case "input_image": { + const imageUrl = part.image_url !== undefined + ? part.image_url + : part.file_id !== undefined + ? `openai://file/${part.file_id}` + : undefined + + if (imageUrl !== undefined && Predicate.isNotNull(imageUrl)) { + parts.push({ + type: "image_url", + image_url: { + url: imageUrl, + ...(Predicate.isNotNullish(part.detail) ? { detail: part.detail } : undefined) + } + }) + } + break + } + case "input_file": { + if (part.file_url !== undefined) { + parts.push({ type: "text", text: part.file_url }) + } else if (part.file_data !== undefined) { + parts.push({ type: "text", text: part.file_data }) + } else if (part.file_id !== undefined) { + parts.push({ type: "text", text: `openai://file/${part.file_id}` }) + } + break + } + } + } + + if (parts.length === 0) { + return "" + } + + if (parts.every((part) => part.type === "text")) { + return parts.map((part) => part.text).join("\n") + } + + return parts +} + +const stringifyJson = (value: unknown): string => + typeof value === "string" + ? value + : JSON.stringify(value) + +// ============================================================================= +// Utilities +// ============================================================================= + +const isFileId = (data: string, config: typeof Config.Service): boolean => + config.fileIdPrefixes != null && config.fileIdPrefixes.some((prefix) => data.startsWith(prefix)) + +const getItemId = ( + part: + | Prompt.TextPart + | Prompt.ReasoningPart + | Prompt.ToolCallPart + | Prompt.ToolResultPart +): string | null => part.options.openai?.itemId ?? null +const getStatus = ( + part: + | Prompt.TextPart + | Prompt.ToolCallPart + | Prompt.ToolResultPart +): MessageStatus | null => part.options.openai?.status ?? null +const getEncryptedContent = ( + part: Prompt.ReasoningPart +): string | null => part.options.openai?.encryptedContent ?? null + +const getImageDetail = (part: Prompt.FilePart): ImageDetail => part.options.openai?.imageDetail ?? "auto" + +const makeItemIdMetadata = (itemId: string | undefined) => itemId !== undefined ? { itemId } : undefined + +const normalizeServiceTier = ( + serviceTier: string | undefined +): "default" | "auto" | "flex" | "scale" | "priority" | null | undefined => { + switch (serviceTier) { + case undefined: + return undefined + case "default": + case "auto": + case "flex": + case "scale": + case "priority": + return serviceTier + default: + return null + } +} + +const prepareResponseFormat = Effect.fnUntraced(function*({ config, options }: { + readonly config: typeof Config.Service + readonly options: LanguageModel.ProviderOptions +}): Effect.fn.Return { + if (options.responseFormat.type === "json") { + const name = options.responseFormat.objectName + const schema = options.responseFormat.schema + const jsonSchema = yield* tryJsonSchema(schema, "prepareResponseFormat") + return { + type: "json_schema", + name, + description: AST.resolveDescription(schema.ast) ?? "Response with a JSON object", + schema: jsonSchema as any, + strict: config.strictJsonSchema ?? true + } + } + return { type: "text" } +}) + +interface ModelCapabilities { + readonly isReasoningModel: boolean + readonly systemMessageMode: "remove" | "system" | "developer" + readonly supportsFlexProcessing: boolean + readonly supportsPriorityProcessing: boolean + /** + * Allow temperature, topP, logProbs when reasoningEffort is none. + */ + readonly supportsNonReasoningParameters: boolean +} + +const getModelCapabilities = (modelId: string): ModelCapabilities => { + const supportsFlexProcessing = modelId.startsWith("o3") || + modelId.startsWith("o4-mini") || + (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat")) + + const supportsPriorityProcessing = modelId.startsWith("gpt-4") || + modelId.startsWith("gpt-5-mini") || + (modelId.startsWith("gpt-5") && + !modelId.startsWith("gpt-5-nano") && + !modelId.startsWith("gpt-5-chat")) || + modelId.startsWith("o3") || + modelId.startsWith("o4-mini") + + // Use allowlist approach: only known reasoning models should use 'developer' role + // This prevents issues with fine-tuned models, third-party models, and custom models + const isReasoningModel = modelId.startsWith("o1") || + modelId.startsWith("o3") || + modelId.startsWith("o4-mini") || + modelId.startsWith("codex-mini") || + modelId.startsWith("computer-use-preview") || + (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat")) + + // https://platform.openai.com/docs/guides/latest-model#gpt-5-1-parameter-compatibility + // GPT-5.1 and GPT-5.2 support temperature, topP, logProbs when reasoningEffort is none + const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2") + + const systemMessageMode = isReasoningModel ? "developer" : "system" + + return { + supportsFlexProcessing, + supportsPriorityProcessing, + isReasoningModel, + systemMessageMode, + supportsNonReasoningParameters + } +} + +const getUsage = (usage: CreateResponse200["usage"]): Response.Usage => { + if (Predicate.isNullish(usage)) { + return { + inputTokens: { + uncached: undefined, + total: undefined, + cacheRead: undefined, + cacheWrite: undefined + }, + outputTokens: { + total: undefined, + text: undefined, + reasoning: undefined + } + } + } + + const inputTokens = usage.prompt_tokens + const outputTokens = usage.completion_tokens + const cachedTokens = getUsageDetailNumber(usage.prompt_tokens_details, "cached_tokens") ?? 0 + const reasoningTokens = getUsageDetailNumber(usage.completion_tokens_details, "reasoning_tokens") ?? 0 + + return { + inputTokens: { + uncached: inputTokens - cachedTokens, + total: inputTokens, + cacheRead: cachedTokens, + cacheWrite: undefined + }, + outputTokens: { + total: outputTokens, + text: outputTokens - reasoningTokens, + reasoning: reasoningTokens + } + } +} + +const getUsageDetailNumber = ( + details: unknown, + field: string +): number | undefined => { + if (typeof details !== "object" || details === null) { + return undefined + } + + const value = (details as Record)[field] + return typeof value === "number" ? value : undefined +} diff --git a/packages/effect-ai-openai-compat/src/OpenAiTelemetry.ts b/packages/effect-ai-openai-compat/src/OpenAiTelemetry.ts new file mode 100644 index 0000000..21ab20e --- /dev/null +++ b/packages/effect-ai-openai-compat/src/OpenAiTelemetry.ts @@ -0,0 +1,208 @@ +/** + * The `OpenAiTelemetry` module defines OpenAI-compatible telemetry attributes + * and a helper for adding them to a tracing span. It keeps the standard GenAI + * telemetry attributes and adds request and response metadata under the + * `gen_ai.openai.*` OpenTelemetry namespaces. + * + * @since 4.0.0 + */ +import { dual } from "effect/Function" +import * as String from "effect/String" +import type { Span } from "effect/Tracer" +import type { Simplify } from "effect/Types" +import * as Telemetry from "effect/unstable/ai/Telemetry" + +/** + * The attributes used to describe telemetry in the context of Generative + * Artificial Intelligence (GenAI) Models requests and responses. + * + * **Details** + * + * These attributes follow the OpenTelemetry generative AI semantic + * conventions: + * https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/ + * + * @category models + * @since 4.0.0 + */ +export type OpenAiTelemetryAttributes = Simplify< + & Telemetry.GenAITelemetryAttributes + & Telemetry.AttributesWithPrefix + & Telemetry.AttributesWithPrefix +> + +/** + * All telemetry attributes which are part of the GenAI specification, + * including the OpenAI-specific attributes. + * + * @category models + * @since 4.0.0 + */ +export type AllAttributes = Telemetry.AllAttributes & RequestAttributes & ResponseAttributes + +/** + * Telemetry attributes which are part of the GenAI specification and are + * namespaced by `gen_ai.openai.request`. + * + * @category models + * @since 4.0.0 + */ +export interface RequestAttributes { + /** + * The response format that is requested. + */ + readonly responseFormat?: (string & {}) | WellKnownResponseFormat | null | undefined + /** + * The service tier requested. May be a specific tier, `default`, or `auto`. + */ + readonly serviceTier?: (string & {}) | WellKnownServiceTier | null | undefined +} + +/** + * Telemetry attributes which are part of the GenAI specification and are + * namespaced by `gen_ai.openai.response`. + * + * @category models + * @since 4.0.0 + */ +export interface ResponseAttributes { + /** + * The service tier used for the response. + */ + readonly serviceTier?: string | null | undefined + /** + * A fingerprint to track any eventual change in the Generative AI + * environment. + */ + readonly systemFingerprint?: string | null | undefined +} + +/** + * The `gen_ai.openai.request.response_format` attribute has a list of + * well-known values. + * + * **Details** + * + * If one of them applies, then the respective value **MUST** be used; + * otherwise, a custom value **MAY** be used. + * + * @category models + * @since 4.0.0 + */ +export type WellKnownResponseFormat = "json_object" | "json_schema" | "text" + +/** + * The `gen_ai.openai.request.service_tier` attribute has a list of + * well-known values. + * + * **Details** + * + * If one of them applies, then the respective value **MUST** be used; + * otherwise, a custom value **MAY** be used. + * + * @category models + * @since 4.0.0 + */ +export type WellKnownServiceTier = "auto" | "default" + +/** + * Options accepted by `addGenAIAnnotations`, combining standard GenAI telemetry + * attributes with optional OpenAI-compatible request and response attributes. + * + * @category options + * @since 4.0.0 + */ +export type OpenAiTelemetryAttributeOptions = Telemetry.GenAITelemetryAttributeOptions & { + openai?: { + request?: RequestAttributes | undefined + response?: ResponseAttributes | undefined + } | undefined +} + +const addOpenAiRequestAttributes = Telemetry.addSpanAttributes("gen_ai.openai.request", String.camelToSnake)< + RequestAttributes +> +const addOpenAiResponseAttributes = Telemetry.addSpanAttributes("gen_ai.openai.response", String.camelToSnake)< + ResponseAttributes +> + +/** + * Applies the specified OpenAI GenAI telemetry attributes to the provided + * `Span`. + * + * **When to use** + * + * Use to annotate an OpenAI-compatible model span with standard GenAI telemetry + * attributes and OpenAI-specific request or response metadata. + * + * **Details** + * + * Standard GenAI attributes are applied first. When OpenAI request or response + * metadata is present, it is written under `gen_ai.openai.request.*` and + * `gen_ai.openai.response.*` attributes. + * + * **Gotchas** + * + * Mutates the supplied `Span` in place. + * + * @category tracing + * @since 4.0.0 + */ +export const addGenAIAnnotations: { + /** + * Applies the specified OpenAI GenAI telemetry attributes to the provided + * `Span`. + * + * **When to use** + * + * Use to annotate an OpenAI-compatible model span with standard GenAI telemetry + * attributes and OpenAI-specific request or response metadata. + * + * **Details** + * + * Standard GenAI attributes are applied first. When OpenAI request or response + * metadata is present, it is written under `gen_ai.openai.request.*` and + * `gen_ai.openai.response.*` attributes. + * + * **Gotchas** + * + * Mutates the supplied `Span` in place. + * + * @category tracing + * @since 4.0.0 + */ + (options: OpenAiTelemetryAttributeOptions): (span: Span) => void + /** + * Applies the specified OpenAI GenAI telemetry attributes to the provided + * `Span`. + * + * **When to use** + * + * Use to annotate an OpenAI-compatible model span with standard GenAI telemetry + * attributes and OpenAI-specific request or response metadata. + * + * **Details** + * + * Standard GenAI attributes are applied first. When OpenAI request or response + * metadata is present, it is written under `gen_ai.openai.request.*` and + * `gen_ai.openai.response.*` attributes. + * + * **Gotchas** + * + * Mutates the supplied `Span` in place. + * + * @category tracing + * @since 4.0.0 + */ + (span: Span, options: OpenAiTelemetryAttributeOptions): void +} = dual(2, (span: Span, options: OpenAiTelemetryAttributeOptions) => { + Telemetry.addGenAIAnnotations(span, options) + if (options.openai != null) { + if (options.openai.request != null) { + addOpenAiRequestAttributes(span, options.openai.request) + } + if (options.openai.response != null) { + addOpenAiResponseAttributes(span, options.openai.response) + } + } +}) diff --git a/packages/effect-ai-openai-compat/src/index.ts b/packages/effect-ai-openai-compat/src/index.ts new file mode 100644 index 0000000..7a5cd7f --- /dev/null +++ b/packages/effect-ai-openai-compat/src/index.ts @@ -0,0 +1,35 @@ +/** + * @since 4.0.0 + */ + +// @barrel: Auto-generated exports. Do not edit manually. + +/** + * @since 4.0.0 + */ +export * as OpenAiClient from "./OpenAiClient.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiConfig from "./OpenAiConfig.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiEmbeddingModel from "./OpenAiEmbeddingModel.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiError from "./OpenAiError.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiLanguageModel from "./OpenAiLanguageModel.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiTelemetry from "./OpenAiTelemetry.ts" diff --git a/packages/effect-ai-openai-compat/src/internal/errors.ts b/packages/effect-ai-openai-compat/src/internal/errors.ts new file mode 100644 index 0000000..500289c --- /dev/null +++ b/packages/effect-ai-openai-compat/src/internal/errors.ts @@ -0,0 +1,301 @@ +import * as Arr from "effect/Array" +import * as Duration from "effect/Duration" +import * as Effect from "effect/Effect" +import { dual } from "effect/Function" +import * as Number from "effect/Number" +import * as Option from "effect/Option" +import * as Redactable from "effect/Redactable" +import * as Schema from "effect/Schema" +import * as SchemaTransformation from "effect/SchemaTransformation" +import * as String from "effect/String" +import * as AiError from "effect/unstable/ai/AiError" +import type * as Response from "effect/unstable/ai/Response" +import type * as Sse from "effect/unstable/encoding/Sse" +import type * as HttpClientError from "effect/unstable/http/HttpClientError" +import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import type { OpenAiErrorMetadata } from "../OpenAiError.ts" + +/** @internal */ +export const OpenAiErrorBody = Schema.Struct({ + error: Schema.Struct({ + message: Schema.String, + type: Schema.optional(Schema.NullOr(Schema.String)), + status: Schema.optional(Schema.NullOr(Schema.String)), + param: Schema.optional(Schema.NullOr(Schema.String)), + code: Schema.optional(Schema.NullOr(Schema.Union([Schema.String, Schema.Finite]))) + }) +}) +const OpenAiErrorBodyJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Union([ + OpenAiErrorBody, + Schema.NonEmptyArray(OpenAiErrorBody).pipe( + Schema.decodeTo( + Schema.toType(OpenAiErrorBody), + SchemaTransformation.transform({ + decode: Arr.headNonEmpty, + encode: (item) => [item] + }) + ) + ) +]))) + +/** @internal */ +export const mapSchemaError = dual< + (method: string) => (error: Schema.SchemaError) => AiError.AiError, + (error: Schema.SchemaError, method: string) => AiError.AiError +>(2, (error, method) => + AiError.make({ + module: "OpenAiClient", + method, + reason: AiError.InvalidOutputError.fromSchemaError(error) + })) + +/** @internal */ +export const mapSseError = dual< + (method: string) => (error: Sse.SseError) => AiError.AiError, + (error: Sse.SseError, method: string) => AiError.AiError +>(2, (error, method) => + AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.InvalidOutputError({ description: error.message }) + })) + +/** @internal */ +export const mapHttpClientError = dual< + (method: string) => (error: HttpClientError.HttpClientError) => Effect.Effect, + (error: HttpClientError.HttpClientError, method: string) => Effect.Effect +>(2, (error, method) => { + const reason = error.reason + switch (reason._tag) { + case "TransportError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.NetworkError({ + reason: "TransportError", + description: reason.description, + request: buildHttpRequestDetails(reason.request) + }) + })) + } + case "EncodeError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.NetworkError({ + reason: "EncodeError", + description: reason.description, + request: buildHttpRequestDetails(reason.request) + }) + })) + } + case "InvalidUrlError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.NetworkError({ + reason: "InvalidUrlError", + description: reason.description, + request: buildHttpRequestDetails(reason.request) + }) + })) + } + case "StatusCodeError": { + return mapStatusCodeError(reason, method) + } + case "DecodeError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.InvalidOutputError({ + description: reason.description ?? "Failed to decode response" + }) + })) + } + case "EmptyBodyError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.InvalidOutputError({ + description: reason.description ?? "Response body was empty" + }) + })) + } + } +}) + +/** @internal */ +const mapStatusCodeError = Effect.fnUntraced(function*( + error: HttpClientError.StatusCodeError, + method: string +) { + const { request, response, description } = error + const status = response.status + const headers = response.headers as Record + const requestId = headers["x-request-id"] + + let body = yield* response.text.pipe( + Effect.catchCause(() => Effect.succeed(description?.startsWith("{") ? description : undefined)) + ) + const decoded = OpenAiErrorBodyJson(body) + + const reason = mapStatusCodeToReason({ + status, + headers, + message: Option.isSome(decoded) ? decoded.value.error.message : undefined, + http: buildHttpContext({ request, response, body }), + metadata: { + errorCode: Option.isSome(decoded) ? decoded.value.error.code?.toString() ?? null : null, + errorType: decoded.pipe( + Option.flatMapNullishOr((d) => d.error.type ?? d.error.status), + Option.map(String.toLowerCase), + Option.getOrNull + ), + requestId: requestId ?? null + } + }) + + return yield* AiError.make({ module: "OpenAiClient", method, reason }) +}) + +/** @internal */ +export const parseRateLimitHeaders = (headers: Record) => { + const retryAfterRaw = headers["retry-after"] + let retryAfter: Duration.Duration | undefined + if (retryAfterRaw !== undefined) { + const parsed = Number.parse(retryAfterRaw) + if (Option.isSome(parsed)) { + retryAfter = Duration.seconds(parsed.value) + } + } + const remainingRaw = headers["x-ratelimit-remaining-requests"] + const remaining = remainingRaw !== undefined ? Option.getOrNull(Number.parse(remainingRaw)) : null + return { + retryAfter, + limit: headers["x-ratelimit-limit-requests"] ?? null, + remaining, + resetRequests: headers["x-ratelimit-reset-requests"] ?? null, + resetTokens: headers["x-ratelimit-reset-tokens"] ?? null + } +} + +/** @internal */ +export const buildHttpRequestDetails = ( + request: HttpClientRequest.HttpClientRequest +): typeof Response.HttpRequestDetails.Type => ({ + method: request.method, + url: request.url, + urlParams: Array.from(request.urlParams), + hash: Option.getOrUndefined(request.hash), + headers: Redactable.redact(request.headers) as Record +}) + +/** @internal */ +export const buildHttpContext = (params: { + readonly request: HttpClientRequest.HttpClientRequest + readonly response?: HttpClientResponse.HttpClientResponse + readonly body?: string | undefined +}): typeof AiError.HttpContext.Type => ({ + request: buildHttpRequestDetails(params.request), + response: params.response !== undefined + ? { + status: params.response.status, + headers: Redactable.redact(params.response.headers) as Record + } + : undefined, + body: params.body +}) + +/** @internal */ +export const mapStatusCodeToReason = ({ status, headers, message, metadata, http }: { + readonly status: number + readonly headers: Record + readonly message: string | undefined + readonly metadata: OpenAiErrorMetadata + readonly http: typeof AiError.HttpContext.Type +}): AiError.AiErrorReason => { + const errorDescription = AiError.buildErrorDescription({ + status, + message, + method: http.request.method, + url: http.request.url, + errorCode: metadata.errorCode, + errorType: metadata.errorType, + requestId: metadata.requestId, + body: http.body + }) + + switch (status) { + case 400: + return new AiError.InvalidRequestError({ + description: errorDescription, + metadata: { openai: metadata }, + http + }) + case 401: + return new AiError.AuthenticationError({ + kind: "InvalidKey", + description: errorDescription, + metadata, + http + }) + case 403: + return new AiError.AuthenticationError({ + kind: "InsufficientPermissions", + description: errorDescription, + metadata, + http + }) + case 404: + return new AiError.InvalidRequestError({ + description: errorDescription, + metadata: { openai: metadata }, + http + }) + case 409: + case 422: + return new AiError.InvalidRequestError({ + description: errorDescription, + metadata: { openai: metadata }, + http + }) + case 429: { + if ( + metadata.errorCode === "insufficient_quota" || + metadata.errorType === "insufficient_quota" || + metadata.errorType?.includes("quota") || + metadata.errorType?.includes("exhausted") + ) { + return new AiError.QuotaExhaustedError({ + metadata: { openai: metadata }, + http + }) + } + const { retryAfter, ...rateLimitMetadata } = parseRateLimitHeaders(headers) + return new AiError.RateLimitError({ + retryAfter, + metadata: { + openai: { + ...metadata, + ...rateLimitMetadata + } + }, + http + }) + } + default: + if (status >= 500) { + return new AiError.InternalProviderError({ + description: message ?? "Server error", + metadata, + http + }) + } + return new AiError.UnknownError({ + description: message, + metadata, + http + }) + } +} diff --git a/packages/effect-ai-openai-compat/src/internal/utilities.ts b/packages/effect-ai-openai-compat/src/internal/utilities.ts new file mode 100644 index 0000000..75daf6b --- /dev/null +++ b/packages/effect-ai-openai-compat/src/internal/utilities.ts @@ -0,0 +1,24 @@ +import type * as Response from "effect/unstable/ai/Response" + +const finishReasonMap: Record = { + content_filter: "content-filter", + function_call: "tool-calls", + length: "length", + stop: "stop", + tool_calls: "tool-calls" +} + +/** @internal */ +export const resolveFinishReason = ( + finishReason: string | null | undefined, + hasToolCalls: boolean +): Response.FinishReason => { + if (finishReason == null) { + return hasToolCalls ? "tool-calls" : "stop" + } + const reason = Object.hasOwn(finishReasonMap, finishReason) ? finishReasonMap[finishReason] : undefined + if (reason == null) { + return hasToolCalls ? "tool-calls" : "unknown" + } + return reason +} diff --git a/packages/effect-ai-openai-compat/test/UpstreamParity.test.ts b/packages/effect-ai-openai-compat/test/UpstreamParity.test.ts new file mode 100644 index 0000000..892404d --- /dev/null +++ b/packages/effect-ai-openai-compat/test/UpstreamParity.test.ts @@ -0,0 +1,40 @@ +import { createHash } from 'node:crypto' +import { readFileSync } from 'node:fs' +import { dirname, join } from 'node:path' +import { fileURLToPath } from 'node:url' + +import { assert, it } from '@effect/vitest' +import { + OpenAiClient, + OpenAiConfig, + OpenAiEmbeddingModel, + OpenAiLanguageModel, +} from '@humanlayer/effect-ai-openai-compat' + +const packageRoot = dirname(dirname(fileURLToPath(import.meta.url))) + +it('keeps unmodified OpenAI-compatible provider source snapshot files byte-exact', () => { + const checksums = readFileSync(join(packageRoot, 'UPSTREAM.sha256'), 'utf8') + .trim() + .split('\n') + .map((line) => { + const separator = line.indexOf(' ') + return { checksum: line.slice(0, separator), path: line.slice(separator + 2) } + }) + + for (const { checksum, path } of checksums) { + const contents = readFileSync(join(packageRoot, path)) + const actual = createHash('sha256').update(contents).digest('hex') + assert.strictEqual(actual, checksum, path) + } +}) + +it('uses HumanLayer-specific Effect service keys', () => { + assert.strictEqual(OpenAiClient.OpenAiClient.key, '@humanlayer/effect-ai-openai-compat/OpenAiClient') + assert.strictEqual(OpenAiConfig.OpenAiConfig.key, '@humanlayer/effect-ai-openai-compat/OpenAiConfig') + assert.strictEqual( + OpenAiEmbeddingModel.Config.key, + '@humanlayer/effect-ai-openai-compat/OpenAiEmbeddingModel/Config', + ) + assert.strictEqual(OpenAiLanguageModel.Config.key, '@humanlayer/effect-ai-openai-compat/OpenAiLanguageModel/Config') +}) diff --git a/packages/effect-ai-openai-compat/tsconfig.json b/packages/effect-ai-openai-compat/tsconfig.json new file mode 100644 index 0000000..75fb0eb --- /dev/null +++ b/packages/effect-ai-openai-compat/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noUncheckedIndexedAccess": false, + "noImplicitReturns": false + }, + "include": ["src"] +} diff --git a/packages/effect-ai-openai-compat/vitest.config.ts b/packages/effect-ai-openai-compat/vitest.config.ts new file mode 100644 index 0000000..62216b1 --- /dev/null +++ b/packages/effect-ai-openai-compat/vitest.config.ts @@ -0,0 +1,3 @@ +import { base } from '@humanlayer/fold-vitest-config' + +export default base diff --git a/packages/effect-ai-openai/LICENSE b/packages/effect-ai-openai/LICENSE new file mode 100644 index 0000000..be1f5c1 --- /dev/null +++ b/packages/effect-ai-openai/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2023 Effectful Technologies Inc + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/effect-ai-openai/README.md b/packages/effect-ai-openai/README.md new file mode 100644 index 0000000..f520827 --- /dev/null +++ b/packages/effect-ai-openai/README.md @@ -0,0 +1,14 @@ +# @humanlayer/effect-ai-openai + +An [OpenAI](https://openai.com) provider for the Effect AI modules. Includes a typed OpenAI API client, language model and embedding model layers, tools, and telemetry helpers. + +## Installation + +```sh +npm install effect@4.0.0-rc.112 @humanlayer/effect-ai-openai +``` + +## Documentation + +- [Effect website](https://effect.website) +- [API reference](https://effect.website/docs/v4/api/ai-openai) diff --git a/packages/effect-ai-openai/UPSTREAM.md b/packages/effect-ai-openai/UPSTREAM.md new file mode 100644 index 0000000..04ecf23 --- /dev/null +++ b/packages/effect-ai-openai/UPSTREAM.md @@ -0,0 +1,31 @@ +# Upstream provenance + +This directory is a vendored source snapshot of the published Effect OpenAI provider. It does not contain upstream +`dist/` output. + +| Field | Value | +| ---------------- | ------------------------------------------------------------------------------------------------- | +| Upstream package | `@effect/ai-openai@4.0.0-rc.112` | +| Source artifact | `https://registry.npmjs.org/@effect/ai-openai/-/ai-openai-4.0.0-rc.112.tgz` | +| npm integrity | `sha512-j2X86xvgpAtNiusyESADHZn3PUzMVatE1zWXd0No2aybx/euKiVBVWZOtzq7ntJ5KvPHRBOFXTGPADdApQrwug==` | +| Tarball SHA-256 | `26902ae06ec9118172f8033e84d4bffa19c0a6d3be56a42bc1147a6a131e4e43` | +| Imported at | `2026-09-03` | +| Imported inputs | `src/**`, `README.md`, and `LICENSE` | +| License | MIT; copied to [`LICENSE`](./LICENSE) | + +## HumanLayer delta + +- `src/OpenAiLanguageModel.ts` preserves string tool results, converts ordered `Prompt` text/image parts into + Responses `function_call_output` content, and continues to JSON-stringify unknown result objects. Raw base64 image + strings, byte arrays, file IDs, URLs, and data URLs are encoded as `input_image` values. +- `src/OpenAiSchema.ts` accepts provider stream-error events that omit `code`, `param`, or `sequence_number`, in both + flat and nested error shapes. +- Provider service/config keys use the `@humanlayer/effect-ai-openai` namespace so upstream and forked layers cannot + satisfy one another accidentally in the same Effect context. +- `test/HumanlayerFork.test.ts` covers the changed behavior through the public HumanLayer provider package. + +## Refresh rule + +Refresh from a released npm package or an explicit immutable upstream commit that has been verified against the +supported `effect` peer runtime. Update this table and review the full source diff; do not sync from a moving branch +reference or hand-edit generated `src/Generated.ts`. diff --git a/packages/effect-ai-openai/package.json b/packages/effect-ai-openai/package.json new file mode 100644 index 0000000..ff9e6f6 --- /dev/null +++ b/packages/effect-ai-openai/package.json @@ -0,0 +1,37 @@ +{ + "name": "@humanlayer/effect-ai-openai", + "version": "0.0.0", + "private": true, + "license": "MIT", + "type": "module", + "description": "HumanLayer's vendored OpenAI provider for Effect AI SDK", + "sideEffects": [], + "exports": { + "./package.json": "./package.json", + ".": { + "types": "./dist/index.d.ts", + "import": "./src/index.ts", + "default": "./src/index.ts" + }, + "./*": { + "types": "./dist/*.d.ts", + "import": "./src/*.ts", + "default": "./src/*.ts" + }, + "./internal/*": null, + "./index": null, + "./*/index": null + }, + "scripts": { + "typecheck": "tsc --noEmit", + "test": "bun vitest run test/HumanlayerFork.test.ts" + }, + "peerDependencies": { + "effect": "catalog:" + }, + "devDependencies": { + "@effect/vitest": "catalog:", + "@humanlayer/fold-vitest-config": "workspace:*", + "effect": "catalog:" + } +} diff --git a/packages/effect-ai-openai/src/Generated.ts b/packages/effect-ai-openai/src/Generated.ts new file mode 100644 index 0000000..d51b312 --- /dev/null +++ b/packages/effect-ai-openai/src/Generated.ts @@ -0,0 +1,35774 @@ +/** + * @since 1.0.0 + */ + +import * as Data from "effect/Data" +import * as Effect from "effect/Effect" +import type { SchemaError } from "effect/Schema" +import * as Schema from "effect/Schema" +import * as Stream from "effect/Stream" +import * as Sse from "effect/unstable/encoding/Sse" +import * as HttpClient from "effect/unstable/http/HttpClient" +import * as HttpClientError from "effect/unstable/http/HttpClientError" +import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +// non-recursive definitions +export type AddUploadPartRequest = { readonly "data": string } +export const AddUploadPartRequest = Schema.Struct({ + "data": Schema.String.annotate({ "description": "The chunk of bytes for this Part.\n", "format": "binary" }) +}) +export type AdminApiKey = { + readonly "object": "organization.admin_api_key" + readonly "id": string + readonly "name"?: string | null + readonly "redacted_value": string + readonly "created_at": number + readonly "last_used_at"?: number | null + readonly "owner": { + readonly "type"?: string + readonly "object"?: string + readonly "id"?: string + readonly "name"?: string + readonly "created_at"?: number + readonly "role"?: string + } +} +export const AdminApiKey = Schema.Struct({ + "object": Schema.Literal("organization.admin_api_key").annotate({ + "description": "The object type, which is always `organization.admin_api_key`" + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The name of the API key" }) + ), + "redacted_value": Schema.String.annotate({ "description": "The redacted value of the API key" }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the API key was created", + "format": "unixtime" + }).check(Schema.isInt()), + "last_used_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the API key was last used", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "owner": Schema.Struct({ + "type": Schema.optionalKey(Schema.String.annotate({ "description": "Always `user`" })), + "object": Schema.optionalKey( + Schema.String.annotate({ "description": "The object type, which is always organization.user" }) + ), + "id": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }) + ), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the user" })), + "created_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the user was created", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "role": Schema.optionalKey(Schema.String.annotate({ "description": "Always `owner`" })) + }) +}).annotate({ "description": "Represents an individual Admin API key in an org." }) +export type AdminApiKeyCreateResponse = { + readonly "object": "organization.admin_api_key" + readonly "id": string + readonly "name"?: string | null + readonly "redacted_value": string + readonly "created_at": number + readonly "last_used_at"?: number | null + readonly "owner": { + readonly "type"?: string + readonly "object"?: string + readonly "id"?: string + readonly "name"?: string + readonly "created_at"?: number + readonly "role"?: string + } + readonly "value": string +} +export const AdminApiKeyCreateResponse = Schema.Struct({ + "object": Schema.Literal("organization.admin_api_key").annotate({ + "description": "The object type, which is always `organization.admin_api_key`" + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The name of the API key" }) + ), + "redacted_value": Schema.String.annotate({ "description": "The redacted value of the API key" }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the API key was created", + "format": "unixtime" + }).check(Schema.isInt()), + "last_used_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the API key was last used", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "owner": Schema.Struct({ + "type": Schema.optionalKey(Schema.String.annotate({ "description": "Always `user`" })), + "object": Schema.optionalKey( + Schema.String.annotate({ "description": "The object type, which is always organization.user" }) + ), + "id": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }) + ), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the user" })), + "created_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the user was created", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "role": Schema.optionalKey(Schema.String.annotate({ "description": "Always `owner`" })) + }), + "value": Schema.String.annotate({ "description": "The value of the API key. Only shown on create." }) +}).annotate({ + "description": "The newly created admin API key. The `value` field is only returned once, when the key is created." +}) +export type AssignedRoleDetails = { + readonly "id": string + readonly "name": string + readonly "permissions": ReadonlyArray + readonly "resource_type": string + readonly "predefined_role": boolean + readonly "description": string | null + readonly "created_at": number | null + readonly "updated_at": number | null + readonly "created_by": string | null + readonly "created_by_user_obj": {} | null + readonly "metadata": {} | null +} +export const AssignedRoleDetails = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier for the role." }), + "name": Schema.String.annotate({ "description": "Name of the role." }), + "permissions": Schema.Array(Schema.String).annotate({ "description": "Permissions associated with the role." }), + "resource_type": Schema.String.annotate({ "description": "Resource type the role applies to." }), + "predefined_role": Schema.Boolean.annotate({ "description": "Whether the role is predefined by OpenAI." }), + "description": Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "Description of the role." }), + "created_at": Schema.Union([Schema.Number.annotate({ "format": "unixtime" }).check(Schema.isInt()), Schema.Null]) + .annotate({ "description": "When the role was created." }), + "updated_at": Schema.Union([Schema.Number.annotate({ "format": "int64" }).check(Schema.isInt()), Schema.Null]) + .annotate({ "description": "When the role was last updated." }), + "created_by": Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "Identifier of the actor who created the role." + }), + "created_by_user_obj": Schema.Union([Schema.Struct({}), Schema.Null]).annotate({ + "description": "User details for the actor that created the role, when available." + }), + "metadata": Schema.Union([Schema.Struct({}), Schema.Null]).annotate({ + "description": "Arbitrary metadata stored on the role." + }) +}).annotate({ "description": "Detailed information about a role assignment entry returned when listing assignments." }) +export type AssistantSupportedModels = + | "gpt-5" + | "gpt-5-mini" + | "gpt-5-nano" + | "gpt-5-2025-08-07" + | "gpt-5-mini-2025-08-07" + | "gpt-5-nano-2025-08-07" + | "gpt-4.1" + | "gpt-4.1-mini" + | "gpt-4.1-nano" + | "gpt-4.1-2025-04-14" + | "gpt-4.1-mini-2025-04-14" + | "gpt-4.1-nano-2025-04-14" + | "o3-mini" + | "o3-mini-2025-01-31" + | "o1" + | "o1-2024-12-17" + | "gpt-4o" + | "gpt-4o-2024-11-20" + | "gpt-4o-2024-08-06" + | "gpt-4o-2024-05-13" + | "gpt-4o-mini" + | "gpt-4o-mini-2024-07-18" + | "gpt-4.5-preview" + | "gpt-4.5-preview-2025-02-27" + | "gpt-4-turbo" + | "gpt-4-turbo-2024-04-09" + | "gpt-4-0125-preview" + | "gpt-4-turbo-preview" + | "gpt-4-1106-preview" + | "gpt-4-vision-preview" + | "gpt-4" + | "gpt-4-0314" + | "gpt-4-0613" + | "gpt-4-32k" + | "gpt-4-32k-0314" + | "gpt-4-32k-0613" + | "gpt-3.5-turbo" + | "gpt-3.5-turbo-16k" + | "gpt-3.5-turbo-0613" + | "gpt-3.5-turbo-1106" + | "gpt-3.5-turbo-0125" + | "gpt-3.5-turbo-16k-0613" +export const AssistantSupportedModels = Schema.Literals([ + "gpt-5", + "gpt-5-mini", + "gpt-5-nano", + "gpt-5-2025-08-07", + "gpt-5-mini-2025-08-07", + "gpt-5-nano-2025-08-07", + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613" +]) +export type AssistantToolsCode = { readonly "type": "code_interpreter" } +export const AssistantToolsCode = Schema.Struct({ + "type": Schema.Literal("code_interpreter").annotate({ + "description": "The type of tool being defined: `code_interpreter`" + }) +}).annotate({ "title": "Code interpreter tool" }) +export type AssistantToolsFileSearchTypeOnly = { readonly "type": "file_search" } +export const AssistantToolsFileSearchTypeOnly = Schema.Struct({ + "type": Schema.Literal("file_search").annotate({ "description": "The type of tool being defined: `file_search`" }) +}).annotate({ "title": "FileSearch tool" }) +export type AssistantsNamedToolChoice = { + readonly "type": "function" | "code_interpreter" | "file_search" + readonly "function"?: { readonly "name": string } +} +export const AssistantsNamedToolChoice = Schema.Struct({ + "type": Schema.Literals(["function", "code_interpreter", "file_search"]).annotate({ + "description": "The type of the tool. If type is `function`, the function name must be set" + }), + "function": Schema.optionalKey( + Schema.Struct({ "name": Schema.String.annotate({ "description": "The name of the function to call." }) }) + ) +}).annotate({ "description": "Specifies a tool the model should use. Use to force the model to call a specific tool." }) +export type AudioResponseFormat = "json" | "text" | "srt" | "verbose_json" | "vtt" | "diarized_json" +export const AudioResponseFormat = Schema.Literals(["json", "text", "srt", "verbose_json", "vtt", "diarized_json"]) + .annotate({ + "description": + "The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, `vtt`, or `diarized_json`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`. For `gpt-4o-transcribe-diarize`, the supported formats are `json`, `text`, and `diarized_json`, with `diarized_json` required to receive speaker annotations.\n" + }) +export type AuditLogActorServiceAccount = { readonly "id"?: string } +export const AuditLogActorServiceAccount = Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The service account id." })) +}).annotate({ "description": "The service account that performed the audit logged action." }) +export type AuditLogActorUser = { readonly "id"?: string; readonly "email"?: string } +export const AuditLogActorUser = Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The user id." })), + "email": Schema.optionalKey(Schema.String.annotate({ "description": "The user email." })) +}).annotate({ "description": "The user who performed the audit logged action." }) +export type AuditLogEventType = + | "api_key.created" + | "api_key.updated" + | "api_key.deleted" + | "certificate.created" + | "certificate.updated" + | "certificate.deleted" + | "certificates.activated" + | "certificates.deactivated" + | "checkpoint.permission.created" + | "checkpoint.permission.deleted" + | "external_key.registered" + | "external_key.removed" + | "group.created" + | "group.updated" + | "group.deleted" + | "invite.sent" + | "invite.accepted" + | "invite.deleted" + | "ip_allowlist.created" + | "ip_allowlist.updated" + | "ip_allowlist.deleted" + | "ip_allowlist.config.activated" + | "ip_allowlist.config.deactivated" + | "login.succeeded" + | "login.failed" + | "logout.succeeded" + | "logout.failed" + | "organization.updated" + | "project.created" + | "project.updated" + | "project.archived" + | "project.deleted" + | "rate_limit.updated" + | "rate_limit.deleted" + | "resource.deleted" + | "tunnel.created" + | "tunnel.updated" + | "tunnel.deleted" + | "role.created" + | "role.updated" + | "role.deleted" + | "role.assignment.created" + | "role.assignment.deleted" + | "scim.enabled" + | "scim.disabled" + | "service_account.created" + | "service_account.updated" + | "service_account.deleted" + | "user.added" + | "user.updated" + | "user.deleted" +export const AuditLogEventType = Schema.Literals([ + "api_key.created", + "api_key.updated", + "api_key.deleted", + "certificate.created", + "certificate.updated", + "certificate.deleted", + "certificates.activated", + "certificates.deactivated", + "checkpoint.permission.created", + "checkpoint.permission.deleted", + "external_key.registered", + "external_key.removed", + "group.created", + "group.updated", + "group.deleted", + "invite.sent", + "invite.accepted", + "invite.deleted", + "ip_allowlist.created", + "ip_allowlist.updated", + "ip_allowlist.deleted", + "ip_allowlist.config.activated", + "ip_allowlist.config.deactivated", + "login.succeeded", + "login.failed", + "logout.succeeded", + "logout.failed", + "organization.updated", + "project.created", + "project.updated", + "project.archived", + "project.deleted", + "rate_limit.updated", + "rate_limit.deleted", + "resource.deleted", + "tunnel.created", + "tunnel.updated", + "tunnel.deleted", + "role.created", + "role.updated", + "role.deleted", + "role.assignment.created", + "role.assignment.deleted", + "scim.enabled", + "scim.disabled", + "service_account.created", + "service_account.updated", + "service_account.deleted", + "user.added", + "user.updated", + "user.deleted" +]).annotate({ "description": "The event type." }) +export type BatchFileExpirationAfter = { readonly "anchor": "created_at"; readonly "seconds": number } +export const BatchFileExpirationAfter = Schema.Struct({ + "anchor": Schema.Literal("created_at").annotate({ + "description": + "Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`. Note that the anchor is the file creation time, not the time the batch is created." + }), + "seconds": Schema.Number.annotate({ + "description": + "The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).", + "format": "int64" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(3600)).check(Schema.isLessThanOrEqualTo(2592000)) +}).annotate({ + "title": "File expiration policy", + "description": "The expiration policy for the output and/or error file that are generated for a batch." +}) +export type Certificate = { + readonly "object": "certificate" | "organization.certificate" | "organization.project.certificate" + readonly "id": string + readonly "name": string | null + readonly "created_at": number + readonly "certificate_details": { + readonly "valid_at"?: number + readonly "expires_at"?: number + readonly "content"?: string + } + readonly "active"?: boolean +} +export const Certificate = Schema.Struct({ + "object": Schema.Literals(["certificate", "organization.certificate", "organization.project.certificate"]).annotate({ + "description": + "The object type.\n\n- If creating, updating, or getting a specific certificate, the object type is `certificate`.\n- If listing, activating, or deactivating certificates for the organization, the object type is `organization.certificate`.\n- If listing, activating, or deactivating certificates for a project, the object type is `organization.project.certificate`.\n" + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The name of the certificate." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the certificate was uploaded.", + "format": "unixtime" + }).check(Schema.isInt()), + "certificate_details": Schema.Struct({ + "valid_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the certificate becomes valid.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "expires_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the certificate expires.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "content": Schema.optionalKey( + Schema.String.annotate({ "description": "The content of the certificate in PEM format." }) + ) + }), + "active": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": + "Whether the certificate is currently active at the specified scope. Not returned when getting details for a specific certificate." + }) + ) +}).annotate({ "description": "Represents an individual `certificate` uploaded to the organization." }) +export type ChatCompletionAllowedTools = { readonly "mode": "auto" | "required"; readonly "tools": ReadonlyArray<{}> } +export const ChatCompletionAllowedTools = Schema.Struct({ + "mode": Schema.Literals(["auto", "required"]).annotate({ + "description": + "Constrains the tools available to the model to a pre-defined set.\n\n`auto` allows the model to pick from among the allowed tools and generate a\nmessage.\n\n`required` requires the model to call one or more of the allowed tools.\n" + }), + "tools": Schema.Array( + Schema.Struct({}).annotate({ "description": "A tool definition that the model should be allowed to call.\n" }) + ).annotate({ + "description": + "A list of tool definitions that the model should be allowed to call.\n\nFor the Chat Completions API, the list of tool definitions might look like:\n```json\n[\n { \"type\": \"function\", \"function\": { \"name\": \"get_weather\" } },\n { \"type\": \"function\", \"function\": { \"name\": \"get_time\" } }\n]\n```\n" + }) +}).annotate({ + "title": "Allowed tools", + "description": "Constrains the tools available to the model to a pre-defined set.\n" +}) +export type ChatCompletionDeleted = { + readonly "object": "chat.completion.deleted" + readonly "id": string + readonly "deleted": boolean +} +export const ChatCompletionDeleted = Schema.Struct({ + "object": Schema.Literal("chat.completion.deleted").annotate({ "description": "The type of object being deleted." }), + "id": Schema.String.annotate({ "description": "The ID of the chat completion that was deleted." }), + "deleted": Schema.Boolean.annotate({ "description": "Whether the chat completion was deleted." }) +}) +export type ChatCompletionFunctionCallOption = { readonly "name": string } +export const ChatCompletionFunctionCallOption = Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the function to call." }) +}).annotate({ + "description": + "Specifying a particular function via `{\"name\": \"my_function\"}` forces the model to call that function.\n" +}) +export type ChatCompletionMessageCustomToolCall = { + readonly "id": string + readonly "type": "custom" + readonly "custom": { readonly "name": string; readonly "input": string } +} +export const ChatCompletionMessageCustomToolCall = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The ID of the tool call." }), + "type": Schema.Literal("custom").annotate({ "description": "The type of the tool. Always `custom`." }), + "custom": Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the custom tool to call." }), + "input": Schema.String.annotate({ "description": "The input for the custom tool call generated by the model." }) + }).annotate({ "description": "The custom tool that the model called." }) +}).annotate({ "title": "Custom tool call", "description": "A call to a custom tool created by the model.\n" }) +export type ChatCompletionMessageToolCall = { + readonly "id": string + readonly "type": "function" + readonly "function": { readonly "name": string; readonly "arguments": string } +} +export const ChatCompletionMessageToolCall = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The ID of the tool call." }), + "type": Schema.Literal("function").annotate({ + "description": "The type of the tool. Currently, only `function` is supported." + }), + "function": Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the function to call." }), + "arguments": Schema.String.annotate({ + "description": + "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + }) + }).annotate({ "description": "The function that the model called." }) +}).annotate({ "title": "Function tool call", "description": "A call to a function tool created by the model.\n" }) +export type ChatCompletionMessageToolCallChunk = { + readonly "index": number + readonly "id"?: string + readonly "type"?: "function" + readonly "function"?: { readonly "name"?: string; readonly "arguments"?: string } +} +export const ChatCompletionMessageToolCallChunk = Schema.Struct({ + "index": Schema.Number.check(Schema.isInt()), + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the tool call." })), + "type": Schema.optionalKey( + Schema.Literal("function").annotate({ + "description": "The type of the tool. Currently, only `function` is supported." + }) + ), + "function": Schema.optionalKey(Schema.Struct({ + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the function to call." })), + "arguments": Schema.optionalKey(Schema.String.annotate({ + "description": + "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + })) + })) +}) +export type ChatCompletionNamedToolChoice = { + readonly "type": "function" + readonly "function": { readonly "name": string } +} +export const ChatCompletionNamedToolChoice = Schema.Struct({ + "type": Schema.Literal("function").annotate({ + "description": "For function calling, the type is always `function`." + }), + "function": Schema.Struct({ "name": Schema.String.annotate({ "description": "The name of the function to call." }) }) +}).annotate({ + "title": "Function tool choice", + "description": "Specifies a tool the model should use. Use to force the model to call a specific function." +}) +export type ChatCompletionNamedToolChoiceCustom = { + readonly "type": "custom" + readonly "custom": { readonly "name": string } +} +export const ChatCompletionNamedToolChoiceCustom = Schema.Struct({ + "type": Schema.Literal("custom").annotate({ "description": "For custom tool calling, the type is always `custom`." }), + "custom": Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the custom tool to call." }) + }) +}).annotate({ + "title": "Custom tool choice", + "description": "Specifies a tool the model should use. Use to force the model to call a specific custom tool." +}) +export type ChatCompletionRequestFunctionMessage = { + readonly "role": "function" + readonly "content": string | null + readonly "name": string +} +export const ChatCompletionRequestFunctionMessage = Schema.Struct({ + "role": Schema.Literal("function").annotate({ + "description": "The role of the messages author, in this case `function`." + }), + "content": Schema.Union([ + Schema.String.annotate({ "description": "The contents of the function message." }), + Schema.Null + ]), + "name": Schema.String.annotate({ "description": "The name of the function to call." }) +}).annotate({ "title": "Function message" }) +export type ChatCompletionRequestMessageContentPartAudio = { + readonly "type": "input_audio" + readonly "input_audio": { readonly "data": string; readonly "format": "wav" | "mp3" } +} +export const ChatCompletionRequestMessageContentPartAudio = Schema.Struct({ + "type": Schema.Literal("input_audio").annotate({ + "description": "The type of the content part. Always `input_audio`." + }), + "input_audio": Schema.Struct({ + "data": Schema.String.annotate({ "description": "Base64 encoded audio data." }), + "format": Schema.Literals(["wav", "mp3"]).annotate({ + "description": "The format of the encoded audio data. Currently supports \"wav\" and \"mp3\".\n" + }) + }) +}).annotate({ "title": "Audio content part", "description": "Learn about [audio inputs](/docs/guides/audio).\n" }) +export type ChatCompletionRequestMessageContentPartFile = { + readonly "type": "file" + readonly "file": { readonly "filename"?: string; readonly "file_data"?: string; readonly "file_id"?: string } +} +export const ChatCompletionRequestMessageContentPartFile = Schema.Struct({ + "type": Schema.Literal("file").annotate({ "description": "The type of the content part. Always `file`." }), + "file": Schema.Struct({ + "filename": Schema.optionalKey( + Schema.String.annotate({ + "description": "The name of the file, used when passing the file to the model as a \nstring.\n" + }) + ), + "file_data": Schema.optionalKey( + Schema.String.annotate({ + "description": "The base64 encoded file data, used when passing the file to the model \nas a string.\n" + }) + ), + "file_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of an uploaded file to use as input.\n" }) + ) + }) +}).annotate({ + "title": "File content part", + "description": "Learn about [file inputs](/docs/guides/text) for text generation.\n" +}) +export type ChatCompletionRequestMessageContentPartImage = { + readonly "type": "image_url" + readonly "image_url": { readonly "url": string; readonly "detail"?: "auto" | "low" | "high" } +} +export const ChatCompletionRequestMessageContentPartImage = Schema.Struct({ + "type": Schema.Literal("image_url").annotate({ "description": "The type of the content part." }), + "image_url": Schema.Struct({ + "url": Schema.String.annotate({ + "description": "Either a URL of the image or the base64 encoded image data.", + "format": "uri" + }), + "detail": Schema.optionalKey( + Schema.Literals(["auto", "low", "high"]).annotate({ + "description": + "Specifies the detail level of the image. Learn more in the [Vision guide](/docs/guides/vision#low-or-high-fidelity-image-understanding)." + }) + ) + }) +}).annotate({ "title": "Image content part", "description": "Learn about [image inputs](/docs/guides/vision).\n" }) +export type ChatCompletionRequestMessageContentPartRefusal = { readonly "type": "refusal"; readonly "refusal": string } +export const ChatCompletionRequestMessageContentPartRefusal = Schema.Struct({ + "type": Schema.Literal("refusal").annotate({ "description": "The type of the content part." }), + "refusal": Schema.String.annotate({ "description": "The refusal message generated by the model." }) +}).annotate({ "title": "Refusal content part" }) +export type ChatCompletionRequestMessageContentPartText = { readonly "type": "text"; readonly "text": string } +export const ChatCompletionRequestMessageContentPartText = Schema.Struct({ + "type": Schema.Literal("text").annotate({ "description": "The type of the content part." }), + "text": Schema.String.annotate({ "description": "The text content." }) +}).annotate({ + "title": "Text content part", + "description": "Learn about [text inputs](/docs/guides/text-generation).\n" +}) +export type ChatCompletionStreamOptions = { + readonly "include_usage"?: boolean + readonly "include_obfuscation"?: boolean +} | null +export const ChatCompletionStreamOptions = Schema.Union([ + Schema.Struct({ + "include_usage": Schema.optionalKey(Schema.Boolean.annotate({ + "description": + "If set, an additional chunk will be streamed before the `data: [DONE]`\nmessage. The `usage` field on this chunk shows the token usage statistics\nfor the entire request, and the `choices` field will always be an empty\narray.\n\nAll other chunks will also include a `usage` field, but with a null\nvalue. **NOTE:** If the stream is interrupted, you may not receive the\nfinal usage chunk which contains the total token usage for the request.\n" + })), + "include_obfuscation": Schema.optionalKey(Schema.Boolean.annotate({ + "description": + "When true, stream obfuscation will be enabled. Stream obfuscation adds\nrandom characters to an `obfuscation` field on streaming delta events to\nnormalize payload sizes as a mitigation to certain side-channel attacks.\nThese obfuscation fields are included by default, but add a small amount\nof overhead to the data stream. You can set `include_obfuscation` to\nfalse to optimize for bandwidth if you trust the network links between\nyour application and the OpenAI API.\n" + })) + }).annotate({ "description": "Options for streaming response. Only set this when you set `stream: true`.\n" }), + Schema.Null +]) +export type ChatCompletionTokenLogprob = { + readonly "token": string + readonly "logprob": number + readonly "bytes": ReadonlyArray | null + readonly "top_logprobs": ReadonlyArray< + { readonly "token": string; readonly "logprob": number; readonly "bytes": ReadonlyArray | null } + > +} +export const ChatCompletionTokenLogprob = Schema.Struct({ + "token": Schema.String.annotate({ "description": "The token." }), + "logprob": Schema.Number.annotate({ + "description": + "The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." + }).check(Schema.isFinite()), + "bytes": Schema.Union([ + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": + "A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." + }), + Schema.Null + ]), + "top_logprobs": Schema.Array(Schema.Struct({ + "token": Schema.String.annotate({ "description": "The token." }), + "logprob": Schema.Number.annotate({ + "description": + "The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." + }).check(Schema.isFinite()), + "bytes": Schema.Union([ + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": + "A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." + }), + Schema.Null + ]) + })).annotate({ + "description": + "List of the most likely tokens and their log probability, at this token position. The number of entries may be fewer than the requested `top_logprobs`." + }) +}) +export type ComparisonFilter = { + readonly "type": "eq" | "ne" | "gt" | "gte" | "lt" | "lte" | "in" | "nin" + readonly "key": string + readonly "value": string | number | boolean | ReadonlyArray +} +export const ComparisonFilter = Schema.Struct({ + "type": Schema.Literals(["eq", "ne", "gt", "gte", "lt", "lte", "in", "nin"]).annotate({ + "description": + "Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`.\n- `eq`: equals\n- `ne`: not equal\n- `gt`: greater than\n- `gte`: greater than or equal\n- `lt`: less than\n- `lte`: less than or equal\n- `in`: in\n- `nin`: not in\n" + }), + "key": Schema.String.annotate({ "description": "The key to compare against the value." }), + "value": Schema.Union([ + Schema.String, + Schema.Number.check(Schema.isFinite()), + Schema.Boolean, + Schema.Array(Schema.Union([Schema.String, Schema.Number.check(Schema.isFinite())], { mode: "oneOf" })) + ], { mode: "oneOf" }).annotate({ + "description": "The value to compare against the attribute key; supports string, number, or boolean types." + }) +}).annotate({ + "title": "Comparison Filter", + "description": + "A filter used to compare a specified attribute key to a given value using a defined comparison operation.\n" +}) +export type CompleteUploadRequest = { readonly "part_ids": ReadonlyArray; readonly "md5"?: string } +export const CompleteUploadRequest = Schema.Struct({ + "part_ids": Schema.Array(Schema.String).annotate({ "description": "The ordered list of Part IDs.\n" }), + "md5": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The optional md5 checksum for the file contents to verify if the bytes uploaded matches what you expect.\n" + }) + ) +}) +export type CompletionUsage = { + readonly "completion_tokens": number + readonly "prompt_tokens": number + readonly "total_tokens": number + readonly "completion_tokens_details"?: { + readonly "accepted_prediction_tokens"?: number + readonly "audio_tokens"?: number + readonly "reasoning_tokens"?: number + readonly "rejected_prediction_tokens"?: number + } + readonly "prompt_tokens_details"?: { readonly "audio_tokens"?: number; readonly "cached_tokens"?: number } +} +export const CompletionUsage = Schema.Struct({ + "completion_tokens": Schema.Number.annotate({ "description": "Number of tokens in the generated completion." }).check( + Schema.isInt() + ), + "prompt_tokens": Schema.Number.annotate({ "description": "Number of tokens in the prompt." }).check(Schema.isInt()), + "total_tokens": Schema.Number.annotate({ + "description": "Total number of tokens used in the request (prompt + completion)." + }).check(Schema.isInt()), + "completion_tokens_details": Schema.optionalKey( + Schema.Struct({ + "accepted_prediction_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "When using Predicted Outputs, the number of tokens in the\nprediction that appeared in the completion.\n" + }).check(Schema.isInt()) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Audio input tokens generated by the model." }).check(Schema.isInt()) + ), + "reasoning_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Tokens generated by the model for reasoning." }).check(Schema.isInt()) + ), + "rejected_prediction_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "When using Predicted Outputs, the number of tokens in the\nprediction that did not appear in the completion. However, like\nreasoning tokens, these tokens are still counted in the total\ncompletion tokens for purposes of billing, output, and context window\nlimits.\n" + }).check(Schema.isInt()) + ) + }).annotate({ "description": "Breakdown of tokens used in a completion." }) + ), + "prompt_tokens_details": Schema.optionalKey( + Schema.Struct({ + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Audio input tokens present in the prompt." }).check(Schema.isInt()) + ), + "cached_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Cached tokens present in the prompt." }).check(Schema.isInt()) + ) + }).annotate({ "description": "Breakdown of tokens used in the prompt." }) + ) +}).annotate({ "description": "Usage statistics for the completion request." }) +export type ComputerScreenshotImage = { + readonly "type": "computer_screenshot" + readonly "image_url"?: string + readonly "file_id"?: string +} +export const ComputerScreenshotImage = Schema.Struct({ + "type": Schema.Literal("computer_screenshot").annotate({ + "description": + "Specifies the event type. For a computer screenshot, this property is \nalways set to `computer_screenshot`.\n" + }), + "image_url": Schema.optionalKey( + Schema.String.annotate({ "description": "The URL of the screenshot image.", "format": "uri" }) + ), + "file_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of an uploaded file that contains the screenshot." }) + ) +}).annotate({ "description": "A computer screenshot image used with the computer use tool.\n" }) +export type ContainerFileResource = { + readonly "id": string + readonly "object": string + readonly "container_id": string + readonly "created_at": number + readonly "bytes": number + readonly "path": string + readonly "source": string +} +export const ContainerFileResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Unique identifier for the file." }), + "object": Schema.String.annotate({ "description": "The type of this object (`container.file`)." }), + "container_id": Schema.String.annotate({ "description": "The container this file belongs to." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the file was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "bytes": Schema.Number.annotate({ "description": "Size of the file in bytes." }).check(Schema.isInt()), + "path": Schema.String.annotate({ "description": "Path of the file in the container." }), + "source": Schema.String.annotate({ "description": "Source of the file (e.g., `user`, `assistant`)." }) +}).annotate({ "title": "The container file object" }) +export type ContainerResource = { + readonly "id": string + readonly "object": string + readonly "name": string + readonly "created_at": number + readonly "status": string + readonly "last_active_at"?: number + readonly "expires_after"?: { readonly "anchor"?: "last_active_at"; readonly "minutes"?: number } + readonly "memory_limit"?: "1g" | "4g" | "16g" | "64g" + readonly "network_policy"?: { + readonly "type": "allowlist" | "disabled" + readonly "allowed_domains"?: ReadonlyArray + } +} +export const ContainerResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Unique identifier for the container." }), + "object": Schema.String.annotate({ "description": "The type of this object." }), + "name": Schema.String.annotate({ "description": "Name of the container." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the container was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "status": Schema.String.annotate({ "description": "Status of the container (e.g., active, deleted)." }), + "last_active_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the container was last active.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "expires_after": Schema.optionalKey( + Schema.Struct({ + "anchor": Schema.optionalKey( + Schema.Literal("last_active_at").annotate({ "description": "The reference point for the expiration." }) + ), + "minutes": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of minutes after the anchor before the container expires." + }).check(Schema.isInt()) + ) + }).annotate({ + "description": + "The container will expire after this time period.\nThe anchor is the reference point for the expiration.\nThe minutes is the number of minutes after the anchor before the container expires.\n" + }) + ), + "memory_limit": Schema.optionalKey( + Schema.Literals(["1g", "4g", "16g", "64g"]).annotate({ + "description": "The memory limit configured for the container." + }) + ), + "network_policy": Schema.optionalKey( + Schema.Struct({ + "type": Schema.Literals(["allowlist", "disabled"]).annotate({ "description": "The network policy mode." }), + "allowed_domains": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ "description": "Allowed outbound domains when `type` is `allowlist`." }) + ) + }).annotate({ "description": "Network access policy for the container." }) + ) +}).annotate({ "title": "The container object" }) +export type CostsResult = { + readonly "object": "organization.costs.result" + readonly "amount"?: { readonly "value"?: number; readonly "currency"?: string } + readonly "line_item"?: string | null + readonly "project_id"?: string | null + readonly "api_key_id"?: string | null + readonly "quantity"?: number | null +} +export const CostsResult = Schema.Struct({ + "object": Schema.Literal("organization.costs.result"), + "amount": Schema.optionalKey( + Schema.Struct({ + "value": Schema.optionalKey( + Schema.Number.annotate({ "description": "The numeric value of the cost." }).check(Schema.isFinite()) + ), + "currency": Schema.optionalKey( + Schema.String.annotate({ "description": "Lowercase ISO-4217 currency e.g. \"usd\"" }) + ) + }).annotate({ "description": "The monetary value in its associated currency." }) + ), + "line_item": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=line_item`, this field provides the line item of the grouped costs result." + }), + Schema.Null + ]) + ), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped costs result." + }), + Schema.Null + ]) + ), + "api_key_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=api_key_id`, this field provides the API Key ID of the grouped costs result." + }), + Schema.Null + ]) + ), + "quantity": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "When `group_by=line_item`, this field provides the quantity of the grouped costs result." + }).check(Schema.isFinite()), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated costs details of the specific time bucket." }) +export type CreateContainerFileBody = { readonly "file_id"?: string; readonly "file"?: string } +export const CreateContainerFileBody = Schema.Struct({ + "file_id": Schema.optionalKey(Schema.String.annotate({ "description": "Name of the file to create." })), + "file": Schema.optionalKey( + Schema.String.annotate({ "description": "The File object (not file name) to be uploaded.\n", "format": "binary" }) + ) +}) +export type CreateEmbeddingRequest = { + readonly "input": string | ReadonlyArray | ReadonlyArray | ReadonlyArray> + readonly "model": string | "text-embedding-ada-002" | "text-embedding-3-small" | "text-embedding-3-large" + readonly "encoding_format"?: "float" | "base64" + readonly "dimensions"?: number + readonly "user"?: string +} +export const CreateEmbeddingRequest = Schema.Struct({ + "input": Schema.Union([ + Schema.String.annotate({ "title": "string", "description": "The string that will be turned into an embedding." }), + Schema.Array(Schema.String).annotate({ + "title": "array", + "description": "The array of strings that will be turned into an embedding." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(2048)), + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "title": "array", + "description": "The array of integers that will be turned into an embedding." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(2048)), + Schema.Array(Schema.Array(Schema.Number.check(Schema.isInt())).check(Schema.isMinLength(1))).annotate({ + "title": "array", + "description": "The array of arrays containing integers that will be turned into an embedding." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(2048)) + ], { mode: "oneOf" }).annotate({ + "description": + "Input text to embed, encoded as a string or array of tokens. To embed multiple inputs in a single request, pass an array of strings or array of token arrays. The input must not exceed the max input tokens for the model (8192 tokens for all embedding models), cannot be an empty string, and any array must be 2048 dimensions or less. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens. In addition to the per-input token limit, all embedding models enforce a maximum of 300,000 tokens summed across all inputs in a single request.\n" + }), + "model": Schema.Union([ + Schema.String, + Schema.Literals(["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]) + ]).annotate({ + "description": + "ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models) for descriptions of them.\n" + }), + "encoding_format": Schema.optionalKey( + Schema.Literals(["float", "base64"]).annotate({ + "description": + "The format to return the embeddings in. Can be either `float` or [`base64`](https://pypi.org/project/pybase64/)." + }) + ), + "dimensions": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The number of dimensions the resulting output embeddings should have. Only supported in `text-embedding-3` and later models.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)) + ), + "user": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices#end-user-ids).\n" + }) + ) +}) +export type CreateFineTuningCheckpointPermissionRequest = { readonly "project_ids": ReadonlyArray } +export const CreateFineTuningCheckpointPermissionRequest = Schema.Struct({ + "project_ids": Schema.Array(Schema.String).annotate({ "description": "The project identifiers to grant access to." }) +}) +export type CreateGroupBody = { readonly "name": string } +export const CreateGroupBody = Schema.Struct({ + "name": Schema.String.annotate({ "description": "Human readable name for the group." }).check(Schema.isMinLength(1)) + .check(Schema.isMaxLength(255)) +}).annotate({ "description": "Request payload for creating a new group in the organization." }) +export type CreateGroupUserBody = { readonly "user_id": string } +export const CreateGroupUserBody = Schema.Struct({ + "user_id": Schema.String.annotate({ "description": "Identifier of the user to add to the group." }) +}).annotate({ "description": "Request payload for adding a user to a group." }) +export type CreateImageVariationRequest = { + readonly "image": string + readonly "model"?: string | "dall-e-2" | null + readonly "n"?: number + readonly "response_format"?: "url" | "b64_json" | null + readonly "size"?: "256x256" | "512x512" | "1024x1024" | null + readonly "user"?: string +} +export const CreateImageVariationRequest = Schema.Struct({ + "image": Schema.String.annotate({ + "description": + "The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square.", + "format": "binary" + }), + "model": Schema.optionalKey( + Schema.Union([ + Schema.Union([Schema.String, Schema.Literal("dall-e-2")]).annotate({ + "description": "The model to use for image generation. Only `dall-e-2` is supported at this time." + }), + Schema.Null + ]) + ), + "n": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(10)], { + "description": "The number of images to generate. Must be between 1 and 10." + }) + ) + ]) + ), + "response_format": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["url", "b64_json"]).annotate({ + "description": + "The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated." + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated." + }) + ]) + ), + "size": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["256x256", "512x512", "1024x1024"]).annotate({ + "description": "The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`." + }), + Schema.Union([Schema.Null]).annotate({ + "description": "The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`." + }) + ]) + ), + "user": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices#end-user-ids).\n" + }) + ) +}) +export type CreateModerationRequest = { + readonly "input": + | string + | ReadonlyArray + | ReadonlyArray< + { readonly "type": "image_url"; readonly "image_url": { readonly "url": string } } | { + readonly "type": "text" + readonly "text": string + } + > + readonly "model"?: + | string + | "omni-moderation-latest" + | "omni-moderation-2024-09-26" + | "text-moderation-latest" + | "text-moderation-stable" +} +export const CreateModerationRequest = Schema.Struct({ + "input": Schema.Union([ + Schema.String.annotate({ "description": "A string of text to classify for moderation." }), + Schema.Array(Schema.String).annotate({ "description": "An array of strings to classify for moderation." }), + Schema.Array(Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("image_url").annotate({ "description": "Always `image_url`." }), + "image_url": Schema.Struct({ + "url": Schema.String.annotate({ + "description": "Either a URL of the image or the base64 encoded image data.", + "format": "uri" + }) + }).annotate({ "description": "Contains either an image URL or a data URL for a base64 encoded image." }) + }).annotate({ "description": "An object describing an image to classify." }), + Schema.Struct({ + "type": Schema.Literal("text").annotate({ "description": "Always `text`." }), + "text": Schema.String.annotate({ "description": "A string of text to classify." }) + }).annotate({ "description": "An object describing text to classify." }) + ], { mode: "oneOf" })).annotate({ "description": "An array of multi-modal inputs to the moderation model." }) + ], { mode: "oneOf" }).annotate({ + "description": + "Input (or inputs) to classify. Can be a single string, an array of strings, or\nan array of multi-modal input objects similar to other models.\n" + }), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "omni-moderation-latest", + "omni-moderation-2024-09-26", + "text-moderation-latest", + "text-moderation-stable" + ]) + ]).annotate({ + "description": + "The content moderation model you would like to use. Learn more in\n[the moderation guide](/docs/guides/moderation), and learn about\navailable models [here](/docs/models#moderation).\n" + }) + ) +}) +export type CreateModerationResponse = { + readonly "id": string + readonly "model": string + readonly "results": ReadonlyArray< + { + readonly "flagged": boolean + readonly "categories": { + readonly "hate": boolean + readonly "hate/threatening": boolean + readonly "harassment": boolean + readonly "harassment/threatening": boolean + readonly "illicit": boolean | null + readonly "illicit/violent": boolean | null + readonly "self-harm": boolean + readonly "self-harm/intent": boolean + readonly "self-harm/instructions": boolean + readonly "sexual": boolean + readonly "sexual/minors": boolean + readonly "violence": boolean + readonly "violence/graphic": boolean + } + readonly "category_scores": { + readonly "hate": number + readonly "hate/threatening": number + readonly "harassment": number + readonly "harassment/threatening": number + readonly "illicit": number + readonly "illicit/violent": number + readonly "self-harm": number + readonly "self-harm/intent": number + readonly "self-harm/instructions": number + readonly "sexual": number + readonly "sexual/minors": number + readonly "violence": number + readonly "violence/graphic": number + } + readonly "category_applied_input_types": { + readonly "hate": ReadonlyArray<"text"> + readonly "hate/threatening": ReadonlyArray<"text"> + readonly "harassment": ReadonlyArray<"text"> + readonly "harassment/threatening": ReadonlyArray<"text"> + readonly "illicit": ReadonlyArray<"text"> + readonly "illicit/violent": ReadonlyArray<"text"> + readonly "self-harm": ReadonlyArray<"text" | "image"> + readonly "self-harm/intent": ReadonlyArray<"text" | "image"> + readonly "self-harm/instructions": ReadonlyArray<"text" | "image"> + readonly "sexual": ReadonlyArray<"text" | "image"> + readonly "sexual/minors": ReadonlyArray<"text"> + readonly "violence": ReadonlyArray<"text" | "image"> + readonly "violence/graphic": ReadonlyArray<"text" | "image"> + } + } + > +} +export const CreateModerationResponse = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique identifier for the moderation request." }), + "model": Schema.String.annotate({ "description": "The model used to generate the moderation results." }), + "results": Schema.Array(Schema.Struct({ + "flagged": Schema.Boolean.annotate({ "description": "Whether any of the below categories are flagged." }), + "categories": Schema.Struct({ + "hate": Schema.Boolean.annotate({ + "description": + "Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is harassment." + }), + "hate/threatening": Schema.Boolean.annotate({ + "description": + "Hateful content that also includes violence or serious harm towards the targeted group based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste." + }), + "harassment": Schema.Boolean.annotate({ + "description": "Content that expresses, incites, or promotes harassing language towards any target." + }), + "harassment/threatening": Schema.Boolean.annotate({ + "description": "Harassment content that also includes violence or serious harm towards any target." + }), + "illicit": Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Content that includes instructions or advice that facilitate the planning or execution of wrongdoing, or that gives advice or instruction on how to commit illicit acts. For example, \"how to shoplift\" would fit this category." + }), + Schema.Null + ]), + "illicit/violent": Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Content that includes instructions or advice that facilitate the planning or execution of wrongdoing that also includes violence, or that gives advice or instruction on the procurement of any weapon." + }), + Schema.Null + ]), + "self-harm": Schema.Boolean.annotate({ + "description": + "Content that promotes, encourages, or depicts acts of self-harm, such as suicide, cutting, and eating disorders." + }), + "self-harm/intent": Schema.Boolean.annotate({ + "description": + "Content where the speaker expresses that they are engaging or intend to engage in acts of self-harm, such as suicide, cutting, and eating disorders." + }), + "self-harm/instructions": Schema.Boolean.annotate({ + "description": + "Content that encourages performing acts of self-harm, such as suicide, cutting, and eating disorders, or that gives instructions or advice on how to commit such acts." + }), + "sexual": Schema.Boolean.annotate({ + "description": + "Content meant to arouse sexual excitement, such as the description of sexual activity, or that promotes sexual services (excluding sex education and wellness)." + }), + "sexual/minors": Schema.Boolean.annotate({ + "description": "Sexual content that includes an individual who is under 18 years old." + }), + "violence": Schema.Boolean.annotate({ + "description": "Content that depicts death, violence, or physical injury." + }), + "violence/graphic": Schema.Boolean.annotate({ + "description": "Content that depicts death, violence, or physical injury in graphic detail." + }) + }).annotate({ "description": "A list of the categories, and whether they are flagged or not." }), + "category_scores": Schema.Struct({ + "hate": Schema.Number.annotate({ "description": "The score for the category 'hate'." }).check(Schema.isFinite()), + "hate/threatening": Schema.Number.annotate({ "description": "The score for the category 'hate/threatening'." }) + .check(Schema.isFinite()), + "harassment": Schema.Number.annotate({ "description": "The score for the category 'harassment'." }).check( + Schema.isFinite() + ), + "harassment/threatening": Schema.Number.annotate({ + "description": "The score for the category 'harassment/threatening'." + }).check(Schema.isFinite()), + "illicit": Schema.Number.annotate({ "description": "The score for the category 'illicit'." }).check( + Schema.isFinite() + ), + "illicit/violent": Schema.Number.annotate({ "description": "The score for the category 'illicit/violent'." }) + .check(Schema.isFinite()), + "self-harm": Schema.Number.annotate({ "description": "The score for the category 'self-harm'." }).check( + Schema.isFinite() + ), + "self-harm/intent": Schema.Number.annotate({ "description": "The score for the category 'self-harm/intent'." }) + .check(Schema.isFinite()), + "self-harm/instructions": Schema.Number.annotate({ + "description": "The score for the category 'self-harm/instructions'." + }).check(Schema.isFinite()), + "sexual": Schema.Number.annotate({ "description": "The score for the category 'sexual'." }).check( + Schema.isFinite() + ), + "sexual/minors": Schema.Number.annotate({ "description": "The score for the category 'sexual/minors'." }).check( + Schema.isFinite() + ), + "violence": Schema.Number.annotate({ "description": "The score for the category 'violence'." }).check( + Schema.isFinite() + ), + "violence/graphic": Schema.Number.annotate({ "description": "The score for the category 'violence/graphic'." }) + .check(Schema.isFinite()) + }).annotate({ "description": "A list of the categories along with their scores as predicted by model." }), + "category_applied_input_types": Schema.Struct({ + "hate": Schema.Array(Schema.Literal("text")).annotate({ + "description": "The applied input type(s) for the category 'hate'." + }), + "hate/threatening": Schema.Array(Schema.Literal("text")).annotate({ + "description": "The applied input type(s) for the category 'hate/threatening'." + }), + "harassment": Schema.Array(Schema.Literal("text")).annotate({ + "description": "The applied input type(s) for the category 'harassment'." + }), + "harassment/threatening": Schema.Array(Schema.Literal("text")).annotate({ + "description": "The applied input type(s) for the category 'harassment/threatening'." + }), + "illicit": Schema.Array(Schema.Literal("text")).annotate({ + "description": "The applied input type(s) for the category 'illicit'." + }), + "illicit/violent": Schema.Array(Schema.Literal("text")).annotate({ + "description": "The applied input type(s) for the category 'illicit/violent'." + }), + "self-harm": Schema.Array(Schema.Literals(["text", "image"])).annotate({ + "description": "The applied input type(s) for the category 'self-harm'." + }), + "self-harm/intent": Schema.Array(Schema.Literals(["text", "image"])).annotate({ + "description": "The applied input type(s) for the category 'self-harm/intent'." + }), + "self-harm/instructions": Schema.Array(Schema.Literals(["text", "image"])).annotate({ + "description": "The applied input type(s) for the category 'self-harm/instructions'." + }), + "sexual": Schema.Array(Schema.Literals(["text", "image"])).annotate({ + "description": "The applied input type(s) for the category 'sexual'." + }), + "sexual/minors": Schema.Array(Schema.Literal("text")).annotate({ + "description": "The applied input type(s) for the category 'sexual/minors'." + }), + "violence": Schema.Array(Schema.Literals(["text", "image"])).annotate({ + "description": "The applied input type(s) for the category 'violence'." + }), + "violence/graphic": Schema.Array(Schema.Literals(["text", "image"])).annotate({ + "description": "The applied input type(s) for the category 'violence/graphic'." + }) + }).annotate({ "description": "A list of the categories along with the input type(s) that the score applies to." }) + })).annotate({ "description": "A list of moderation objects." }) +}).annotate({ "description": "Represents if a given text input is potentially harmful." }) +export type CreateTranscriptionResponseJson = { + readonly "text": string + readonly "logprobs"?: ReadonlyArray< + { readonly "token"?: string; readonly "logprob"?: number; readonly "bytes"?: ReadonlyArray } + > + readonly "usage"?: { + readonly "type": "tokens" + readonly "input_tokens": number + readonly "input_token_details"?: { readonly "text_tokens"?: number; readonly "audio_tokens"?: number } + readonly "output_tokens": number + readonly "total_tokens": number + } | { readonly "type": "duration"; readonly "seconds": number } +} +export const CreateTranscriptionResponseJson = Schema.Struct({ + "text": Schema.String.annotate({ "description": "The transcribed text." }), + "logprobs": Schema.optionalKey( + Schema.Array(Schema.Struct({ + "token": Schema.optionalKey(Schema.String.annotate({ "description": "The token in the transcription." })), + "logprob": Schema.optionalKey( + Schema.Number.annotate({ "description": "The log probability of the token." }).check(Schema.isFinite()) + ), + "bytes": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isFinite())).annotate({ "description": "The bytes of the token." }) + ) + })).annotate({ + "description": + "The log probabilities of the tokens in the transcription. Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` array.\n" + }) + ), + "usage": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("tokens").annotate({ + "description": "The type of the usage object. Always `tokens` for this variant." + }), + "input_tokens": Schema.Number.annotate({ "description": "Number of input tokens billed for this request." }) + .check(Schema.isInt()), + "input_token_details": Schema.optionalKey( + Schema.Struct({ + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Number of text tokens billed for this request." }).check( + Schema.isInt() + ) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Number of audio tokens billed for this request." }).check( + Schema.isInt() + ) + ) + }).annotate({ "description": "Details about the input tokens billed for this request." }) + ), + "output_tokens": Schema.Number.annotate({ "description": "Number of output tokens generated." }).check( + Schema.isInt() + ), + "total_tokens": Schema.Number.annotate({ "description": "Total number of tokens used (input + output)." }).check( + Schema.isInt() + ) + }).annotate({ "title": "Token Usage", "description": "Token usage statistics for the request." }), + Schema.Struct({ + "type": Schema.Literal("duration").annotate({ + "description": "The type of the usage object. Always `duration` for this variant." + }), + "seconds": Schema.Number.annotate({ + "description": "Duration of the input audio in seconds.", + "format": "double" + }).check(Schema.isFinite()) + }).annotate({ "title": "Duration Usage", "description": "Token usage statistics for the request." }) + ], { mode: "oneOf" })) +}).annotate({ "description": "Represents a transcription response returned by model, based on the provided input." }) +export type CreateTranslationRequest = { + readonly "file": string + readonly "model": string | "whisper-1" + readonly "prompt"?: string + readonly "response_format"?: "json" | "text" | "srt" | "verbose_json" | "vtt" + readonly "temperature"?: number +} +export const CreateTranslationRequest = Schema.Struct({ + "file": Schema.String.annotate({ + "description": + "The audio file object (not file name) translate, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n", + "format": "binary" + }), + "model": Schema.Union([Schema.String, Schema.Literal("whisper-1")]).annotate({ + "description": + "ID of the model to use. Only `whisper-1` (which is powered by our open source Whisper V2 model) is currently available.\n" + }), + "prompt": Schema.optionalKey( + Schema.String.annotate({ + "description": + "An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text#prompting) should be in English.\n" + }) + ), + "response_format": Schema.optionalKey( + Schema.Literals(["json", "text", "srt", "verbose_json", "vtt"]).annotate({ + "description": + "The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`.\n" + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n" + }).check(Schema.isFinite()) + ) +}) +export type CreateTranslationResponseJson = { readonly "text": string } +export const CreateTranslationResponseJson = Schema.Struct({ "text": Schema.String }) +export type CreateVoiceConsentRequest = { + readonly "name": string + readonly "recording": string + readonly "language": string +} +export const CreateVoiceConsentRequest = Schema.Struct({ + "name": Schema.String.annotate({ "description": "The label to use for this consent recording." }), + "recording": Schema.String.annotate({ + "description": + "The consent audio recording file. Maximum size is 10 MiB.\n\nSupported MIME types:\n`audio/mpeg`, `audio/wav`, `audio/x-wav`, `audio/ogg`, `audio/aac`, `audio/flac`, `audio/webm`, `audio/mp4`.\n", + "format": "binary" + }), + "language": Schema.String.annotate({ + "description": "The BCP 47 language tag for the consent phrase (for example, `en-US`)." + }) +}) +export type CreateVoiceRequest = { + readonly "name": string + readonly "audio_sample": string + readonly "consent": string +} +export const CreateVoiceRequest = Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the new voice." }), + "audio_sample": Schema.String.annotate({ + "description": + "The sample audio recording file. Maximum size is 10 MiB.\n\nSupported MIME types:\n`audio/mpeg`, `audio/wav`, `audio/x-wav`, `audio/ogg`, `audio/aac`, `audio/flac`, `audio/webm`, `audio/mp4`.\n", + "format": "binary" + }), + "consent": Schema.String.annotate({ "description": "The consent recording ID (for example, `cons_1234`)." }) +}) +export type CustomToolCall = { + readonly "type": "custom_tool_call" + readonly "id"?: string + readonly "call_id": string + readonly "namespace"?: string + readonly "name": string + readonly "input": string +} +export const CustomToolCall = Schema.Struct({ + "type": Schema.Literal("custom_tool_call").annotate({ + "description": "The type of the custom tool call. Always `custom_tool_call`.\n" + }), + "id": Schema.optionalKey( + Schema.String.annotate({ "description": "The unique ID of the custom tool call in the OpenAI platform.\n" }) + ), + "call_id": Schema.String.annotate({ + "description": "An identifier used to map this custom tool call to a tool call output.\n" + }), + "namespace": Schema.optionalKey( + Schema.String.annotate({ "description": "The namespace of the custom tool being called.\n" }) + ), + "name": Schema.String.annotate({ "description": "The name of the custom tool being called.\n" }), + "input": Schema.String.annotate({ "description": "The input for the custom tool call generated by the model.\n" }) +}).annotate({ "title": "Custom tool call", "description": "A call to a custom tool created by the model.\n" }) +export type CustomToolCallResource = { + readonly "type": "custom_tool_call" + readonly "id": string + readonly "call_id": string + readonly "namespace"?: string + readonly "name": string + readonly "input": string + readonly "status": "in_progress" | "completed" | "incomplete" + readonly "created_by"?: string +} +export const CustomToolCallResource = Schema.Struct({ + "type": Schema.Literal("custom_tool_call").annotate({ + "description": "The type of the custom tool call. Always `custom_tool_call`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the custom tool call item.\n" }), + "call_id": Schema.String.annotate({ + "description": "An identifier used to map this custom tool call to a tool call output.\n" + }), + "namespace": Schema.optionalKey( + Schema.String.annotate({ "description": "The namespace of the custom tool being called.\n" }) + ), + "name": Schema.String.annotate({ "description": "The name of the custom tool being called.\n" }), + "input": Schema.String.annotate({ "description": "The input for the custom tool call generated by the model.\n" }), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item.\n" }) + ) +}).annotate({ "title": "Custom tool call", "description": "A call to a custom tool created by the model.\n" }) +export type CustomToolChatCompletions = { + readonly "type": "custom" + readonly "custom": { + readonly "name": string + readonly "description"?: string + readonly "format"?: { readonly "type": "text" } | { + readonly "type": "grammar" + readonly "grammar": { readonly "definition": string; readonly "syntax": "lark" | "regex" } + } + } +} +export const CustomToolChatCompletions = Schema.Struct({ + "type": Schema.Literal("custom").annotate({ "description": "The type of the custom tool. Always `custom`." }), + "custom": Schema.Struct({ + "name": Schema.String.annotate({ + "description": "The name of the custom tool, used to identify it in tool calls." + }), + "description": Schema.optionalKey( + Schema.String.annotate({ + "description": "Optional description of the custom tool, used to provide more context.\n" + }) + ), + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("text").annotate({ "description": "Unconstrained text format. Always `text`." }) + }).annotate({ "title": "Text format", "description": "Unconstrained free-form text." }), + Schema.Struct({ + "type": Schema.Literal("grammar").annotate({ "description": "Grammar format. Always `grammar`." }), + "grammar": Schema.Struct({ + "definition": Schema.String.annotate({ "description": "The grammar definition." }), + "syntax": Schema.Literals(["lark", "regex"]).annotate({ + "description": "The syntax of the grammar definition. One of `lark` or `regex`." + }) + }).annotate({ "title": "Grammar format", "description": "Your chosen grammar." }) + }).annotate({ "title": "Grammar format", "description": "A grammar defined by the user." }) + ], { mode: "oneOf" }).annotate({ + "description": "The input format for the custom tool. Default is unconstrained text.\n" + }) + ) + }).annotate({ "title": "Custom tool properties", "description": "Properties of the custom tool.\n" }) +}).annotate({ "title": "Custom tool", "description": "A custom tool that processes input using a specified format.\n" }) +export type DeleteAssistantResponse = { + readonly "id": string + readonly "deleted": boolean + readonly "object": "assistant.deleted" +} +export const DeleteAssistantResponse = Schema.Struct({ + "id": Schema.String, + "deleted": Schema.Boolean, + "object": Schema.Literal("assistant.deleted") +}) +export type DeleteCertificateResponse = { readonly "object": "certificate.deleted"; readonly "id": string } +export const DeleteCertificateResponse = Schema.Struct({ + "object": Schema.Literal("certificate.deleted").annotate({ + "description": "The object type, must be `certificate.deleted`." + }), + "id": Schema.String.annotate({ "description": "The ID of the certificate that was deleted." }) +}) +export type DeleteFileResponse = { readonly "id": string; readonly "object": "file"; readonly "deleted": boolean } +export const DeleteFileResponse = Schema.Struct({ + "id": Schema.String, + "object": Schema.Literal("file"), + "deleted": Schema.Boolean +}) +export type DeleteFineTuningCheckpointPermissionResponse = { + readonly "id": string + readonly "object": "checkpoint.permission" + readonly "deleted": boolean +} +export const DeleteFineTuningCheckpointPermissionResponse = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The ID of the fine-tuned model checkpoint permission that was deleted." + }), + "object": Schema.Literal("checkpoint.permission").annotate({ + "description": "The object type, which is always \"checkpoint.permission\"." + }), + "deleted": Schema.Boolean.annotate({ + "description": "Whether the fine-tuned model checkpoint permission was successfully deleted." + }) +}) +export type DeleteMessageResponse = { + readonly "id": string + readonly "deleted": boolean + readonly "object": "thread.message.deleted" +} +export const DeleteMessageResponse = Schema.Struct({ + "id": Schema.String, + "deleted": Schema.Boolean, + "object": Schema.Literal("thread.message.deleted") +}) +export type DeleteModelResponse = { readonly "id": string; readonly "deleted": boolean; readonly "object": string } +export const DeleteModelResponse = Schema.Struct({ + "id": Schema.String, + "deleted": Schema.Boolean, + "object": Schema.String +}) +export type DeleteThreadResponse = { + readonly "id": string + readonly "deleted": boolean + readonly "object": "thread.deleted" +} +export const DeleteThreadResponse = Schema.Struct({ + "id": Schema.String, + "deleted": Schema.Boolean, + "object": Schema.Literal("thread.deleted") +}) +export type DeleteVectorStoreFileResponse = { + readonly "id": string + readonly "deleted": boolean + readonly "object": "vector_store.file.deleted" +} +export const DeleteVectorStoreFileResponse = Schema.Struct({ + "id": Schema.String, + "deleted": Schema.Boolean, + "object": Schema.Literal("vector_store.file.deleted") +}) +export type DeleteVectorStoreResponse = { + readonly "id": string + readonly "deleted": boolean + readonly "object": "vector_store.deleted" +} +export const DeleteVectorStoreResponse = Schema.Struct({ + "id": Schema.String, + "deleted": Schema.Boolean, + "object": Schema.Literal("vector_store.deleted") +}) +export type DeletedRoleAssignmentResource = { readonly "object": string; readonly "deleted": boolean } +export const DeletedRoleAssignmentResource = Schema.Struct({ + "object": Schema.String.annotate({ + "description": "Identifier for the deleted assignment, such as `group.role.deleted` or `user.role.deleted`." + }), + "deleted": Schema.Boolean.annotate({ "description": "Whether the assignment was removed." }) +}).annotate({ "description": "Confirmation payload returned after unassigning a role." }) +export type DoneEvent = { readonly "event": "done"; readonly "data": "[DONE]" } +export const DoneEvent = Schema.Struct({ "event": Schema.Literal("done"), "data": Schema.Literal("[DONE]") }).annotate({ + "description": "Occurs when a stream ends." +}) +export type Embedding = { + readonly "index": number + readonly "embedding": ReadonlyArray + readonly "object": "embedding" +} +export const Embedding = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the embedding in the list of embeddings." }).check( + Schema.isInt() + ), + "embedding": Schema.Array(Schema.Number.annotate({ "format": "float" }).check(Schema.isFinite())).annotate({ + "description": + "The embedding vector, which is a list of floats. The length of vector depends on the model as listed in the [embedding guide](/docs/guides/embeddings).\n" + }), + "object": Schema.Literal("embedding").annotate({ "description": "The object type, which is always \"embedding\"." }) +}).annotate({ "description": "Represents an embedding vector returned by embedding endpoint.\n" }) +export type Error = { + readonly "code": string | null + readonly "message": string + readonly "param": string | null + readonly "type": string +} +export const Error = Schema.Struct({ + "code": Schema.Union([Schema.String, Schema.Null]), + "message": Schema.String, + "param": Schema.Union([Schema.String, Schema.Null]), + "type": Schema.String +}) +export type EvalApiError = { readonly "code": string; readonly "message": string } +export const EvalApiError = Schema.Struct({ + "code": Schema.String.annotate({ "description": "The error code." }), + "message": Schema.String.annotate({ "description": "The error message." }) +}).annotate({ "title": "EvalApiError", "description": "An object representing an error response from the Eval API.\n" }) +export type EvalGraderPython = { + readonly "type": "python" + readonly "name": string + readonly "source": string + readonly "image_tag"?: string + readonly "pass_threshold"?: number +} +export const EvalGraderPython = Schema.Struct({ + "type": Schema.Literal("python").annotate({ "description": "The object type, which is always `python`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "source": Schema.String.annotate({ "description": "The source code of the python script." }), + "image_tag": Schema.optionalKey( + Schema.String.annotate({ "description": "The image tag to use for the python script." }) + ), + "pass_threshold": Schema.optionalKey( + Schema.Number.annotate({ "description": "The threshold for the score." }).check(Schema.isFinite()) + ) +}).annotate({ + "title": "PythonGrader", + "description": "A PythonGrader object that runs a python script on the input.\n" +}) +export type EvalGraderStringCheck = { + readonly "type": "string_check" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "operation": "eq" | "ne" | "like" | "ilike" +} +export const EvalGraderStringCheck = Schema.Struct({ + "type": Schema.Literal("string_check").annotate({ + "description": "The object type, which is always `string_check`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The input text. This may include template strings." }), + "reference": Schema.String.annotate({ "description": "The reference text. This may include template strings." }), + "operation": Schema.Literals(["eq", "ne", "like", "ilike"]).annotate({ + "description": "The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`." + }) +}).annotate({ + "title": "StringCheckGrader", + "description": + "A StringCheckGrader object that performs a string comparison between input and reference using a specified operation.\n" +}) +export type EvalGraderTextSimilarity = { + readonly "type": "text_similarity" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "evaluation_metric": + | "cosine" + | "fuzzy_match" + | "bleu" + | "gleu" + | "meteor" + | "rouge_1" + | "rouge_2" + | "rouge_3" + | "rouge_4" + | "rouge_5" + | "rouge_l" + readonly "pass_threshold": number +} +export const EvalGraderTextSimilarity = Schema.Struct({ + "type": Schema.Literal("text_similarity").annotate({ "description": "The type of grader." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The text being graded." }), + "reference": Schema.String.annotate({ "description": "The text being graded against." }), + "evaluation_metric": Schema.Literals([ + "cosine", + "fuzzy_match", + "bleu", + "gleu", + "meteor", + "rouge_1", + "rouge_2", + "rouge_3", + "rouge_4", + "rouge_5", + "rouge_l" + ]).annotate({ + "description": + "The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, \n`gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, \nor `rouge_l`.\n" + }), + "pass_threshold": Schema.Number.annotate({ "description": "The threshold for the score." }).check(Schema.isFinite()) +}).annotate({ + "title": "TextSimilarityGrader", + "description": "A TextSimilarityGrader object which grades text based on similarity metrics.\n" +}) +export type EvalItemContentOutputText = { readonly "type": "output_text"; readonly "text": string } +export const EvalItemContentOutputText = Schema.Struct({ + "type": Schema.Literal("output_text").annotate({ + "description": "The type of the output text. Always `output_text`.\n" + }), + "text": Schema.String.annotate({ "description": "The text output from the model.\n" }) +}).annotate({ "title": "Output text", "description": "A text output from the model.\n" }) +export type EvalItemContentText = string +export const EvalItemContentText = Schema.String.annotate({ + "title": "Text input", + "description": "A text input to the model.\n" +}) +export type EvalItemInputImage = { + readonly "type": "input_image" + readonly "image_url": string + readonly "detail"?: string +} +export const EvalItemInputImage = Schema.Struct({ + "type": Schema.Literal("input_image").annotate({ + "description": "The type of the image input. Always `input_image`.\n" + }), + "image_url": Schema.String.annotate({ "description": "The URL of the image input.\n", "format": "uri" }), + "detail": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`.\n" + }) + ) +}).annotate({ "title": "Input image", "description": "An image input block used within EvalItem content arrays." }) +export type EvalJsonlFileContentSource = { + readonly "type": "file_content" + readonly "content": ReadonlyArray<{ readonly "item": {}; readonly "sample"?: {} }> +} +export const EvalJsonlFileContentSource = Schema.Struct({ + "type": Schema.Literal("file_content").annotate({ + "description": "The type of jsonl source. Always `file_content`." + }), + "content": Schema.Array(Schema.Struct({ "item": Schema.Struct({}), "sample": Schema.optionalKey(Schema.Struct({})) })) + .annotate({ "description": "The content of the jsonl file." }) +}).annotate({ "title": "EvalJsonlFileContentSource" }) +export type EvalJsonlFileIdSource = { readonly "type": "file_id"; readonly "id": string } +export const EvalJsonlFileIdSource = Schema.Struct({ + "type": Schema.Literal("file_id").annotate({ "description": "The type of jsonl source. Always `file_id`." }), + "id": Schema.String.annotate({ "description": "The identifier of the file." }) +}).annotate({ "title": "EvalJsonlFileIdSource" }) +export type EvalResponsesSource = { + readonly "type": "responses" + readonly "metadata"?: {} | null + readonly "model"?: string | null + readonly "instructions_search"?: string | null + readonly "created_after"?: number | null + readonly "created_before"?: number | null + readonly "reasoning_effort"?: "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | null | null + readonly "temperature"?: number | null + readonly "top_p"?: number | null + readonly "users"?: ReadonlyArray | null + readonly "tools"?: ReadonlyArray | null +} +export const EvalResponsesSource = Schema.Struct({ + "type": Schema.Literal("responses").annotate({ "description": "The type of run data source. Always `responses`." }), + "metadata": Schema.optionalKey( + Schema.Union([ + Schema.Struct({}).annotate({ + "description": "Metadata filter for the responses. This is a query parameter used to select responses." + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The name of the model to find responses for. This is a query parameter used to select responses." + }), + Schema.Null + ]) + ), + "instructions_search": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "Optional string to search the 'instructions' field. This is a query parameter used to select responses." + }), + Schema.Null + ]) + ), + "created_after": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Only include items created after this timestamp (inclusive). This is a query parameter used to select responses." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]) + ), + "created_before": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Only include items created before this timestamp (inclusive). This is a query parameter used to select responses." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + Schema.Null + ]) + ), + "reasoning_effort": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Literals(["none", "minimal", "low", "medium", "high", "xhigh"]).annotate({ + "description": + "Constrains effort on reasoning for\n[reasoning models](https://platform.openai.com/docs/guides/reasoning).\nCurrently supported values are `none`, `minimal`, `low`, `medium`, `high`, and `xhigh`. Reducing\nreasoning effort can result in faster responses and fewer tokens used\non reasoning in a response.\n\n- `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning values in gpt-5.1.\n- All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`.\n- The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort.\n- `xhigh` is supported for all models after `gpt-5.1-codex-max`.\n" + }), + Schema.Null + ]).annotate({ + "description": "Optional reasoning effort parameter. This is a query parameter used to select responses." + }), + Schema.Null + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "Sampling temperature. This is a query parameter used to select responses." + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "Nucleus sampling parameter. This is a query parameter used to select responses." + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "users": Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + "description": "List of user identifiers. This is a query parameter used to select responses." + }), + Schema.Null + ]) + ), + "tools": Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ + "description": "List of tool names. This is a query parameter used to select responses." + }), + Schema.Null + ]) + ) +}).annotate({ + "title": "EvalResponsesSource", + "description": "A EvalResponsesSource object describing a run data source configuration.\n" +}) +export type EvalRunOutputItemResult = { + readonly "name": string + readonly "type"?: string + readonly "score": number + readonly "passed": boolean + readonly "sample"?: {} | null +} +export const EvalRunOutputItemResult = Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "type": Schema.optionalKey( + Schema.String.annotate({ "description": "The grader type (for example, \"string-check-grader\")." }) + ), + "score": Schema.Number.annotate({ "description": "The numeric score produced by the grader." }).check( + Schema.isFinite() + ), + "passed": Schema.Boolean.annotate({ "description": "Whether the grader considered the output a pass." }), + "sample": Schema.optionalKey( + Schema.Union([Schema.Struct({}), Schema.Null]).annotate({ + "description": "Optional sample or intermediate data produced by the grader." + }) + ) +}).annotate({ + "title": "EvalRunOutputItemResult", + "description": "A single grader result for an evaluation run output item.\n" +}) +export type FileExpirationAfter = { readonly "anchor": "created_at"; readonly "seconds": number } +export const FileExpirationAfter = Schema.Struct({ + "anchor": Schema.Literal("created_at").annotate({ + "description": "Anchor timestamp after which the expiration policy applies. Supported anchors: `created_at`." + }), + "seconds": Schema.Number.annotate({ + "description": + "The number of seconds after the anchor time that the file will expire. Must be between 3600 (1 hour) and 2592000 (30 days).", + "format": "int64" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(3600)).check(Schema.isLessThanOrEqualTo(2592000)) +}).annotate({ + "title": "File expiration policy", + "description": + "The expiration policy for a file. By default, files with `purpose=batch` expire after 30 days and all other files are persisted until they are manually deleted." +}) +export type FilePath = { readonly "type": "file_path"; readonly "file_id": string; readonly "index": number } +export const FilePath = Schema.Struct({ + "type": Schema.Literal("file_path").annotate({ "description": "The type of the file path. Always `file_path`.\n" }), + "file_id": Schema.String.annotate({ "description": "The ID of the file.\n" }), + "index": Schema.Number.annotate({ "description": "The index of the file in the list of files.\n" }).check( + Schema.isInt() + ) +}).annotate({ "title": "File path", "description": "A path to a file.\n" }) +export type FileSearchRanker = "auto" | "default_2024_08_21" +export const FileSearchRanker = Schema.Literals(["auto", "default_2024_08_21"]).annotate({ + "description": "The ranker to use for the file search. If not specified will use the `auto` ranker." +}) +export type FineTuneDPOHyperparameters = { + readonly "beta"?: "auto" | number + readonly "batch_size"?: "auto" | number + readonly "learning_rate_multiplier"?: "auto" | number + readonly "n_epochs"?: "auto" | number +} +export const FineTuneDPOHyperparameters = Schema.Struct({ + "beta": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isFinite()).check(Schema.isLessThanOrEqualTo(2)).check(Schema.isGreaterThan(0)) + ], { mode: "oneOf" }).annotate({ + "description": + "The beta value for the DPO method. A higher beta value will increase the weight of the penalty between the policy and reference model.\n" + }) + ), + "batch_size": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(256)) + ], { mode: "oneOf" }).annotate({ + "description": + "Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n" + }) + ), + "learning_rate_multiplier": Schema.optionalKey( + Schema.Union([Schema.Literal("auto"), Schema.Number.check(Schema.isFinite()).check(Schema.isGreaterThan(0))], { + mode: "oneOf" + }).annotate({ + "description": + "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n" + }) + ), + "n_epochs": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(50)) + ], { mode: "oneOf" }).annotate({ + "description": + "The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n" + }) + ) +}).annotate({ "description": "The hyperparameters used for the DPO fine-tuning job." }) +export type FineTuneReinforcementHyperparameters = { + readonly "batch_size"?: "auto" | number + readonly "learning_rate_multiplier"?: "auto" | number + readonly "n_epochs"?: "auto" | number + readonly "reasoning_effort"?: "default" | "low" | "medium" | "high" + readonly "compute_multiplier"?: "auto" | number + readonly "eval_interval"?: "auto" | number + readonly "eval_samples"?: "auto" | number +} +export const FineTuneReinforcementHyperparameters = Schema.Struct({ + "batch_size": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(256)) + ], { mode: "oneOf" }).annotate({ + "description": + "Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n" + }) + ), + "learning_rate_multiplier": Schema.optionalKey( + Schema.Union([Schema.Literal("auto"), Schema.Number.check(Schema.isFinite()).check(Schema.isGreaterThan(0))], { + mode: "oneOf" + }).annotate({ + "description": + "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n" + }) + ), + "n_epochs": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(50)) + ], { mode: "oneOf" }).annotate({ + "description": + "The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n" + }) + ), + "reasoning_effort": Schema.optionalKey( + Schema.Literals(["default", "low", "medium", "high"]).annotate({ "description": "Level of reasoning effort.\n" }) + ), + "compute_multiplier": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isFinite()).check(Schema.isLessThanOrEqualTo(10)).check(Schema.isGreaterThan(0.00001)) + ], { mode: "oneOf" }).annotate({ + "description": "Multiplier on amount of compute used for exploring search space during training.\n" + }) + ), + "eval_interval": Schema.optionalKey( + Schema.Union( + [Schema.Literal("auto"), Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1))], + { mode: "oneOf" } + ).annotate({ "description": "The number of training steps between evaluation runs.\n" }) + ), + "eval_samples": Schema.optionalKey( + Schema.Union( + [Schema.Literal("auto"), Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1))], + { mode: "oneOf" } + ).annotate({ "description": "Number of evaluation samples to generate per training step.\n" }) + ) +}).annotate({ "description": "The hyperparameters used for the reinforcement fine-tuning job." }) +export type FineTuneSupervisedHyperparameters = { + readonly "batch_size"?: "auto" | number + readonly "learning_rate_multiplier"?: "auto" | number + readonly "n_epochs"?: "auto" | number +} +export const FineTuneSupervisedHyperparameters = Schema.Struct({ + "batch_size": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(256)) + ], { mode: "oneOf" }).annotate({ + "description": + "Number of examples in each batch. A larger batch size means that model parameters are updated less frequently, but with lower variance.\n" + }) + ), + "learning_rate_multiplier": Schema.optionalKey( + Schema.Union([Schema.Literal("auto"), Schema.Number.check(Schema.isFinite()).check(Schema.isGreaterThan(0))], { + mode: "oneOf" + }).annotate({ + "description": + "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid overfitting.\n" + }) + ), + "n_epochs": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(50)) + ], { mode: "oneOf" }).annotate({ + "description": + "The number of epochs to train the model for. An epoch refers to one full cycle through the training dataset.\n" + }) + ) +}).annotate({ "description": "The hyperparameters used for the fine-tuning job." }) +export type FineTuningCheckpointPermission = { + readonly "id": string + readonly "created_at": number + readonly "project_id": string + readonly "object": "checkpoint.permission" +} +export const FineTuningCheckpointPermission = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The permission identifier, which can be referenced in the API endpoints." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the permission was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "project_id": Schema.String.annotate({ "description": "The project identifier that the permission is for." }), + "object": Schema.Literal("checkpoint.permission").annotate({ + "description": "The object type, which is always \"checkpoint.permission\"." + }) +}).annotate({ + "title": "FineTuningCheckpointPermission", + "description": "The `checkpoint.permission` object represents a permission for a fine-tuned model checkpoint.\n" +}) +export type FineTuningIntegration = { + readonly "type": "wandb" + readonly "wandb": { + readonly "project": string + readonly "name"?: string | null + readonly "entity"?: string | null + readonly "tags"?: ReadonlyArray + } +} +export const FineTuningIntegration = Schema.Struct({ + "type": Schema.Literal("wandb").annotate({ + "description": "The type of the integration being enabled for the fine-tuning job" + }), + "wandb": Schema.Struct({ + "project": Schema.String.annotate({ + "description": "The name of the project that the new run will be created under.\n" + }), + "name": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "A display name to set for the run. If not set, we will use the Job ID as the name.\n" + }), + Schema.Null + ]) + ), + "entity": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The entity to use for the run. This allows you to set the team or username of the WandB user that you would\nlike associated with the run. If not set, the default entity for the registered WandB API key is used.\n" + }), + Schema.Null + ]) + ), + "tags": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: \"openai/finetune\", \"openai/{base-model}\", \"openai/{ftjob-abcdef}\".\n" + }) + ) + }).annotate({ + "description": + "The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n" + }) +}).annotate({ "title": "Fine-Tuning Job Integration" }) +export type FineTuningJobCheckpoint = { + readonly "id": string + readonly "created_at": number + readonly "fine_tuned_model_checkpoint": string + readonly "step_number": number + readonly "metrics": { + readonly "step"?: number + readonly "train_loss"?: number + readonly "train_mean_token_accuracy"?: number + readonly "valid_loss"?: number + readonly "valid_mean_token_accuracy"?: number + readonly "full_valid_loss"?: number + readonly "full_valid_mean_token_accuracy"?: number + } + readonly "fine_tuning_job_id": string + readonly "object": "fine_tuning.job.checkpoint" +} +export const FineTuningJobCheckpoint = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The checkpoint identifier, which can be referenced in the API endpoints." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the checkpoint was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "fine_tuned_model_checkpoint": Schema.String.annotate({ + "description": "The name of the fine-tuned checkpoint model that is created." + }), + "step_number": Schema.Number.annotate({ "description": "The step number that the checkpoint was created at." }).check( + Schema.isInt() + ), + "metrics": Schema.Struct({ + "step": Schema.optionalKey(Schema.Number.check(Schema.isFinite())), + "train_loss": Schema.optionalKey(Schema.Number.check(Schema.isFinite())), + "train_mean_token_accuracy": Schema.optionalKey(Schema.Number.check(Schema.isFinite())), + "valid_loss": Schema.optionalKey(Schema.Number.check(Schema.isFinite())), + "valid_mean_token_accuracy": Schema.optionalKey(Schema.Number.check(Schema.isFinite())), + "full_valid_loss": Schema.optionalKey(Schema.Number.check(Schema.isFinite())), + "full_valid_mean_token_accuracy": Schema.optionalKey(Schema.Number.check(Schema.isFinite())) + }).annotate({ "description": "Metrics at the step number during the fine-tuning job." }), + "fine_tuning_job_id": Schema.String.annotate({ + "description": "The name of the fine-tuning job that this checkpoint was created from." + }), + "object": Schema.Literal("fine_tuning.job.checkpoint").annotate({ + "description": "The object type, which is always \"fine_tuning.job.checkpoint\"." + }) +}).annotate({ + "title": "FineTuningJobCheckpoint", + "description": + "The `fine_tuning.job.checkpoint` object represents a model checkpoint for a fine-tuning job that is ready to use.\n" +}) +export type FineTuningJobEvent = { + readonly "object": "fine_tuning.job.event" + readonly "id": string + readonly "created_at": number + readonly "level": "info" | "warn" | "error" + readonly "message": string + readonly "type"?: "message" | "metrics" + readonly "data"?: {} +} +export const FineTuningJobEvent = Schema.Struct({ + "object": Schema.Literal("fine_tuning.job.event").annotate({ + "description": "The object type, which is always \"fine_tuning.job.event\"." + }), + "id": Schema.String.annotate({ "description": "The object identifier." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the fine-tuning job was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "level": Schema.Literals(["info", "warn", "error"]).annotate({ "description": "The log level of the event." }), + "message": Schema.String.annotate({ "description": "The message of the event." }), + "type": Schema.optionalKey(Schema.Literals(["message", "metrics"]).annotate({ "description": "The type of event." })), + "data": Schema.optionalKey(Schema.Struct({}).annotate({ "description": "The data associated with the event." })) +}).annotate({ "description": "Fine-tuning job event object" }) +export type FunctionParameters = {} +export const FunctionParameters = Schema.Struct({}).annotate({ + "description": + "The parameters the functions accepts, described as a JSON Schema object. See the [guide](/docs/guides/function-calling) for examples, and the [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for documentation about the format. \n\nOmitting `parameters` defines a function with an empty parameter list." +}) +export type FunctionToolCall = { + readonly "id"?: string + readonly "type": "function_call" + readonly "call_id": string + readonly "namespace"?: string + readonly "name": string + readonly "arguments": string + readonly "status"?: "in_progress" | "completed" | "incomplete" +} +export const FunctionToolCall = Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The unique ID of the function tool call.\n" })), + "type": Schema.Literal("function_call").annotate({ + "description": "The type of the function tool call. Always `function_call`.\n" + }), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the function tool call generated by the model.\n" + }), + "namespace": Schema.optionalKey(Schema.String.annotate({ "description": "The namespace of the function to run.\n" })), + "name": Schema.String.annotate({ "description": "The name of the function to run.\n" }), + "arguments": Schema.String.annotate({ "description": "A JSON string of the arguments to pass to the function.\n" }), + "status": Schema.optionalKey( + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + ) +}).annotate({ + "title": "Function tool call", + "description": + "A tool call to run a function. See the \n[function calling guide](/docs/guides/function-calling) for more information.\n" +}) +export type FunctionToolCallResource = { + readonly "id": string + readonly "type": "function_call" + readonly "call_id": string + readonly "namespace"?: string + readonly "name": string + readonly "arguments": string + readonly "status": "in_progress" | "completed" | "incomplete" + readonly "created_by"?: string +} +export const FunctionToolCallResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the function tool call.\n" }), + "type": Schema.Literal("function_call").annotate({ + "description": "The type of the function tool call. Always `function_call`.\n" + }), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the function tool call generated by the model.\n" + }), + "namespace": Schema.optionalKey(Schema.String.annotate({ "description": "The namespace of the function to run.\n" })), + "name": Schema.String.annotate({ "description": "The name of the function to run.\n" }), + "arguments": Schema.String.annotate({ "description": "A JSON string of the arguments to pass to the function.\n" }), + "status": Schema.Union([ + Schema.Literal("in_progress").annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }), + Schema.Literal("completed").annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }), + Schema.Literal("incomplete").annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + ]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item.\n" }) + ) +}).annotate({ + "title": "Function tool call", + "description": + "A tool call to run a function. See the \n[function calling guide](/docs/guides/function-calling) for more information.\n" +}) +export type GraderPython = { + readonly "type": "python" + readonly "name": string + readonly "source": string + readonly "image_tag"?: string +} +export const GraderPython = Schema.Struct({ + "type": Schema.Literal("python").annotate({ "description": "The object type, which is always `python`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "source": Schema.String.annotate({ "description": "The source code of the python script." }), + "image_tag": Schema.optionalKey( + Schema.String.annotate({ "description": "The image tag to use for the python script." }) + ) +}).annotate({ + "title": "PythonGrader", + "description": "A PythonGrader object that runs a python script on the input.\n" +}) +export type GraderStringCheck = { + readonly "type": "string_check" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "operation": "eq" | "ne" | "like" | "ilike" +} +export const GraderStringCheck = Schema.Struct({ + "type": Schema.Literal("string_check").annotate({ + "description": "The object type, which is always `string_check`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The input text. This may include template strings." }), + "reference": Schema.String.annotate({ "description": "The reference text. This may include template strings." }), + "operation": Schema.Literals(["eq", "ne", "like", "ilike"]).annotate({ + "description": "The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`." + }) +}).annotate({ + "title": "StringCheckGrader", + "description": + "A StringCheckGrader object that performs a string comparison between input and reference using a specified operation.\n" +}) +export type GraderTextSimilarity = { + readonly "type": "text_similarity" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "evaluation_metric": + | "cosine" + | "fuzzy_match" + | "bleu" + | "gleu" + | "meteor" + | "rouge_1" + | "rouge_2" + | "rouge_3" + | "rouge_4" + | "rouge_5" + | "rouge_l" +} +export const GraderTextSimilarity = Schema.Struct({ + "type": Schema.Literal("text_similarity").annotate({ "description": "The type of grader." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The text being graded." }), + "reference": Schema.String.annotate({ "description": "The text being graded against." }), + "evaluation_metric": Schema.Literals([ + "cosine", + "fuzzy_match", + "bleu", + "gleu", + "meteor", + "rouge_1", + "rouge_2", + "rouge_3", + "rouge_4", + "rouge_5", + "rouge_l" + ]).annotate({ + "description": + "The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, \n`gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, \nor `rouge_l`.\n" + }) +}).annotate({ + "title": "TextSimilarityGrader", + "description": "A TextSimilarityGrader object which grades text based on similarity metrics.\n" +}) +export type Group = { + readonly "object": "group" + readonly "id": string + readonly "name": string + readonly "created_at": number + readonly "scim_managed": boolean +} +export const Group = Schema.Struct({ + "object": Schema.Literal("group").annotate({ "description": "Always `group`." }), + "id": Schema.String.annotate({ "description": "Identifier for the group." }), + "name": Schema.String.annotate({ "description": "Display name of the group." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the group was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "scim_managed": Schema.Boolean.annotate({ "description": "Whether the group is managed through SCIM." }) +}).annotate({ "description": "Summary information about a group returned in role assignment responses." }) +export type GroupDeletedResource = { + readonly "object": "group.deleted" + readonly "id": string + readonly "deleted": boolean +} +export const GroupDeletedResource = Schema.Struct({ + "object": Schema.Literal("group.deleted").annotate({ "description": "Always `group.deleted`." }), + "id": Schema.String.annotate({ "description": "Identifier of the deleted group." }), + "deleted": Schema.Boolean.annotate({ "description": "Whether the group was deleted." }) +}).annotate({ "description": "Confirmation payload returned after deleting a group." }) +export type GroupResourceWithSuccess = { + readonly "id": string + readonly "name": string + readonly "created_at": number + readonly "is_scim_managed": boolean +} +export const GroupResourceWithSuccess = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier for the group." }), + "name": Schema.String.annotate({ "description": "Updated display name for the group." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the group was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "is_scim_managed": Schema.Boolean.annotate({ + "description": "Whether the group is managed through SCIM and controlled by your identity provider." + }) +}).annotate({ "description": "Response returned after updating a group." }) +export type GroupResponse = { + readonly "id": string + readonly "name": string + readonly "created_at": number + readonly "is_scim_managed": boolean + readonly "group_type": string +} +export const GroupResponse = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier for the group." }), + "name": Schema.String.annotate({ "description": "Display name of the group." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the group was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "is_scim_managed": Schema.Boolean.annotate({ + "description": "Whether the group is managed through SCIM and controlled by your identity provider." + }), + "group_type": Schema.String.annotate({ "description": "The type of the group." }) +}).annotate({ "description": "Details about an organization group." }) +export type GroupUser = { readonly "id": string; readonly "name": string; readonly "email": string | null } +export const GroupUser = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.String.annotate({ "description": "The name of the user." }), + "email": Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The email address of the user." }) +}).annotate({ "description": "Represents an individual user returned when inspecting group membership." }) +export type GroupUserAssignment = { + readonly "object": "group.user" + readonly "user_id": string + readonly "group_id": string +} +export const GroupUserAssignment = Schema.Struct({ + "object": Schema.Literal("group.user").annotate({ "description": "Always `group.user`." }), + "user_id": Schema.String.annotate({ "description": "Identifier of the user that was added." }), + "group_id": Schema.String.annotate({ "description": "Identifier of the group the user was added to." }) +}).annotate({ "description": "Confirmation payload returned after adding a user to a group." }) +export type GroupUserDeletedResource = { readonly "object": "group.user.deleted"; readonly "deleted": boolean } +export const GroupUserDeletedResource = Schema.Struct({ + "object": Schema.Literal("group.user.deleted").annotate({ "description": "Always `group.user.deleted`." }), + "deleted": Schema.Boolean.annotate({ "description": "Whether the group membership was removed." }) +}).annotate({ "description": "Confirmation payload returned after removing a user from a group." }) +export type HostedToolPermission = { readonly "enabled": boolean } +export const HostedToolPermission = Schema.Struct({ + "enabled": Schema.Boolean.annotate({ "description": "Whether the hosted tool is enabled for the project." }) +}).annotate({ "description": "Permission state for a single hosted tool on a project." }) +export type HostedToolPermissionUpdate = { readonly "enabled": boolean } +export const HostedToolPermissionUpdate = Schema.Struct({ + "enabled": Schema.Boolean.annotate({ "description": "Whether to enable the hosted tool for the project." }) +}) +export type Image = { readonly "b64_json"?: string; readonly "url"?: string; readonly "revised_prompt"?: string } +export const Image = Schema.Struct({ + "b64_json": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The base64-encoded JSON of the generated image. Returned by default for the GPT image models, and only present if `response_format` is set to `b64_json` for `dall-e-2` and `dall-e-3`." + }) + ), + "url": Schema.optionalKey( + Schema.String.annotate({ + "description": + "When using `dall-e-2` or `dall-e-3`, the URL of the generated image if `response_format` is set to `url` (default value). Unsupported for the GPT image models.", + "format": "uri" + }) + ), + "revised_prompt": Schema.optionalKey( + Schema.String.annotate({ + "description": "For `dall-e-3` only, the revised prompt that was used to generate the image." + }) + ) +}).annotate({ "description": "Represents the content or the URL of an image generated by the OpenAI API." }) +export type ImageEditPartialImageEvent = { + readonly "type": "image_edit.partial_image" + readonly "b64_json": string + readonly "created_at": number + readonly "size": "1024x1024" | "1024x1536" | "1536x1024" | "auto" + readonly "quality": "low" | "medium" | "high" | "auto" + readonly "background": "transparent" | "opaque" | "auto" + readonly "output_format": "png" | "webp" | "jpeg" + readonly "partial_image_index": number +} +export const ImageEditPartialImageEvent = Schema.Struct({ + "type": Schema.Literal("image_edit.partial_image").annotate({ + "description": "The type of the event. Always `image_edit.partial_image`.\n" + }), + "b64_json": Schema.String.annotate({ + "description": "Base64-encoded partial image data, suitable for rendering as an image.\n" + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp when the event was created.\n", + "format": "unixtime" + }).check(Schema.isInt()), + "size": Schema.Literals(["1024x1024", "1024x1536", "1536x1024", "auto"]).annotate({ + "description": "The size of the requested edited image.\n" + }), + "quality": Schema.Literals(["low", "medium", "high", "auto"]).annotate({ + "description": "The quality setting for the requested edited image.\n" + }), + "background": Schema.Literals(["transparent", "opaque", "auto"]).annotate({ + "description": "The background setting for the requested edited image.\n" + }), + "output_format": Schema.Literals(["png", "webp", "jpeg"]).annotate({ + "description": "The output format for the requested edited image.\n" + }), + "partial_image_index": Schema.Number.annotate({ "description": "0-based index for the partial image (streaming).\n" }) + .check(Schema.isInt()) +}).annotate({ "description": "Emitted when a partial image is available during image editing streaming.\n" }) +export type ImageGenPartialImageEvent = { + readonly "type": "image_generation.partial_image" + readonly "b64_json": string + readonly "created_at": number + readonly "size": "1024x1024" | "1024x1536" | "1536x1024" | "auto" + readonly "quality": "low" | "medium" | "high" | "auto" + readonly "background": "transparent" | "opaque" | "auto" + readonly "output_format": "png" | "webp" | "jpeg" + readonly "partial_image_index": number +} +export const ImageGenPartialImageEvent = Schema.Struct({ + "type": Schema.Literal("image_generation.partial_image").annotate({ + "description": "The type of the event. Always `image_generation.partial_image`.\n" + }), + "b64_json": Schema.String.annotate({ + "description": "Base64-encoded partial image data, suitable for rendering as an image.\n" + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp when the event was created.\n", + "format": "unixtime" + }).check(Schema.isInt()), + "size": Schema.Literals(["1024x1024", "1024x1536", "1536x1024", "auto"]).annotate({ + "description": "The size of the requested image.\n" + }), + "quality": Schema.Literals(["low", "medium", "high", "auto"]).annotate({ + "description": "The quality setting for the requested image.\n" + }), + "background": Schema.Literals(["transparent", "opaque", "auto"]).annotate({ + "description": "The background setting for the requested image.\n" + }), + "output_format": Schema.Literals(["png", "webp", "jpeg"]).annotate({ + "description": "The output format for the requested image.\n" + }), + "partial_image_index": Schema.Number.annotate({ "description": "0-based index for the partial image (streaming).\n" }) + .check(Schema.isInt()) +}).annotate({ "description": "Emitted when a partial image is available during image generation streaming.\n" }) +export type ImageGenToolCall = { + readonly "type": "image_generation_call" + readonly "id": string + readonly "status": "in_progress" | "completed" | "generating" | "failed" + readonly "result": string | null +} +export const ImageGenToolCall = Schema.Struct({ + "type": Schema.Literal("image_generation_call").annotate({ + "description": "The type of the image generation call. Always `image_generation_call`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the image generation call.\n" }), + "status": Schema.Literals(["in_progress", "completed", "generating", "failed"]).annotate({ + "description": "The status of the image generation call.\n" + }), + "result": Schema.Union([ + Schema.String.annotate({ "description": "The generated image encoded in base64.\n" }), + Schema.Null + ]) +}).annotate({ "title": "Image generation call", "description": "An image generation request made by the model.\n" }) +export type ImageRefParam = { readonly "image_url": string; readonly "file_id"?: string } | { + readonly "file_id": string + readonly "image_url"?: string +} +export const ImageRefParam = Schema.Union([ + Schema.Struct({ + "image_url": Schema.String.annotate({ + "description": "A fully qualified URL or base64-encoded data URL.", + "format": "uri" + }).check(Schema.isMaxLength(20971520)), + "file_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The File API ID of an uploaded image to use as input." }) + ) + }).annotate({ + "description": + "Reference an input image by either URL or uploaded file ID.\nProvide exactly one of `image_url` or `file_id`.\n" + }), + Schema.Struct({ + "file_id": Schema.String.annotate({ "description": "The File API ID of an uploaded image to use as input." }), + "image_url": Schema.optionalKey( + Schema.String.annotate({ "description": "A fully qualified URL or base64-encoded data URL.", "format": "uri" }) + .check(Schema.isMaxLength(20971520)) + ) + }).annotate({ + "description": + "Reference an input image by either URL or uploaded file ID.\nProvide exactly one of `image_url` or `file_id`.\n" + }) +]) +export type ImagesUsage = { + readonly "total_tokens": number + readonly "input_tokens": number + readonly "output_tokens": number + readonly "input_tokens_details": { readonly "text_tokens": number; readonly "image_tokens": number } +} +export const ImagesUsage = Schema.Struct({ + "total_tokens": Schema.Number.annotate({ + "description": "The total number of tokens (images and text) used for the image generation.\n" + }).check(Schema.isInt()), + "input_tokens": Schema.Number.annotate({ + "description": "The number of tokens (images and text) in the input prompt." + }).check(Schema.isInt()), + "output_tokens": Schema.Number.annotate({ "description": "The number of image tokens in the output image." }).check( + Schema.isInt() + ), + "input_tokens_details": Schema.Struct({ + "text_tokens": Schema.Number.annotate({ "description": "The number of text tokens in the input prompt." }).check( + Schema.isInt() + ), + "image_tokens": Schema.Number.annotate({ "description": "The number of image tokens in the input prompt." }).check( + Schema.isInt() + ) + }).annotate({ "description": "The input tokens detailed information for the image generation." }) +}).annotate({ "description": "For the GPT image models only, the token usage information for the image generation.\n" }) +export type InputAudio = { + readonly "type": "input_audio" + readonly "input_audio": { readonly "data": string; readonly "format": "mp3" | "wav" } +} +export const InputAudio = Schema.Struct({ + "type": Schema.Literal("input_audio").annotate({ + "description": "The type of the input item. Always `input_audio`.\n" + }), + "input_audio": Schema.Struct({ + "data": Schema.String.annotate({ "description": "Base64-encoded audio data.\n" }), + "format": Schema.Literals(["mp3", "wav"]).annotate({ + "description": "The format of the audio data. Currently supported formats are `mp3` and\n`wav`.\n" + }) + }) +}).annotate({ "title": "Input audio", "description": "An audio input to the model.\n" }) +export type Invite = { + readonly "object": "organization.invite" + readonly "id": string + readonly "email": string + readonly "role": "owner" | "reader" + readonly "status": "accepted" | "expired" | "pending" + readonly "created_at": number + readonly "expires_at"?: number | null + readonly "accepted_at"?: number | null + readonly "projects": ReadonlyArray<{ readonly "id": string; readonly "role": "member" | "owner" }> +} +export const Invite = Schema.Struct({ + "object": Schema.Literal("organization.invite").annotate({ + "description": "The object type, which is always `organization.invite`" + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "email": Schema.String.annotate({ "description": "The email address of the individual to whom the invite was sent" }), + "role": Schema.Literals(["owner", "reader"]).annotate({ "description": "`owner` or `reader`" }), + "status": Schema.Literals(["accepted", "expired", "pending"]).annotate({ + "description": "`accepted`,`expired`, or `pending`" + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the invite was sent.", + "format": "unixtime" + }).check(Schema.isInt()), + "expires_at": Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ "format": "unixtime" }).check(Schema.isInt()), Schema.Null]).annotate({ + "description": "The Unix timestamp (in seconds) of when the invite expires." + }) + ), + "accepted_at": Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ "format": "unixtime" }).check(Schema.isInt()), Schema.Null]).annotate({ + "description": "The Unix timestamp (in seconds) of when the invite was accepted." + }) + ), + "projects": Schema.Array( + Schema.Struct({ + "id": Schema.String.annotate({ "description": "Project's public ID" }), + "role": Schema.Literals(["member", "owner"]).annotate({ "description": "Project membership role" }) + }) + ).annotate({ "description": "The projects that were granted membership upon acceptance of the invite." }) +}).annotate({ "description": "Represents an individual `invite` to the organization." }) +export type InviteDeleteResponse = { + readonly "object": "organization.invite.deleted" + readonly "id": string + readonly "deleted": boolean +} +export const InviteDeleteResponse = Schema.Struct({ + "object": Schema.Literal("organization.invite.deleted").annotate({ + "description": "The object type, which is always `organization.invite.deleted`" + }), + "id": Schema.String, + "deleted": Schema.Boolean +}) +export type InviteProjectGroupBody = { readonly "group_id": string; readonly "role": string } +export const InviteProjectGroupBody = Schema.Struct({ + "group_id": Schema.String.annotate({ "description": "Identifier of the group to add to the project." }), + "role": Schema.String.annotate({ "description": "Identifier of the project role to grant to the group." }) +}).annotate({ "description": "Request payload for granting a group access to a project." }) +export type InviteRequest = { + readonly "email": string + readonly "role": "reader" | "owner" + readonly "projects"?: ReadonlyArray<{ readonly "id": string; readonly "role": "member" | "owner" }> +} +export const InviteRequest = Schema.Struct({ + "email": Schema.String.annotate({ "description": "Send an email to this address" }), + "role": Schema.Literals(["reader", "owner"]).annotate({ "description": "`owner` or `reader`" }), + "projects": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "id": Schema.String.annotate({ "description": "Project's public ID" }), + "role": Schema.Literals(["member", "owner"]).annotate({ "description": "Project membership role" }) + }) + ).annotate({ + "description": + "An array of projects to which membership is granted at the same time the org invite is accepted. If omitted, the user will be invited to the default project for compatibility with legacy behavior. If empty list is passed, the user will not be invited to any projects, including the default one." + }) + ) +}) +export type LocalShellToolCallOutput = { + readonly "type": "local_shell_call_output" + readonly "id": string + readonly "output": string + readonly "status"?: "in_progress" | "completed" | "incomplete" | null + readonly "call_id": unknown +} +export const LocalShellToolCallOutput = Schema.Struct({ + "type": Schema.Literal("local_shell_call_output").annotate({ + "description": "The type of the local shell tool call output. Always `local_shell_call_output`.\n" + }), + "id": Schema.String.annotate({ + "description": "The unique ID of the local shell tool call generated by the model.\n" + }), + "output": Schema.String.annotate({ "description": "A JSON string of the output of the local shell tool call.\n" }), + "status": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n" + }), + Schema.Null + ]) + ), + "call_id": Schema.Unknown +}).annotate({ "title": "Local shell call output", "description": "The output of a local shell tool call.\n" }) +export type LogProbProperties = { + readonly "token": string + readonly "logprob": number + readonly "bytes": ReadonlyArray +} +export const LogProbProperties = Schema.Struct({ + "token": Schema.String.annotate({ "description": "The token that was used to generate the log probability.\n" }), + "logprob": Schema.Number.annotate({ "description": "The log probability of the token.\n" }).check(Schema.isFinite()), + "bytes": Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": "The bytes that were used to generate the log probability.\n" + }) +}).annotate({ "description": "A log probability object.\n" }) +export type MCPApprovalRequest = { + readonly "type": "mcp_approval_request" + readonly "id": string + readonly "server_label": string + readonly "name": string + readonly "arguments": string +} +export const MCPApprovalRequest = Schema.Struct({ + "type": Schema.Literal("mcp_approval_request").annotate({ + "description": "The type of the item. Always `mcp_approval_request`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the approval request.\n" }), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server making the request.\n" }), + "name": Schema.String.annotate({ "description": "The name of the tool to run.\n" }), + "arguments": Schema.String.annotate({ "description": "A JSON string of arguments for the tool.\n" }) +}).annotate({ "title": "MCP approval request", "description": "A request for human approval of a tool invocation.\n" }) +export type MCPApprovalResponseResource = { + readonly "type": "mcp_approval_response" + readonly "id": string + readonly "approval_request_id": string + readonly "approve": boolean + readonly "reason"?: string | null + readonly "request_id": unknown +} +export const MCPApprovalResponseResource = Schema.Struct({ + "type": Schema.Literal("mcp_approval_response").annotate({ + "description": "The type of the item. Always `mcp_approval_response`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the approval response\n" }), + "approval_request_id": Schema.String.annotate({ "description": "The ID of the approval request being answered.\n" }), + "approve": Schema.Boolean.annotate({ "description": "Whether the request was approved.\n" }), + "reason": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "Optional reason for the decision.\n" }), Schema.Null]) + ), + "request_id": Schema.Unknown +}).annotate({ "title": "MCP approval response", "description": "A response to an MCP approval request.\n" }) +export type MCPListToolsTool = { + readonly "name": string + readonly "description"?: string | null + readonly "input_schema": {} + readonly "annotations"?: {} | null +} +export const MCPListToolsTool = Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the tool.\n" }), + "description": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "The description of the tool.\n" }), Schema.Null]) + ), + "input_schema": Schema.Struct({}).annotate({ "description": "The JSON schema describing the tool's input.\n" }), + "annotations": Schema.optionalKey( + Schema.Union([ + Schema.Struct({}).annotate({ "description": "Additional annotations about the tool.\n" }), + Schema.Null + ]) + ) +}).annotate({ "title": "MCP list tools tool", "description": "A tool available on an MCP server.\n" }) +export type MCPToolCall = { + readonly "type": "mcp_call" + readonly "id": string + readonly "server_label": string + readonly "name": string + readonly "arguments": string + readonly "output"?: string | null + readonly "error"?: string | null + readonly "status"?: "in_progress" | "completed" | "incomplete" | "calling" | "failed" + readonly "approval_request_id"?: string | null +} +export const MCPToolCall = Schema.Struct({ + "type": Schema.Literal("mcp_call").annotate({ "description": "The type of the item. Always `mcp_call`.\n" }), + "id": Schema.String.annotate({ "description": "The unique ID of the tool call.\n" }), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server running the tool.\n" }), + "name": Schema.String.annotate({ "description": "The name of the tool that was run.\n" }), + "arguments": Schema.String.annotate({ "description": "A JSON string of the arguments passed to the tool.\n" }), + "output": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "The output from the tool call.\n" }), Schema.Null]) + ), + "error": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "The error from the tool call, if any.\n" }), Schema.Null]) + ), + "status": Schema.optionalKey( + Schema.Literals(["in_progress", "completed", "incomplete", "calling", "failed"]).annotate({ + "description": + "The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or `failed`.\n" + }) + ), + "approval_request_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "Unique identifier for the MCP tool call approval request.\nInclude this value in a subsequent `mcp_approval_response` input to approve or reject the corresponding tool call.\n" + }), + Schema.Null + ]) + ) +}).annotate({ "title": "MCP tool call", "description": "An invocation of a tool on an MCP server.\n" }) +export type MCPToolFilter = { readonly "tool_names"?: ReadonlyArray; readonly "read_only"?: boolean } +export const MCPToolFilter = Schema.Struct({ + "tool_names": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ "title": "MCP allowed tools", "description": "List of allowed tool names." }) + ), + "read_only": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": + "Indicates whether or not a tool modifies data or is read-only. If an\nMCP server is [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint),\nit will match this filter.\n" + }) + ) +}).annotate({ "title": "MCP tool filter", "description": "A filter object to specify which tools are allowed.\n" }) +export type MessageContentImageFileObject = { + readonly "type": "image_file" + readonly "image_file": { readonly "file_id": string; readonly "detail"?: "auto" | "low" | "high" } +} +export const MessageContentImageFileObject = Schema.Struct({ + "type": Schema.Literal("image_file").annotate({ "description": "Always `image_file`." }), + "image_file": Schema.Struct({ + "file_id": Schema.String.annotate({ + "description": + "The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose=\"vision\"` when uploading the File if you need to later display the file content." + }), + "detail": Schema.optionalKey( + Schema.Literals(["auto", "low", "high"]).annotate({ + "description": + "Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`." + }) + ) + }) +}).annotate({ + "title": "Image file", + "description": "References an image [File](/docs/api-reference/files) in the content of a message." +}) +export type MessageContentImageUrlObject = { + readonly "type": "image_url" + readonly "image_url": { readonly "url": string; readonly "detail"?: "auto" | "low" | "high" } +} +export const MessageContentImageUrlObject = Schema.Struct({ + "type": Schema.Literal("image_url").annotate({ "description": "The type of the content part." }), + "image_url": Schema.Struct({ + "url": Schema.String.annotate({ + "description": "The external URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.", + "format": "uri" + }), + "detail": Schema.optionalKey( + Schema.Literals(["auto", "low", "high"]).annotate({ + "description": + "Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`. Default value is `auto`" + }) + ) + }) +}).annotate({ "title": "Image URL", "description": "References an image URL in the content of a message." }) +export type MessageContentRefusalObject = { readonly "type": "refusal"; readonly "refusal": string } +export const MessageContentRefusalObject = Schema.Struct({ + "type": Schema.Literal("refusal").annotate({ "description": "Always `refusal`." }), + "refusal": Schema.String +}).annotate({ "title": "Refusal", "description": "The refusal content generated by the assistant." }) +export type MessageContentTextAnnotationsFileCitationObject = { + readonly "type": "file_citation" + readonly "text": string + readonly "file_citation": { readonly "file_id": string } + readonly "start_index": number + readonly "end_index": number +} +export const MessageContentTextAnnotationsFileCitationObject = Schema.Struct({ + "type": Schema.Literal("file_citation").annotate({ "description": "Always `file_citation`." }), + "text": Schema.String.annotate({ "description": "The text in the message content that needs to be replaced." }), + "file_citation": Schema.Struct({ + "file_id": Schema.String.annotate({ "description": "The ID of the specific File the citation is from." }) + }), + "start_index": Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "end_index": Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) +}).annotate({ + "title": "File citation", + "description": + "A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the \"file_search\" tool to search files." +}) +export type MessageContentTextAnnotationsFilePathObject = { + readonly "type": "file_path" + readonly "text": string + readonly "file_path": { readonly "file_id": string } + readonly "start_index": number + readonly "end_index": number +} +export const MessageContentTextAnnotationsFilePathObject = Schema.Struct({ + "type": Schema.Literal("file_path").annotate({ "description": "Always `file_path`." }), + "text": Schema.String.annotate({ "description": "The text in the message content that needs to be replaced." }), + "file_path": Schema.Struct({ + "file_id": Schema.String.annotate({ "description": "The ID of the file that was generated." }) + }), + "start_index": Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)), + "end_index": Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) +}).annotate({ + "title": "File path", + "description": + "A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file." +}) +export type MessageDeltaContentImageFileObject = { + readonly "index": number + readonly "type": "image_file" + readonly "image_file"?: { readonly "file_id"?: string; readonly "detail"?: "auto" | "low" | "high" } +} +export const MessageDeltaContentImageFileObject = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the content part in the message." }).check( + Schema.isInt() + ), + "type": Schema.Literal("image_file").annotate({ "description": "Always `image_file`." }), + "image_file": Schema.optionalKey(Schema.Struct({ + "file_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The [File](/docs/api-reference/files) ID of the image in the message content. Set `purpose=\"vision\"` when uploading the File if you need to later display the file content." + }) + ), + "detail": Schema.optionalKey( + Schema.Literals(["auto", "low", "high"]).annotate({ + "description": + "Specifies the detail level of the image if specified by the user. `low` uses fewer tokens, you can opt in to high resolution using `high`." + }) + ) + })) +}).annotate({ + "title": "Image file", + "description": "References an image [File](/docs/api-reference/files) in the content of a message." +}) +export type MessageDeltaContentImageUrlObject = { + readonly "index": number + readonly "type": "image_url" + readonly "image_url"?: { readonly "url"?: string; readonly "detail"?: "auto" | "low" | "high" } +} +export const MessageDeltaContentImageUrlObject = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the content part in the message." }).check( + Schema.isInt() + ), + "type": Schema.Literal("image_url").annotate({ "description": "Always `image_url`." }), + "image_url": Schema.optionalKey(Schema.Struct({ + "url": Schema.optionalKey( + Schema.String.annotate({ + "description": "The URL of the image, must be a supported image types: jpeg, jpg, png, gif, webp.", + "format": "uri" + }) + ), + "detail": Schema.optionalKey( + Schema.Literals(["auto", "low", "high"]).annotate({ + "description": + "Specifies the detail level of the image. `low` uses fewer tokens, you can opt in to high resolution using `high`." + }) + ) + })) +}).annotate({ "title": "Image URL", "description": "References an image URL in the content of a message." }) +export type MessageDeltaContentRefusalObject = { + readonly "index": number + readonly "type": "refusal" + readonly "refusal"?: string +} +export const MessageDeltaContentRefusalObject = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the refusal part in the message." }).check( + Schema.isInt() + ), + "type": Schema.Literal("refusal").annotate({ "description": "Always `refusal`." }), + "refusal": Schema.optionalKey(Schema.String) +}).annotate({ "title": "Refusal", "description": "The refusal content that is part of a message." }) +export type MessageDeltaContentTextAnnotationsFileCitationObject = { + readonly "index": number + readonly "type": "file_citation" + readonly "text"?: string + readonly "file_citation"?: { readonly "file_id"?: string; readonly "quote"?: string } + readonly "start_index"?: number + readonly "end_index"?: number +} +export const MessageDeltaContentTextAnnotationsFileCitationObject = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the annotation in the text content part." }).check( + Schema.isInt() + ), + "type": Schema.Literal("file_citation").annotate({ "description": "Always `file_citation`." }), + "text": Schema.optionalKey( + Schema.String.annotate({ "description": "The text in the message content that needs to be replaced." }) + ), + "file_citation": Schema.optionalKey( + Schema.Struct({ + "file_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the specific File the citation is from." }) + ), + "quote": Schema.optionalKey(Schema.String.annotate({ "description": "The specific quote in the file." })) + }) + ), + "start_index": Schema.optionalKey(Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0))), + "end_index": Schema.optionalKey(Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0))) +}).annotate({ + "title": "File citation", + "description": + "A citation within the message that points to a specific quote from a specific File associated with the assistant or the message. Generated when the assistant uses the \"file_search\" tool to search files." +}) +export type MessageDeltaContentTextAnnotationsFilePathObject = { + readonly "index": number + readonly "type": "file_path" + readonly "text"?: string + readonly "file_path"?: { readonly "file_id"?: string } + readonly "start_index"?: number + readonly "end_index"?: number +} +export const MessageDeltaContentTextAnnotationsFilePathObject = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the annotation in the text content part." }).check( + Schema.isInt() + ), + "type": Schema.Literal("file_path").annotate({ "description": "Always `file_path`." }), + "text": Schema.optionalKey( + Schema.String.annotate({ "description": "The text in the message content that needs to be replaced." }) + ), + "file_path": Schema.optionalKey( + Schema.Struct({ + "file_id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the file that was generated." })) + }) + ), + "start_index": Schema.optionalKey(Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0))), + "end_index": Schema.optionalKey(Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0))) +}).annotate({ + "title": "File path", + "description": + "A URL for the file that's generated when the assistant used the `code_interpreter` tool to generate a file." +}) +export type MessagePhase = "commentary" | "final_answer" +export const MessagePhase = Schema.Literals(["commentary", "final_answer"]).annotate({ + "description": + "Labels an `assistant` message as intermediate commentary (`commentary`) or the final answer (`final_answer`).\nFor models like `gpt-5.3-codex` and beyond, when sending follow-up requests, preserve and resend\nphase on all assistant messages — dropping it can degrade performance. Not used for user messages.\n" +}) +export type MessageRequestContentTextObject = { readonly "type": "text"; readonly "text": string } +export const MessageRequestContentTextObject = Schema.Struct({ + "type": Schema.Literal("text").annotate({ "description": "Always `text`." }), + "text": Schema.String.annotate({ "description": "Text content to be sent to the model" }) +}).annotate({ "title": "Text", "description": "The text content that is part of a message." }) +export type Metadata = {} | null +export const Metadata = Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null +]) +export type Model = { + readonly "id": string + readonly "created": number + readonly "object": "model" + readonly "owned_by": string + readonly [x: string]: unknown +} +export const Model = Schema.StructWithRest( + Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The model identifier, which can be referenced in the API endpoints." + }), + "created": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) when the model was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "object": Schema.Literal("model").annotate({ "description": "The object type, which is always \"model\"." }), + "owned_by": Schema.String.annotate({ "description": "The organization that owns the model." }) + }), + [Schema.Record(Schema.String, Schema.Json)] +).annotate({ "title": "Model", "description": "Describes an OpenAI model offering that can be used with the API." }) +export type ModelIdsShared = + | string + | "gpt-5.4" + | "gpt-5.4-mini" + | "gpt-5.4-nano" + | "gpt-5.4-mini-2026-03-17" + | "gpt-5.4-nano-2026-03-17" + | "gpt-5.3-chat-latest" + | "gpt-5.2" + | "gpt-5.2-2025-12-11" + | "gpt-5.2-chat-latest" + | "gpt-5.2-pro" + | "gpt-5.2-pro-2025-12-11" + | "gpt-5.1" + | "gpt-5.1-2025-11-13" + | "gpt-5.1-codex" + | "gpt-5.1-mini" + | "gpt-5.1-chat-latest" + | "gpt-5" + | "gpt-5-mini" + | "gpt-5-nano" + | "gpt-5-2025-08-07" + | "gpt-5-mini-2025-08-07" + | "gpt-5-nano-2025-08-07" + | "gpt-5-chat-latest" + | "gpt-4.1" + | "gpt-4.1-mini" + | "gpt-4.1-nano" + | "gpt-4.1-2025-04-14" + | "gpt-4.1-mini-2025-04-14" + | "gpt-4.1-nano-2025-04-14" + | "o4-mini" + | "o4-mini-2025-04-16" + | "o3" + | "o3-2025-04-16" + | "o3-mini" + | "o3-mini-2025-01-31" + | "o1" + | "o1-2024-12-17" + | "o1-preview" + | "o1-preview-2024-09-12" + | "o1-mini" + | "o1-mini-2024-09-12" + | "gpt-4o" + | "gpt-4o-2024-11-20" + | "gpt-4o-2024-08-06" + | "gpt-4o-2024-05-13" + | "gpt-4o-audio-preview" + | "gpt-4o-audio-preview-2024-10-01" + | "gpt-4o-audio-preview-2024-12-17" + | "gpt-4o-audio-preview-2025-06-03" + | "gpt-4o-mini-audio-preview" + | "gpt-4o-mini-audio-preview-2024-12-17" + | "gpt-4o-search-preview" + | "gpt-4o-mini-search-preview" + | "gpt-4o-search-preview-2025-03-11" + | "gpt-4o-mini-search-preview-2025-03-11" + | "chatgpt-4o-latest" + | "codex-mini-latest" + | "gpt-4o-mini" + | "gpt-4o-mini-2024-07-18" + | "gpt-4-turbo" + | "gpt-4-turbo-2024-04-09" + | "gpt-4-0125-preview" + | "gpt-4-turbo-preview" + | "gpt-4-1106-preview" + | "gpt-4-vision-preview" + | "gpt-4" + | "gpt-4-0314" + | "gpt-4-0613" + | "gpt-4-32k" + | "gpt-4-32k-0314" + | "gpt-4-32k-0613" + | "gpt-3.5-turbo" + | "gpt-3.5-turbo-16k" + | "gpt-3.5-turbo-0301" + | "gpt-3.5-turbo-0613" + | "gpt-3.5-turbo-1106" + | "gpt-3.5-turbo-0125" + | "gpt-3.5-turbo-16k-0613" +export const ModelIdsShared = Schema.Union([ + Schema.String, + Schema.Literals([ + "gpt-5.4", + "gpt-5.4-mini", + "gpt-5.4-nano", + "gpt-5.4-mini-2026-03-17", + "gpt-5.4-nano-2026-03-17", + "gpt-5.3-chat-latest", + "gpt-5.2", + "gpt-5.2-2025-12-11", + "gpt-5.2-chat-latest", + "gpt-5.2-pro", + "gpt-5.2-pro-2025-12-11", + "gpt-5.1", + "gpt-5.1-2025-11-13", + "gpt-5.1-codex", + "gpt-5.1-mini", + "gpt-5.1-chat-latest", + "gpt-5", + "gpt-5-mini", + "gpt-5-nano", + "gpt-5-2025-08-07", + "gpt-5-mini-2025-08-07", + "gpt-5-nano-2025-08-07", + "gpt-5-chat-latest", + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", + "o4-mini", + "o4-mini-2025-04-16", + "o3", + "o3-2025-04-16", + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "o1-preview", + "o1-preview-2024-09-12", + "o1-mini", + "o1-mini-2024-09-12", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-audio-preview", + "gpt-4o-audio-preview-2024-10-01", + "gpt-4o-audio-preview-2024-12-17", + "gpt-4o-audio-preview-2025-06-03", + "gpt-4o-mini-audio-preview", + "gpt-4o-mini-audio-preview-2024-12-17", + "gpt-4o-search-preview", + "gpt-4o-mini-search-preview", + "gpt-4o-search-preview-2025-03-11", + "gpt-4o-mini-search-preview-2025-03-11", + "chatgpt-4o-latest", + "codex-mini-latest", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613" + ]) +]) +export type ModifyCertificateRequest = { readonly "name"?: string } +export const ModifyCertificateRequest = Schema.Struct({ + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The updated name for the certificate" })) +}) +export type NoiseReductionType = "near_field" | "far_field" +export const NoiseReductionType = Schema.Literals(["near_field", "far_field"]).annotate({ + "description": + "Type of noise reduction. `near_field` is for close-talking microphones such as headphones, `far_field` is for far-field microphones such as laptop or conference room microphones.\n" +}) +export type OpenAIFile = { + readonly "id": string + readonly "bytes": number + readonly "created_at": number + readonly "expires_at"?: number | null + readonly "filename": string + readonly "object": "file" + readonly "purpose": + | "assistants" + | "assistants_output" + | "batch" + | "batch_output" + | "fine-tune" + | "fine-tune-results" + | "vision" + | "user_data" + readonly "status": "uploaded" | "processed" | "error" + readonly "status_details"?: string | null + readonly [x: string]: unknown +} +export const OpenAIFile = Schema.StructWithRest( + Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The file identifier, which can be referenced in the API endpoints." + }), + "bytes": Schema.Number.annotate({ "description": "The size of the file, in bytes." }).check(Schema.isInt()), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the file was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "expires_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the file will expire.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "filename": Schema.String.annotate({ "description": "The name of the file." }), + "object": Schema.Literal("file").annotate({ "description": "The object type, which is always `file`." }), + "purpose": Schema.Literals([ + "assistants", + "assistants_output", + "batch", + "batch_output", + "fine-tune", + "fine-tune-results", + "vision", + "user_data" + ]).annotate({ + "description": + "The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`." + }), + "status": Schema.Literals(["uploaded", "processed", "error"]).annotate({ + "description": + "Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`." + }), + "status_details": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`." + }) + ) + }), + [Schema.Record(Schema.String, Schema.Json)] +).annotate({ + "title": "OpenAIFile", + "description": "The `File` object represents a document that has been uploaded to OpenAI." +}) +export type OrganizationCertificate = { + readonly "object": "organization.certificate" + readonly "id": string + readonly "name": string | null + readonly "created_at": number + readonly "certificate_details": { readonly "valid_at"?: number; readonly "expires_at"?: number } + readonly "active": boolean +} +export const OrganizationCertificate = Schema.Struct({ + "object": Schema.Literal("organization.certificate").annotate({ + "description": "The object type, which is always `organization.certificate`." + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The name of the certificate." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the certificate was uploaded.", + "format": "unixtime" + }).check(Schema.isInt()), + "certificate_details": Schema.Struct({ + "valid_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the certificate becomes valid.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "expires_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the certificate expires.", + "format": "unixtime" + }).check(Schema.isInt()) + ) + }), + "active": Schema.Boolean.annotate({ + "description": "Whether the certificate is currently active at the organization level." + }) +}).annotate({ "description": "Represents an individual certificate configured at the organization level." }) +export type OrganizationProjectCertificate = { + readonly "object": "organization.project.certificate" + readonly "id": string + readonly "name": string | null + readonly "created_at": number + readonly "certificate_details": { readonly "valid_at"?: number; readonly "expires_at"?: number } + readonly "active": boolean +} +export const OrganizationProjectCertificate = Schema.Struct({ + "object": Schema.Literal("organization.project.certificate").annotate({ + "description": "The object type, which is always `organization.project.certificate`." + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The name of the certificate." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the certificate was uploaded.", + "format": "unixtime" + }).check(Schema.isInt()), + "certificate_details": Schema.Struct({ + "valid_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the certificate becomes valid.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "expires_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the certificate expires.", + "format": "unixtime" + }).check(Schema.isInt()) + ) + }), + "active": Schema.Boolean.annotate({ + "description": "Whether the certificate is currently active at the project level." + }) +}).annotate({ "description": "Represents an individual certificate configured at the project level." }) +export type ParallelToolCalls = boolean +export const ParallelToolCalls = Schema.Boolean.annotate({ + "description": + "Whether to enable [parallel function calling](/docs/guides/function-calling#configuring-parallel-function-calling) during tool use." +}) +export type PartialImages = number | null +export const PartialImages = Schema.Union([ + Schema.Number.annotate({ + "description": + "The number of partial images to generate. This parameter is used for\nstreaming responses that return partial images. Value must be between 0 and 3.\nWhen set to 0, the response will be a single image sent in one streaming event.\n\nNote that the final image may be sent before the full number of partial images\nare generated if the full image is generated more quickly.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(3)), + Schema.Null +]) +export type Project = { + readonly "id": string + readonly "object": "organization.project" + readonly "name"?: string | null + readonly "created_at": number + readonly "archived_at"?: number | null + readonly "status"?: string | null + readonly "external_key_id"?: string | null +} +export const Project = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "object": Schema.Literal("organization.project").annotate({ + "description": "The object type, which is always `organization.project`" + }), + "name": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "The name of the project. This appears in reporting." + }) + ), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the project was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "archived_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the project was archived or `null`.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "status": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "`active` or `archived`" }) + ), + "external_key_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "The external key associated with the project." + }) + ) +}).annotate({ "description": "Represents an individual project." }) +export type ProjectApiKeyDeleteResponse = { + readonly "object": "organization.project.api_key.deleted" + readonly "id": string + readonly "deleted": boolean +} +export const ProjectApiKeyDeleteResponse = Schema.Struct({ + "object": Schema.Literal("organization.project.api_key.deleted"), + "id": Schema.String, + "deleted": Schema.Boolean +}) +export type ProjectApiKeyOwnerServiceAccount = { + readonly "id": string + readonly "name": string + readonly "created_at": number + readonly "role": string +} +export const ProjectApiKeyOwnerServiceAccount = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.String.annotate({ "description": "The name of the service account." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the service account was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "role": Schema.String.annotate({ "description": "The service account's project role." }) +}).annotate({ "description": "The service account that owns a project API key." }) +export type ProjectApiKeyOwnerUser = { + readonly "id": string + readonly "email": string + readonly "name": string + readonly "created_at": number + readonly "role": string +} +export const ProjectApiKeyOwnerUser = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "email": Schema.String.annotate({ "description": "The email address of the user." }), + "name": Schema.String.annotate({ "description": "The name of the user." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the user was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "role": Schema.String.annotate({ "description": "The user's project role." }) +}).annotate({ "description": "The user that owns a project API key." }) +export type ProjectCreateRequest = { + readonly "name": string + readonly "geography"?: string | null + readonly "external_key_id"?: string | null +} +export const ProjectCreateRequest = Schema.Struct({ + "name": Schema.String.annotate({ "description": "The friendly name of the project, this name appears in reports." }), + "geography": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Create the project with the specified data residency region. Your organization must have access to Data residency functionality in order to use. See [data residency controls](/docs/guides/your-data#data-residency-controls) to review the functionality and limitations of setting this field." + }) + ), + "external_key_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "External key ID to associate with the project." + }) + ) +}) +export type ProjectGroup = { + readonly "object": "project.group" + readonly "project_id": string + readonly "group_id": string + readonly "group_name": string + readonly "group_type": string + readonly "created_at": number +} +export const ProjectGroup = Schema.Struct({ + "object": Schema.Literal("project.group").annotate({ "description": "Always `project.group`." }), + "project_id": Schema.String.annotate({ "description": "Identifier of the project." }), + "group_id": Schema.String.annotate({ "description": "Identifier of the group that has access to the project." }), + "group_name": Schema.String.annotate({ "description": "Display name of the group." }), + "group_type": Schema.String.annotate({ "description": "The type of the group." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the group was granted project access.", + "format": "unixtime" + }).check(Schema.isInt()) +}).annotate({ "description": "Details about a group's membership in a project." }) +export type ProjectGroupDeletedResource = { readonly "object": "project.group.deleted"; readonly "deleted": boolean } +export const ProjectGroupDeletedResource = Schema.Struct({ + "object": Schema.Literal("project.group.deleted").annotate({ "description": "Always `project.group.deleted`." }), + "deleted": Schema.Boolean.annotate({ "description": "Whether the group membership in the project was removed." }) +}).annotate({ "description": "Confirmation payload returned after removing a group from a project." }) +export type ProjectModelPermissions = { + readonly "object": "project.model_permissions" + readonly "mode": "allow_list" | "deny_list" + readonly "model_ids": ReadonlyArray +} +export const ProjectModelPermissions = Schema.Struct({ + "object": Schema.Literal("project.model_permissions").annotate({ + "description": "The object type, which is always `project.model_permissions`." + }), + "mode": Schema.Literals(["allow_list", "deny_list"]).annotate({ + "description": "Whether the project uses an allowlist or a denylist." + }), + "model_ids": Schema.Array(Schema.String).annotate({ + "description": "The model IDs included in the model permissions policy." + }) +}).annotate({ "description": "Represents the model allowlist or denylist policy for a project." }) +export type ProjectModelPermissionsDeleteResponse = { + readonly "object": "project.model_permissions.deleted" + readonly "deleted": boolean +} +export const ProjectModelPermissionsDeleteResponse = Schema.Struct({ + "object": Schema.Literal("project.model_permissions.deleted").annotate({ + "description": "The object type, which is always `project.model_permissions.deleted`." + }), + "deleted": Schema.Boolean.annotate({ "description": "Whether the project model permissions were deleted." }) +}).annotate({ "description": "Confirmation payload returned after deleting project model permissions." }) +export type ProjectModelPermissionsUpdateRequest = { + readonly "mode": "allow_list" | "deny_list" + readonly "model_ids": ReadonlyArray +} +export const ProjectModelPermissionsUpdateRequest = Schema.Struct({ + "mode": Schema.Literals(["allow_list", "deny_list"]).annotate({ + "description": "The model permissions mode to apply." + }), + "model_ids": Schema.Array(Schema.String).annotate({ + "description": "The model IDs included in this permissions policy." + }) +}) +export type ProjectRateLimit = { + readonly "object": "project.rate_limit" + readonly "id": string + readonly "model": string + readonly "max_requests_per_1_minute": number + readonly "max_tokens_per_1_minute": number + readonly "max_images_per_1_minute"?: number + readonly "max_audio_megabytes_per_1_minute"?: number + readonly "max_requests_per_1_day"?: number + readonly "batch_1_day_max_input_tokens"?: number +} +export const ProjectRateLimit = Schema.Struct({ + "object": Schema.Literal("project.rate_limit").annotate({ + "description": "The object type, which is always `project.rate_limit`" + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints." }), + "model": Schema.String.annotate({ "description": "The model this rate limit applies to." }), + "max_requests_per_1_minute": Schema.Number.annotate({ "description": "The maximum requests per minute." }).check( + Schema.isInt() + ), + "max_tokens_per_1_minute": Schema.Number.annotate({ "description": "The maximum tokens per minute." }).check( + Schema.isInt() + ), + "max_images_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum images per minute. Only present for relevant models." }).check( + Schema.isInt() + ) + ), + "max_audio_megabytes_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The maximum audio megabytes per minute. Only present for relevant models." + }).check(Schema.isInt()) + ), + "max_requests_per_1_day": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum requests per day. Only present for relevant models." }).check( + Schema.isInt() + ) + ), + "batch_1_day_max_input_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The maximum batch input tokens per day. Only present for relevant models." + }).check(Schema.isInt()) + ) +}).annotate({ "description": "Represents a project rate limit config." }) +export type ProjectRateLimitUpdateRequest = { + readonly "max_requests_per_1_minute"?: number + readonly "max_tokens_per_1_minute"?: number + readonly "max_images_per_1_minute"?: number + readonly "max_audio_megabytes_per_1_minute"?: number + readonly "max_requests_per_1_day"?: number + readonly "batch_1_day_max_input_tokens"?: number +} +export const ProjectRateLimitUpdateRequest = Schema.Struct({ + "max_requests_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum requests per minute." }).check(Schema.isInt()) + ), + "max_tokens_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum tokens per minute." }).check(Schema.isInt()) + ), + "max_images_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum images per minute. Only relevant for certain models." }).check( + Schema.isInt() + ) + ), + "max_audio_megabytes_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The maximum audio megabytes per minute. Only relevant for certain models." + }).check(Schema.isInt()) + ), + "max_requests_per_1_day": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum requests per day. Only relevant for certain models." }).check( + Schema.isInt() + ) + ), + "batch_1_day_max_input_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The maximum batch input tokens per day. Only relevant for certain models." + }).check(Schema.isInt()) + ) +}) +export type ProjectServiceAccount = { + readonly "object": "organization.project.service_account" + readonly "id": string + readonly "name": string + readonly "role": "owner" | "member" + readonly "created_at": number +} +export const ProjectServiceAccount = Schema.Struct({ + "object": Schema.Literal("organization.project.service_account").annotate({ + "description": "The object type, which is always `organization.project.service_account`" + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.String.annotate({ "description": "The name of the service account" }), + "role": Schema.Literals(["owner", "member"]).annotate({ "description": "`owner` or `member`" }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the service account was created", + "format": "unixtime" + }).check(Schema.isInt()) +}).annotate({ "description": "Represents an individual service account in a project." }) +export type ProjectServiceAccountApiKey = { + readonly "object": "organization.project.service_account.api_key" + readonly "value": string + readonly "name": string + readonly "created_at": number + readonly "id": string +} +export const ProjectServiceAccountApiKey = Schema.Struct({ + "object": Schema.Literal("organization.project.service_account.api_key").annotate({ + "description": "The object type, which is always `organization.project.service_account.api_key`" + }), + "value": Schema.String, + "name": Schema.String, + "created_at": Schema.Number.annotate({ "format": "unixtime" }).check(Schema.isInt()), + "id": Schema.String +}) +export type ProjectServiceAccountCreateRequest = { readonly "name": string } +export const ProjectServiceAccountCreateRequest = Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the service account being created." }) +}) +export type ProjectServiceAccountDeleteResponse = { + readonly "object": "organization.project.service_account.deleted" + readonly "id": string + readonly "deleted": boolean +} +export const ProjectServiceAccountDeleteResponse = Schema.Struct({ + "object": Schema.Literal("organization.project.service_account.deleted"), + "id": Schema.String, + "deleted": Schema.Boolean +}) +export type ProjectUpdateRequest = { + readonly "name"?: string | null + readonly "external_key_id"?: string | null + readonly "geography"?: string | null +} +export const ProjectUpdateRequest = Schema.Struct({ + "name": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "The updated name of the project, this name appears in reports." + }) + ), + "external_key_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "External key ID to associate with the project." + }) + ), + "geography": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "Geography for the project." }) + ) +}) +export type ProjectUser = { + readonly "object": "organization.project.user" + readonly "id": string + readonly "name"?: string | null + readonly "email"?: string | null + readonly "role": string + readonly "added_at": number +} +export const ProjectUser = Schema.Struct({ + "object": Schema.Literal("organization.project.user").annotate({ + "description": "The object type, which is always `organization.project.user`" + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The name of the user" }) + ), + "email": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The email address of the user" }) + ), + "role": Schema.String.annotate({ "description": "`owner` or `member`" }), + "added_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the project was added.", + "format": "unixtime" + }).check(Schema.isInt()) +}).annotate({ "description": "Represents an individual user in a project." }) +export type ProjectUserCreateRequest = { + readonly "user_id"?: string | null + readonly "email"?: string | null + readonly "role": string +} +export const ProjectUserCreateRequest = Schema.Struct({ + "user_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The ID of the user." }) + ), + "email": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "Email of the user to add." }) + ), + "role": Schema.String.annotate({ "description": "`owner` or `member`" }) +}) +export type ProjectUserDeleteResponse = { + readonly "object": "organization.project.user.deleted" + readonly "id": string + readonly "deleted": boolean +} +export const ProjectUserDeleteResponse = Schema.Struct({ + "object": Schema.Literal("organization.project.user.deleted"), + "id": Schema.String, + "deleted": Schema.Boolean +}) +export type ProjectUserUpdateRequest = { readonly "role"?: string | null } +export const ProjectUserUpdateRequest = Schema.Struct({ + "role": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "`owner` or `member`" }) + ) +}) +export type PublicAssignOrganizationGroupRoleBody = { readonly "role_id": string } +export const PublicAssignOrganizationGroupRoleBody = Schema.Struct({ + "role_id": Schema.String.annotate({ "description": "Identifier of the role to assign." }) +}).annotate({ "description": "Request payload for assigning a role to a group or user." }) +export type PublicCreateOrganizationRoleBody = { + readonly "role_name": string + readonly "permissions": ReadonlyArray + readonly "description"?: string | null +} +export const PublicCreateOrganizationRoleBody = Schema.Struct({ + "role_name": Schema.String.annotate({ "description": "Unique name for the role." }), + "permissions": Schema.Array(Schema.String).annotate({ "description": "Permissions to grant to the role." }), + "description": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "Optional description of the role." }) + ) +}).annotate({ "description": "Request payload for creating a custom role." }) +export type PublicUpdateOrganizationRoleBody = { + readonly "permissions"?: ReadonlyArray | null + readonly "description"?: string | null + readonly "role_name"?: string | null +} +export const PublicUpdateOrganizationRoleBody = Schema.Struct({ + "permissions": Schema.optionalKey( + Schema.Union([Schema.Array(Schema.String), Schema.Null]).annotate({ + "description": "Updated set of permissions for the role." + }) + ), + "description": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "New description for the role." }) + ), + "role_name": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "New name for the role." }) + ) +}).annotate({ "description": "Request payload for updating an existing role." }) +export type RealtimeAudioFormats = { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" +} | { readonly "type"?: "audio/pcma" } +export const RealtimeAudioFormats = Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) +]) +export type RealtimeCallReferRequest = { readonly "target_uri": string } +export const RealtimeCallReferRequest = Schema.Struct({ + "target_uri": Schema.String.annotate({ + "description": + "URI that should appear in the SIP Refer-To header. Supports values like\n`tel:+14155550123` or `sip:agent@example.com`." + }) +}).annotate({ + "title": "Realtime call refer request", + "description": "Parameters required to transfer a SIP call to a new destination using the\nRealtime API." +}) +export type RealtimeCallRejectRequest = { readonly "status_code"?: number } +export const RealtimeCallRejectRequest = Schema.Struct({ + "status_code": Schema.optionalKey( + Schema.Number.annotate({ + "description": "SIP response code to send back to the caller. Defaults to `603` (Decline)\nwhen omitted." + }).check(Schema.isInt()) + ) +}).annotate({ + "title": "Realtime call reject request", + "description": "Parameters used to decline an incoming SIP call handled by the Realtime API." +}) +export type RealtimeClientEventConversationItemDelete = { + readonly "event_id"?: string + readonly "type": "conversation.item.delete" + readonly "item_id": string +} +export const RealtimeClientEventConversationItemDelete = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("conversation.item.delete").annotate({ + "description": "The event type, must be `conversation.item.delete`." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the item to delete." }) +}).annotate({ + "description": + "Send this event when you want to remove any item from the conversation \nhistory. The server will respond with a `conversation.item.deleted` event, \nunless the item does not exist in the conversation history, in which case the \nserver will respond with an error.\n" +}) +export type RealtimeClientEventConversationItemRetrieve = { + readonly "event_id"?: string + readonly "type": "conversation.item.retrieve" + readonly "item_id": string +} +export const RealtimeClientEventConversationItemRetrieve = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("conversation.item.retrieve").annotate({ + "description": "The event type, must be `conversation.item.retrieve`." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the item to retrieve." }) +}).annotate({ + "description": + "Send this event when you want to retrieve the server's representation of a specific item in the conversation history. This is useful, for example, to inspect user audio after noise cancellation and VAD.\nThe server will respond with a `conversation.item.retrieved` event, \nunless the item does not exist in the conversation history, in which case the \nserver will respond with an error.\n" +}) +export type RealtimeClientEventConversationItemTruncate = { + readonly "event_id"?: string + readonly "type": "conversation.item.truncate" + readonly "item_id": string + readonly "content_index": number + readonly "audio_end_ms": number +} +export const RealtimeClientEventConversationItemTruncate = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("conversation.item.truncate").annotate({ + "description": "The event type, must be `conversation.item.truncate`." + }), + "item_id": Schema.String.annotate({ + "description": + "The ID of the assistant message item to truncate. Only assistant message \nitems can be truncated.\n" + }), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part to truncate. Set this to `0`." + }).check(Schema.isInt()), + "audio_end_ms": Schema.Number.annotate({ + "description": + "Inclusive duration up to which audio is truncated, in milliseconds. If \nthe audio_end_ms is greater than the actual audio duration, the server \nwill respond with an error.\n" + }).check(Schema.isInt()) +}).annotate({ + "description": + "Send this event to truncate a previous assistant message’s audio. The server \nwill produce audio faster than realtime, so this event is useful when the user \ninterrupts to truncate audio that has already been sent to the client but not \nyet played. This will synchronize the server's understanding of the audio with \nthe client's playback.\n\nTruncating audio will delete the server-side text transcript to ensure there \nis not text in the context that hasn't been heard by the user.\n\nIf successful, the server will respond with a `conversation.item.truncated` \nevent. \n" +}) +export type RealtimeClientEventInputAudioBufferAppend = { + readonly "event_id"?: string + readonly "type": "input_audio_buffer.append" + readonly "audio": string +} +export const RealtimeClientEventInputAudioBufferAppend = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("input_audio_buffer.append").annotate({ + "description": "The event type, must be `input_audio_buffer.append`." + }), + "audio": Schema.String.annotate({ + "description": + "Base64-encoded audio bytes. This must be in the format specified by the \n`input_audio_format` field in the session configuration.\n" + }) +}).annotate({ + "description": + "Send this event to append audio bytes to the input audio buffer. The audio \nbuffer is temporary storage you can write to and later commit. A \"commit\" will create a new\nuser message item in the conversation history from the buffer content and clear the buffer.\nInput audio transcription (if enabled) will be generated when the buffer is committed.\n\nIf VAD is enabled the audio buffer is used to detect speech and the server will decide \nwhen to commit. When Server VAD is disabled, you must commit the audio buffer\nmanually. Input audio noise reduction operates on writes to the audio buffer.\n\nThe client may choose how much audio to place in each event up to a maximum \nof 15 MiB, for example streaming smaller chunks from the client may allow the \nVAD to be more responsive. Unlike most other client events, the server will \nnot send a confirmation response to this event.\n" +}) +export type RealtimeClientEventInputAudioBufferClear = { + readonly "event_id"?: string + readonly "type": "input_audio_buffer.clear" +} +export const RealtimeClientEventInputAudioBufferClear = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("input_audio_buffer.clear").annotate({ + "description": "The event type, must be `input_audio_buffer.clear`." + }) +}).annotate({ + "description": + "Send this event to clear the audio bytes in the buffer. The server will \nrespond with an `input_audio_buffer.cleared` event.\n" +}) +export type RealtimeClientEventInputAudioBufferCommit = { + readonly "event_id"?: string + readonly "type": "input_audio_buffer.commit" +} +export const RealtimeClientEventInputAudioBufferCommit = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("input_audio_buffer.commit").annotate({ + "description": "The event type, must be `input_audio_buffer.commit`." + }) +}).annotate({ + "description": + "Send this event to commit the user input audio buffer, which will create a new user message item in the conversation. This event will produce an error if the input audio buffer is empty. When in Server VAD mode, the client does not need to send this event, the server will commit the audio buffer automatically.\n\nCommitting the input audio buffer will trigger input audio transcription (if enabled in session configuration), but it will not create a response from the model. The server will respond with an `input_audio_buffer.committed` event.\n" +}) +export type RealtimeClientEventOutputAudioBufferClear = { + readonly "event_id"?: string + readonly "type": "output_audio_buffer.clear" +} +export const RealtimeClientEventOutputAudioBufferClear = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The unique ID of the client event used for error handling." }) + ), + "type": Schema.Literal("output_audio_buffer.clear").annotate({ + "description": "The event type, must be `output_audio_buffer.clear`." + }) +}).annotate({ + "description": + "**WebRTC/SIP Only:** Emit to cut off the current audio response. This will trigger the server to\nstop generating audio and emit a `output_audio_buffer.cleared` event. This\nevent should be preceded by a `response.cancel` client event to stop the\ngeneration of the current response.\n[Learn more](/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n" +}) +export type RealtimeClientEventResponseCancel = { + readonly "event_id"?: string + readonly "type": "response.cancel" + readonly "response_id"?: string +} +export const RealtimeClientEventResponseCancel = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("response.cancel").annotate({ "description": "The event type, must be `response.cancel`." }), + "response_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A specific response ID to cancel - if not provided, will cancel an \nin-progress response in the default conversation.\n" + }) + ) +}).annotate({ + "description": + "Send this event to cancel an in-progress response. The server will respond \nwith a `response.done` event with a status of `response.status=cancelled`. If \nthere is no response to cancel, the server will respond with an error. It's safe\nto call `response.cancel` even if no response is in progress, an error will be\nreturned the session will remain unaffected.\n" +}) +export type RealtimeConversationItemFunctionCall = { + readonly "id"?: string + readonly "object"?: "realtime.item" + readonly "type": "function_call" + readonly "status"?: "completed" | "incomplete" | "in_progress" + readonly "call_id"?: string + readonly "name": string + readonly "arguments": string +} +export const RealtimeConversationItemFunctionCall = Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ + "description": "The unique ID of the item. This may be provided by the client or generated by the server." + }) + ), + "object": Schema.optionalKey( + Schema.Literal("realtime.item").annotate({ + "description": + "Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item." + }) + ), + "type": Schema.Literal("function_call").annotate({ "description": "The type of the item. Always `function_call`." }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "incomplete", "in_progress"]).annotate({ + "description": "The status of the item. Has no effect on the conversation." + }) + ), + "call_id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the function call." })), + "name": Schema.String.annotate({ "description": "The name of the function being called." }), + "arguments": Schema.String.annotate({ + "description": + "The arguments of the function call. This is a JSON-encoded string representing the arguments passed to the function, for example `{\"arg1\": \"value1\", \"arg2\": 42}`." + }) +}).annotate({ + "title": "Realtime function call item", + "description": "A function call item in a Realtime conversation." +}) +export type RealtimeConversationItemFunctionCallOutput = { + readonly "id"?: string + readonly "object"?: "realtime.item" + readonly "type": "function_call_output" + readonly "status"?: "completed" | "incomplete" | "in_progress" + readonly "call_id": string + readonly "output": string +} +export const RealtimeConversationItemFunctionCallOutput = Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ + "description": "The unique ID of the item. This may be provided by the client or generated by the server." + }) + ), + "object": Schema.optionalKey( + Schema.Literal("realtime.item").annotate({ + "description": + "Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item." + }) + ), + "type": Schema.Literal("function_call_output").annotate({ + "description": "The type of the item. Always `function_call_output`." + }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "incomplete", "in_progress"]).annotate({ + "description": "The status of the item. Has no effect on the conversation." + }) + ), + "call_id": Schema.String.annotate({ "description": "The ID of the function call this output is for." }), + "output": Schema.String.annotate({ + "description": + "The output of the function call, this is free text and can contain any information or simply be empty." + }) +}).annotate({ + "title": "Realtime function call output item", + "description": "A function call output item in a Realtime conversation." +}) +export type RealtimeConversationItemMessageAssistant = { + readonly "id"?: string + readonly "object"?: "realtime.item" + readonly "type": "message" + readonly "status"?: "completed" | "incomplete" | "in_progress" + readonly "role": "assistant" + readonly "content": ReadonlyArray< + { + readonly "type"?: "output_text" | "output_audio" + readonly "text"?: string + readonly "audio"?: string + readonly "transcript"?: string + } + > +} +export const RealtimeConversationItemMessageAssistant = Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ + "description": "The unique ID of the item. This may be provided by the client or generated by the server." + }) + ), + "object": Schema.optionalKey( + Schema.Literal("realtime.item").annotate({ + "description": + "Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item." + }) + ), + "type": Schema.Literal("message").annotate({ "description": "The type of the item. Always `message`." }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "incomplete", "in_progress"]).annotate({ + "description": "The status of the item. Has no effect on the conversation." + }) + ), + "role": Schema.Literal("assistant").annotate({ + "description": "The role of the message sender. Always `assistant`." + }), + "content": Schema.Array(Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literals(["output_text", "output_audio"]).annotate({ + "description": + "The content type, `output_text` or `output_audio` depending on the session `output_modalities` configuration." + }) + ), + "text": Schema.optionalKey(Schema.String.annotate({ "description": "The text content." })), + "audio": Schema.optionalKey( + Schema.String.annotate({ + "description": + "Base64-encoded audio bytes, these will be parsed as the format specified in the session output audio type configuration. This defaults to PCM 16-bit 24kHz mono if not specified." + }) + ), + "transcript": Schema.optionalKey( + Schema.String.annotate({ + "description": "The transcript of the audio content, this will always be present if the output type is `audio`." + }) + ) + })).annotate({ "description": "The content of the message." }) +}).annotate({ + "title": "Realtime assistant message item", + "description": "An assistant message item in a Realtime conversation." +}) +export type RealtimeConversationItemMessageSystem = { + readonly "id"?: string + readonly "object"?: "realtime.item" + readonly "type": "message" + readonly "status"?: "completed" | "incomplete" | "in_progress" + readonly "role": "system" + readonly "content": ReadonlyArray<{ readonly "type"?: "input_text"; readonly "text"?: string }> +} +export const RealtimeConversationItemMessageSystem = Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ + "description": "The unique ID of the item. This may be provided by the client or generated by the server." + }) + ), + "object": Schema.optionalKey( + Schema.Literal("realtime.item").annotate({ + "description": + "Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item." + }) + ), + "type": Schema.Literal("message").annotate({ "description": "The type of the item. Always `message`." }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "incomplete", "in_progress"]).annotate({ + "description": "The status of the item. Has no effect on the conversation." + }) + ), + "role": Schema.Literal("system").annotate({ "description": "The role of the message sender. Always `system`." }), + "content": Schema.Array( + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("input_text").annotate({ + "description": "The content type. Always `input_text` for system messages." + }) + ), + "text": Schema.optionalKey(Schema.String.annotate({ "description": "The text content." })) + }) + ).annotate({ "description": "The content of the message." }) +}).annotate({ + "title": "Realtime system message item", + "description": + "A system message in a Realtime conversation can be used to provide additional context or instructions to the model. This is similar but distinct from the instruction prompt provided at the start of a conversation, as system messages can be added at any point in the conversation. For major changes to the conversation's behavior, use instructions, but for smaller updates (e.g. \"the user is now asking about a different topic\"), use system messages." +}) +export type RealtimeConversationItemMessageUser = { + readonly "id"?: string + readonly "object"?: "realtime.item" + readonly "type": "message" + readonly "status"?: "completed" | "incomplete" | "in_progress" + readonly "role": "user" + readonly "content": ReadonlyArray< + { + readonly "type"?: "input_text" | "input_audio" | "input_image" + readonly "text"?: string + readonly "audio"?: string + readonly "image_url"?: string + readonly "detail"?: "auto" | "low" | "high" + readonly "transcript"?: string + } + > +} +export const RealtimeConversationItemMessageUser = Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ + "description": "The unique ID of the item. This may be provided by the client or generated by the server." + }) + ), + "object": Schema.optionalKey( + Schema.Literal("realtime.item").annotate({ + "description": + "Identifier for the API object being returned - always `realtime.item`. Optional when creating a new item." + }) + ), + "type": Schema.Literal("message").annotate({ "description": "The type of the item. Always `message`." }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "incomplete", "in_progress"]).annotate({ + "description": "The status of the item. Has no effect on the conversation." + }) + ), + "role": Schema.Literal("user").annotate({ "description": "The role of the message sender. Always `user`." }), + "content": Schema.Array(Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literals(["input_text", "input_audio", "input_image"]).annotate({ + "description": "The content type (`input_text`, `input_audio`, or `input_image`)." + }) + ), + "text": Schema.optionalKey(Schema.String.annotate({ "description": "The text content (for `input_text`)." })), + "audio": Schema.optionalKey( + Schema.String.annotate({ + "description": + "Base64-encoded audio bytes (for `input_audio`), these will be parsed as the format specified in the session input audio type configuration. This defaults to PCM 16-bit 24kHz mono if not specified." + }) + ), + "image_url": Schema.optionalKey( + Schema.String.annotate({ + "description": + "Base64-encoded image bytes (for `input_image`) as a data URI. For example `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...`. Supported formats are PNG and JPEG.", + "format": "uri" + }) + ), + "detail": Schema.optionalKey( + Schema.Literals(["auto", "low", "high"]).annotate({ + "description": "The detail level of the image (for `input_image`). `auto` will default to `high`." + }) + ), + "transcript": Schema.optionalKey( + Schema.String.annotate({ + "description": + "Transcript of the audio (for `input_audio`). This is not sent to the model, but will be attached to the message item for reference." + }) + ) + })).annotate({ "description": "The content of the message." }) +}).annotate({ "title": "Realtime user message item", "description": "A user message item in a Realtime conversation." }) +export type RealtimeFunctionTool = { + readonly "type"?: "function" + readonly "name"?: string + readonly "description"?: string + readonly "parameters"?: {} +} +export const RealtimeFunctionTool = Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("function").annotate({ "description": "The type of the tool, i.e. `function`." }) + ), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the function." })), + "description": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The description of the function, including guidance on when and how\nto call it, and guidance about what to tell the user when calling\n(if anything).\n" + }) + ), + "parameters": Schema.optionalKey( + Schema.Struct({}).annotate({ "description": "Parameters of the function in JSON Schema." }) + ) +}).annotate({ "title": "Function tool" }) +export type RealtimeMCPApprovalRequest = { + readonly "type": "mcp_approval_request" + readonly "id": string + readonly "server_label": string + readonly "name": string + readonly "arguments": string +} +export const RealtimeMCPApprovalRequest = Schema.Struct({ + "type": Schema.Literal("mcp_approval_request").annotate({ + "description": "The type of the item. Always `mcp_approval_request`." + }), + "id": Schema.String.annotate({ "description": "The unique ID of the approval request." }), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server making the request." }), + "name": Schema.String.annotate({ "description": "The name of the tool to run." }), + "arguments": Schema.String.annotate({ "description": "A JSON string of arguments for the tool." }) +}).annotate({ + "title": "Realtime MCP approval request", + "description": "A Realtime item requesting human approval of a tool invocation.\n" +}) +export type RealtimeMCPApprovalResponse = { + readonly "type": "mcp_approval_response" + readonly "id": string + readonly "approval_request_id": string + readonly "approve": boolean + readonly "reason"?: string | null +} +export const RealtimeMCPApprovalResponse = Schema.Struct({ + "type": Schema.Literal("mcp_approval_response").annotate({ + "description": "The type of the item. Always `mcp_approval_response`." + }), + "id": Schema.String.annotate({ "description": "The unique ID of the approval response." }), + "approval_request_id": Schema.String.annotate({ "description": "The ID of the approval request being answered." }), + "approve": Schema.Boolean.annotate({ "description": "Whether the request was approved." }), + "reason": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "Optional reason for the decision." }), Schema.Null]) + ) +}).annotate({ + "title": "Realtime MCP approval response", + "description": "A Realtime item responding to an MCP approval request.\n" +}) +export type RealtimeMCPHTTPError = { + readonly "type": "http_error" + readonly "code": number + readonly "message": string +} +export const RealtimeMCPHTTPError = Schema.Struct({ + "type": Schema.Literal("http_error"), + "code": Schema.Number.check(Schema.isInt()), + "message": Schema.String +}).annotate({ "title": "Realtime MCP HTTP error" }) +export type RealtimeMCPProtocolError = { + readonly "type": "protocol_error" + readonly "code": number + readonly "message": string +} +export const RealtimeMCPProtocolError = Schema.Struct({ + "type": Schema.Literal("protocol_error"), + "code": Schema.Number.check(Schema.isInt()), + "message": Schema.String +}).annotate({ "title": "Realtime MCP protocol error" }) +export type RealtimeMCPToolExecutionError = { readonly "type": "tool_execution_error"; readonly "message": string } +export const RealtimeMCPToolExecutionError = Schema.Struct({ + "type": Schema.Literal("tool_execution_error"), + "message": Schema.String +}).annotate({ "title": "Realtime MCP tool execution error" }) +export type RealtimeReasoningEffort = "minimal" | "low" | "medium" | "high" | "xhigh" +export const RealtimeReasoningEffort = Schema.Literals(["minimal", "low", "medium", "high", "xhigh"]).annotate({ + "description": "Constrains effort on reasoning for reasoning-capable Realtime models such as\n`gpt-realtime-2`.\n" +}) +export type RealtimeServerEventConversationCreated = { + readonly "event_id": string + readonly "type": "conversation.created" + readonly "conversation": { readonly "id"?: string; readonly "object"?: string } +} +export const RealtimeServerEventConversationCreated = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.created").annotate({ + "description": "The event type, must be `conversation.created`." + }), + "conversation": Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The unique ID of the conversation." })), + "object": Schema.optionalKey( + Schema.String.annotate({ "description": "The object type, must be `realtime.conversation`." }) + ) + }).annotate({ "description": "The conversation resource." }) +}).annotate({ "description": "Returned when a conversation is created. Emitted right after session creation.\n" }) +export type RealtimeServerEventConversationItemDeleted = { + readonly "event_id": string + readonly "type": "conversation.item.deleted" + readonly "item_id": string +} +export const RealtimeServerEventConversationItemDeleted = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.deleted").annotate({ + "description": "The event type, must be `conversation.item.deleted`." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the item that was deleted." }) +}).annotate({ + "description": + "Returned when an item in the conversation is deleted by the client with a \n`conversation.item.delete` event. This event is used to synchronize the \nserver's understanding of the conversation history with the client's view.\n" +}) +export type RealtimeServerEventConversationItemInputAudioTranscriptionFailed = { + readonly "event_id": string + readonly "type": "conversation.item.input_audio_transcription.failed" + readonly "item_id": string + readonly "content_index": number + readonly "error": { + readonly "type"?: string + readonly "code"?: string + readonly "message"?: string + readonly "param"?: string + } +} +export const RealtimeServerEventConversationItemInputAudioTranscriptionFailed = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.input_audio_transcription.failed").annotate({ + "description": "The event type, must be\n`conversation.item.input_audio_transcription.failed`.\n" + }), + "item_id": Schema.String.annotate({ "description": "The ID of the user message item." }), + "content_index": Schema.Number.annotate({ "description": "The index of the content part containing the audio." }) + .check(Schema.isInt()), + "error": Schema.Struct({ + "type": Schema.optionalKey(Schema.String.annotate({ "description": "The type of error." })), + "code": Schema.optionalKey(Schema.String.annotate({ "description": "Error code, if any." })), + "message": Schema.optionalKey(Schema.String.annotate({ "description": "A human-readable error message." })), + "param": Schema.optionalKey(Schema.String.annotate({ "description": "Parameter related to the error, if any." })) + }).annotate({ "description": "Details of the transcription error." }) +}).annotate({ + "description": + "Returned when input audio transcription is configured, and a transcription \nrequest for a user message failed. These events are separate from other \n`error` events so that the client can identify the related Item.\n" +}) +export type RealtimeServerEventConversationItemInputAudioTranscriptionSegment = { + readonly "event_id": string + readonly "type": "conversation.item.input_audio_transcription.segment" + readonly "item_id": string + readonly "content_index": number + readonly "text": string + readonly "id": string + readonly "speaker": string + readonly "start": number + readonly "end": number +} +export const RealtimeServerEventConversationItemInputAudioTranscriptionSegment = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.input_audio_transcription.segment").annotate({ + "description": "The event type, must be `conversation.item.input_audio_transcription.segment`." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the item containing the input audio content." }), + "content_index": Schema.Number.annotate({ + "description": "The index of the input audio content part within the item." + }).check(Schema.isInt()), + "text": Schema.String.annotate({ "description": "The text for this segment." }), + "id": Schema.String.annotate({ "description": "The segment identifier." }), + "speaker": Schema.String.annotate({ "description": "The detected speaker label for this segment." }), + "start": Schema.Number.annotate({ "description": "Start time of the segment in seconds.", "format": "double" }).check( + Schema.isFinite() + ), + "end": Schema.Number.annotate({ "description": "End time of the segment in seconds.", "format": "double" }).check( + Schema.isFinite() + ) +}).annotate({ "description": "Returned when an input audio transcription segment is identified for an item." }) +export type RealtimeServerEventConversationItemTruncated = { + readonly "event_id": string + readonly "type": "conversation.item.truncated" + readonly "item_id": string + readonly "content_index": number + readonly "audio_end_ms": number +} +export const RealtimeServerEventConversationItemTruncated = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.truncated").annotate({ + "description": "The event type, must be `conversation.item.truncated`." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the assistant message item that was truncated." }), + "content_index": Schema.Number.annotate({ "description": "The index of the content part that was truncated." }).check( + Schema.isInt() + ), + "audio_end_ms": Schema.Number.annotate({ + "description": "The duration up to which the audio was truncated, in milliseconds.\n" + }).check(Schema.isInt()) +}).annotate({ + "description": + "Returned when an earlier assistant audio message item is truncated by the \nclient with a `conversation.item.truncate` event. This event is used to \nsynchronize the server's understanding of the audio with the client's playback.\n\nThis action will truncate the audio and remove the server-side text transcript \nto ensure there is no text in the context that hasn't been heard by the user.\n" +}) +export type RealtimeServerEventError = { + readonly "event_id": string + readonly "type": "error" + readonly "error": { + readonly "type": string + readonly "code"?: string | null + readonly "message": string + readonly "param"?: string | null + readonly "event_id"?: string | null + } +} +export const RealtimeServerEventError = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("error").annotate({ "description": "The event type, must be `error`." }), + "error": Schema.Struct({ + "type": Schema.String.annotate({ + "description": "The type of error (e.g., \"invalid_request_error\", \"server_error\").\n" + }), + "code": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "Error code, if any." }), Schema.Null]) + ), + "message": Schema.String.annotate({ "description": "A human-readable error message." }), + "param": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "Parameter related to the error, if any." }), Schema.Null]) + ), + "event_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "The event_id of the client event that caused the error, if applicable.\n" + }), + Schema.Null + ]) + ) + }).annotate({ "description": "Details of the error." }) +}).annotate({ + "description": + "Returned when an error occurs, which could be a client problem or a server\nproblem. Most errors are recoverable and the session will stay open, we\nrecommend to implementors to monitor and log error messages by default.\n" +}) +export type RealtimeServerEventInputAudioBufferCleared = { + readonly "event_id": string + readonly "type": "input_audio_buffer.cleared" +} +export const RealtimeServerEventInputAudioBufferCleared = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("input_audio_buffer.cleared").annotate({ + "description": "The event type, must be `input_audio_buffer.cleared`." + }) +}).annotate({ + "description": + "Returned when the input audio buffer is cleared by the client with a \n`input_audio_buffer.clear` event.\n" +}) +export type RealtimeServerEventInputAudioBufferCommitted = { + readonly "event_id": string + readonly "type": "input_audio_buffer.committed" + readonly "previous_item_id"?: string | null + readonly "item_id": string +} +export const RealtimeServerEventInputAudioBufferCommitted = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("input_audio_buffer.committed").annotate({ + "description": "The event type, must be `input_audio_buffer.committed`." + }), + "previous_item_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The ID of the preceding item after which the new item will be inserted.\nCan be `null` if the item has no predecessor.\n" + }), + Schema.Null + ]) + ), + "item_id": Schema.String.annotate({ "description": "The ID of the user message item that will be created." }) +}).annotate({ + "description": + "Returned when an input audio buffer is committed, either by the client or\nautomatically in server VAD mode. The `item_id` property is the ID of the user\nmessage item that will be created, thus a `conversation.item.created` event\nwill also be sent to the client.\n" +}) +export type RealtimeServerEventInputAudioBufferDtmfEventReceived = { + readonly "type": "input_audio_buffer.dtmf_event_received" + readonly "event": string + readonly "received_at": number +} +export const RealtimeServerEventInputAudioBufferDtmfEventReceived = Schema.Struct({ + "type": Schema.Literal("input_audio_buffer.dtmf_event_received").annotate({ + "description": "The event type, must be `input_audio_buffer.dtmf_event_received`." + }), + "event": Schema.String.annotate({ "description": "The telephone keypad that was pressed by the user." }), + "received_at": Schema.Number.annotate({ + "description": "UTC Unix Timestamp when DTMF Event was received by server.\n" + }).check(Schema.isInt()) +}).annotate({ + "description": + "**SIP Only:** Returned when an DTMF event is received. A DTMF event is a message that\nrepresents a telephone keypad press (0–9, *, #, A–D). The `event` property\nis the keypad that the user press. The `received_at` is the UTC Unix Timestamp\nthat the server received the event.\n" +}) +export type RealtimeServerEventInputAudioBufferSpeechStarted = { + readonly "event_id": string + readonly "type": "input_audio_buffer.speech_started" + readonly "audio_start_ms": number + readonly "item_id": string +} +export const RealtimeServerEventInputAudioBufferSpeechStarted = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("input_audio_buffer.speech_started").annotate({ + "description": "The event type, must be `input_audio_buffer.speech_started`." + }), + "audio_start_ms": Schema.Number.annotate({ + "description": + "Milliseconds from the start of all audio written to the buffer during the \nsession when speech was first detected. This will correspond to the \nbeginning of audio sent to the model, and thus includes the \n`prefix_padding_ms` configured in the Session.\n" + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The ID of the user message item that will be created when speech stops.\n" + }) +}).annotate({ + "description": + "Sent by the server when in `server_vad` mode to indicate that speech has been \ndetected in the audio buffer. This can happen any time audio is added to the \nbuffer (unless speech is already detected). The client may want to use this \nevent to interrupt audio playback or provide visual feedback to the user. \n\nThe client should expect to receive a `input_audio_buffer.speech_stopped` event \nwhen speech stops. The `item_id` property is the ID of the user message item \nthat will be created when speech stops and will also be included in the \n`input_audio_buffer.speech_stopped` event (unless the client manually commits \nthe audio buffer during VAD activation).\n" +}) +export type RealtimeServerEventInputAudioBufferSpeechStopped = { + readonly "event_id": string + readonly "type": "input_audio_buffer.speech_stopped" + readonly "audio_end_ms": number + readonly "item_id": string +} +export const RealtimeServerEventInputAudioBufferSpeechStopped = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("input_audio_buffer.speech_stopped").annotate({ + "description": "The event type, must be `input_audio_buffer.speech_stopped`." + }), + "audio_end_ms": Schema.Number.annotate({ + "description": + "Milliseconds since the session started when speech stopped. This will \ncorrespond to the end of audio sent to the model, and thus includes the \n`min_silence_duration_ms` configured in the Session.\n" + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ "description": "The ID of the user message item that will be created." }) +}).annotate({ + "description": + "Returned in `server_vad` mode when the server detects the end of speech in \nthe audio buffer. The server will also send an `conversation.item.created` \nevent with the user message item that is created from the audio buffer.\n" +}) +export type RealtimeServerEventInputAudioBufferTimeoutTriggered = { + readonly "event_id": string + readonly "type": "input_audio_buffer.timeout_triggered" + readonly "audio_start_ms": number + readonly "audio_end_ms": number + readonly "item_id": string +} +export const RealtimeServerEventInputAudioBufferTimeoutTriggered = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("input_audio_buffer.timeout_triggered").annotate({ + "description": "The event type, must be `input_audio_buffer.timeout_triggered`." + }), + "audio_start_ms": Schema.Number.annotate({ + "description": + "Millisecond offset of audio written to the input audio buffer that was after the playback time of the last model response." + }).check(Schema.isInt()), + "audio_end_ms": Schema.Number.annotate({ + "description": + "Millisecond offset of audio written to the input audio buffer at the time the timeout was triggered." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ "description": "The ID of the item associated with this segment." }) +}).annotate({ + "description": + "Returned when the Server VAD timeout is triggered for the input audio buffer. This is configured\nwith `idle_timeout_ms` in the `turn_detection` settings of the session, and it indicates that\nthere hasn't been any speech detected for the configured duration.\n\nThe `audio_start_ms` and `audio_end_ms` fields indicate the segment of audio after the last\nmodel response up to the triggering time, as an offset from the beginning of audio written\nto the input audio buffer. This means it demarcates the segment of audio that was silent and\nthe difference between the start and end values will roughly match the configured timeout.\n\nThe empty audio will be committed to the conversation as an `input_audio` item (there will be a\n`input_audio_buffer.committed` event) and a model response will be generated. There may be speech\nthat didn't trigger VAD but is still detected by the model, so the model may respond with\nsomething relevant to the conversation or a prompt to continue speaking.\n" +}) +export type RealtimeServerEventMCPListToolsCompleted = { + readonly "event_id": string + readonly "type": "mcp_list_tools.completed" + readonly "item_id": string +} +export const RealtimeServerEventMCPListToolsCompleted = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("mcp_list_tools.completed").annotate({ + "description": "The event type, must be `mcp_list_tools.completed`." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP list tools item." }) +}).annotate({ "description": "Returned when listing MCP tools has completed for an item." }) +export type RealtimeServerEventMCPListToolsFailed = { + readonly "event_id": string + readonly "type": "mcp_list_tools.failed" + readonly "item_id": string +} +export const RealtimeServerEventMCPListToolsFailed = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("mcp_list_tools.failed").annotate({ + "description": "The event type, must be `mcp_list_tools.failed`." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP list tools item." }) +}).annotate({ "description": "Returned when listing MCP tools has failed for an item." }) +export type RealtimeServerEventMCPListToolsInProgress = { + readonly "event_id": string + readonly "type": "mcp_list_tools.in_progress" + readonly "item_id": string +} +export const RealtimeServerEventMCPListToolsInProgress = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("mcp_list_tools.in_progress").annotate({ + "description": "The event type, must be `mcp_list_tools.in_progress`." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP list tools item." }) +}).annotate({ "description": "Returned when listing MCP tools is in progress for an item." }) +export type RealtimeServerEventOutputAudioBufferCleared = { + readonly "event_id": string + readonly "type": "output_audio_buffer.cleared" + readonly "response_id": string +} +export const RealtimeServerEventOutputAudioBufferCleared = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("output_audio_buffer.cleared").annotate({ + "description": "The event type, must be `output_audio_buffer.cleared`." + }), + "response_id": Schema.String.annotate({ "description": "The unique ID of the response that produced the audio." }) +}).annotate({ + "description": + "**WebRTC/SIP Only:** Emitted when the output audio buffer is cleared. This happens either in VAD\nmode when the user has interrupted (`input_audio_buffer.speech_started`),\nor when the client has emitted the `output_audio_buffer.clear` event to manually\ncut off the current audio response.\n[Learn more](/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n" +}) +export type RealtimeServerEventOutputAudioBufferStarted = { + readonly "event_id": string + readonly "type": "output_audio_buffer.started" + readonly "response_id": string +} +export const RealtimeServerEventOutputAudioBufferStarted = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("output_audio_buffer.started").annotate({ + "description": "The event type, must be `output_audio_buffer.started`." + }), + "response_id": Schema.String.annotate({ "description": "The unique ID of the response that produced the audio." }) +}).annotate({ + "description": + "**WebRTC/SIP Only:** Emitted when the server begins streaming audio to the client. This event is\nemitted after an audio content part has been added (`response.content_part.added`)\nto the response.\n[Learn more](/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n" +}) +export type RealtimeServerEventOutputAudioBufferStopped = { + readonly "event_id": string + readonly "type": "output_audio_buffer.stopped" + readonly "response_id": string +} +export const RealtimeServerEventOutputAudioBufferStopped = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("output_audio_buffer.stopped").annotate({ + "description": "The event type, must be `output_audio_buffer.stopped`." + }), + "response_id": Schema.String.annotate({ "description": "The unique ID of the response that produced the audio." }) +}).annotate({ + "description": + "**WebRTC/SIP Only:** Emitted when the output audio buffer has been completely drained on the server,\nand no more audio is forthcoming. This event is emitted after the full response\ndata has been sent to the client (`response.done`).\n[Learn more](/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc).\n" +}) +export type RealtimeServerEventRateLimitsUpdated = { + readonly "event_id": string + readonly "type": "rate_limits.updated" + readonly "rate_limits": ReadonlyArray< + { + readonly "name"?: "requests" | "tokens" + readonly "limit"?: number + readonly "remaining"?: number + readonly "reset_seconds"?: number + } + > +} +export const RealtimeServerEventRateLimitsUpdated = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("rate_limits.updated").annotate({ + "description": "The event type, must be `rate_limits.updated`." + }), + "rate_limits": Schema.Array(Schema.Struct({ + "name": Schema.optionalKey( + Schema.Literals(["requests", "tokens"]).annotate({ + "description": "The name of the rate limit (`requests`, `tokens`).\n" + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum allowed value for the rate limit." }).check(Schema.isInt()) + ), + "remaining": Schema.optionalKey( + Schema.Number.annotate({ "description": "The remaining value before the limit is reached." }).check( + Schema.isInt() + ) + ), + "reset_seconds": Schema.optionalKey( + Schema.Number.annotate({ "description": "Seconds until the rate limit resets." }).check(Schema.isFinite()) + ) + })).annotate({ "description": "List of rate limit information." }) +}).annotate({ + "description": + "Emitted at the beginning of a Response to indicate the updated rate limits. \nWhen a Response is created some tokens will be \"reserved\" for the output \ntokens, the rate limits shown here reflect that reservation, which is then \nadjusted accordingly once the Response is completed.\n" +}) +export type RealtimeServerEventResponseAudioDelta = { + readonly "event_id": string + readonly "type": "response.output_audio.delta" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "delta": string +} +export const RealtimeServerEventResponseAudioDelta = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.output_audio.delta").annotate({ + "description": "The event type, must be `response.output_audio.delta`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part in the item's content array." + }).check(Schema.isInt()), + "delta": Schema.String.annotate({ "description": "Base64-encoded audio data delta." }) +}).annotate({ "description": "Returned when the model-generated audio is updated." }) +export type RealtimeServerEventResponseAudioDone = { + readonly "event_id": string + readonly "type": "response.output_audio.done" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number +} +export const RealtimeServerEventResponseAudioDone = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.output_audio.done").annotate({ + "description": "The event type, must be `response.output_audio.done`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part in the item's content array." + }).check(Schema.isInt()) +}).annotate({ + "description": + "Returned when the model-generated audio is done. Also emitted when a Response\nis interrupted, incomplete, or cancelled.\n" +}) +export type RealtimeServerEventResponseAudioTranscriptDelta = { + readonly "event_id": string + readonly "type": "response.output_audio_transcript.delta" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "delta": string +} +export const RealtimeServerEventResponseAudioTranscriptDelta = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.output_audio_transcript.delta").annotate({ + "description": "The event type, must be `response.output_audio_transcript.delta`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part in the item's content array." + }).check(Schema.isInt()), + "delta": Schema.String.annotate({ "description": "The transcript delta." }) +}).annotate({ "description": "Returned when the model-generated transcription of audio output is updated.\n" }) +export type RealtimeServerEventResponseAudioTranscriptDone = { + readonly "event_id": string + readonly "type": "response.output_audio_transcript.done" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "transcript": string +} +export const RealtimeServerEventResponseAudioTranscriptDone = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.output_audio_transcript.done").annotate({ + "description": "The event type, must be `response.output_audio_transcript.done`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part in the item's content array." + }).check(Schema.isInt()), + "transcript": Schema.String.annotate({ "description": "The final transcript of the audio." }) +}).annotate({ + "description": + "Returned when the model-generated transcription of audio output is done\nstreaming. Also emitted when a Response is interrupted, incomplete, or\ncancelled.\n" +}) +export type RealtimeServerEventResponseContentPartAdded = { + readonly "event_id": string + readonly "type": "response.content_part.added" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "part": { + readonly "type"?: "audio" | "text" + readonly "text"?: string + readonly "audio"?: string + readonly "transcript"?: string + } +} +export const RealtimeServerEventResponseContentPartAdded = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.content_part.added").annotate({ + "description": "The event type, must be `response.content_part.added`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the item to which the content part was added." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part in the item's content array." + }).check(Schema.isInt()), + "part": Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literals(["audio", "text"]).annotate({ "description": "The content type (\"text\", \"audio\")." }) + ), + "text": Schema.optionalKey(Schema.String.annotate({ "description": "The text content (if type is \"text\")." })), + "audio": Schema.optionalKey( + Schema.String.annotate({ "description": "Base64-encoded audio data (if type is \"audio\")." }) + ), + "transcript": Schema.optionalKey( + Schema.String.annotate({ "description": "The transcript of the audio (if type is \"audio\")." }) + ) + }).annotate({ "description": "The content part that was added." }) +}).annotate({ + "description": "Returned when a new content part is added to an assistant message item during\nresponse generation.\n" +}) +export type RealtimeServerEventResponseContentPartDone = { + readonly "event_id": string + readonly "type": "response.content_part.done" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "part": { + readonly "type"?: "audio" | "text" + readonly "text"?: string + readonly "audio"?: string + readonly "transcript"?: string + } +} +export const RealtimeServerEventResponseContentPartDone = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.content_part.done").annotate({ + "description": "The event type, must be `response.content_part.done`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part in the item's content array." + }).check(Schema.isInt()), + "part": Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literals(["audio", "text"]).annotate({ "description": "The content type (\"text\", \"audio\")." }) + ), + "text": Schema.optionalKey(Schema.String.annotate({ "description": "The text content (if type is \"text\")." })), + "audio": Schema.optionalKey( + Schema.String.annotate({ "description": "Base64-encoded audio data (if type is \"audio\")." }) + ), + "transcript": Schema.optionalKey( + Schema.String.annotate({ "description": "The transcript of the audio (if type is \"audio\")." }) + ) + }).annotate({ "description": "The content part that is done." }) +}).annotate({ + "description": + "Returned when a content part is done streaming in an assistant message item.\nAlso emitted when a Response is interrupted, incomplete, or cancelled.\n" +}) +export type RealtimeServerEventResponseFunctionCallArgumentsDelta = { + readonly "event_id": string + readonly "type": "response.function_call_arguments.delta" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "call_id": string + readonly "delta": string +} +export const RealtimeServerEventResponseFunctionCallArgumentsDelta = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.function_call_arguments.delta").annotate({ + "description": "The event type, must be `response.function_call_arguments.delta`.\n" + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the function call item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "call_id": Schema.String.annotate({ "description": "The ID of the function call." }), + "delta": Schema.String.annotate({ "description": "The arguments delta as a JSON string." }) +}).annotate({ "description": "Returned when the model-generated function call arguments are updated.\n" }) +export type RealtimeServerEventResponseFunctionCallArgumentsDone = { + readonly "event_id": string + readonly "type": "response.function_call_arguments.done" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "call_id": string + readonly "name": string + readonly "arguments": string +} +export const RealtimeServerEventResponseFunctionCallArgumentsDone = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.function_call_arguments.done").annotate({ + "description": "The event type, must be `response.function_call_arguments.done`.\n" + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the function call item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "call_id": Schema.String.annotate({ "description": "The ID of the function call." }), + "name": Schema.String.annotate({ "description": "The name of the function that was called." }), + "arguments": Schema.String.annotate({ "description": "The final arguments as a JSON string." }) +}).annotate({ + "description": + "Returned when the model-generated function call arguments are done streaming.\nAlso emitted when a Response is interrupted, incomplete, or cancelled.\n" +}) +export type RealtimeServerEventResponseMCPCallArgumentsDelta = { + readonly "event_id": string + readonly "type": "response.mcp_call_arguments.delta" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "delta": string + readonly "obfuscation"?: string | null +} +export const RealtimeServerEventResponseMCPCallArgumentsDelta = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.mcp_call_arguments.delta").annotate({ + "description": "The event type, must be `response.mcp_call_arguments.delta`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "delta": Schema.String.annotate({ "description": "The JSON-encoded arguments delta." }), + "obfuscation": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "If present, indicates the delta text was obfuscated." }), + Schema.Null + ]) + ) +}).annotate({ "description": "Returned when MCP tool call arguments are updated during response generation." }) +export type RealtimeServerEventResponseMCPCallArgumentsDone = { + readonly "event_id": string + readonly "type": "response.mcp_call_arguments.done" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "arguments": string +} +export const RealtimeServerEventResponseMCPCallArgumentsDone = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.mcp_call_arguments.done").annotate({ + "description": "The event type, must be `response.mcp_call_arguments.done`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "arguments": Schema.String.annotate({ "description": "The final JSON-encoded arguments string." }) +}).annotate({ "description": "Returned when MCP tool call arguments are finalized during response generation." }) +export type RealtimeServerEventResponseMCPCallCompleted = { + readonly "event_id": string + readonly "type": "response.mcp_call.completed" + readonly "output_index": number + readonly "item_id": string +} +export const RealtimeServerEventResponseMCPCallCompleted = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.mcp_call.completed").annotate({ + "description": "The event type, must be `response.mcp_call.completed`." + }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item." }) +}).annotate({ "description": "Returned when an MCP tool call has completed successfully." }) +export type RealtimeServerEventResponseMCPCallFailed = { + readonly "event_id": string + readonly "type": "response.mcp_call.failed" + readonly "output_index": number + readonly "item_id": string +} +export const RealtimeServerEventResponseMCPCallFailed = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.mcp_call.failed").annotate({ + "description": "The event type, must be `response.mcp_call.failed`." + }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item." }) +}).annotate({ "description": "Returned when an MCP tool call has failed." }) +export type RealtimeServerEventResponseMCPCallInProgress = { + readonly "event_id": string + readonly "type": "response.mcp_call.in_progress" + readonly "output_index": number + readonly "item_id": string +} +export const RealtimeServerEventResponseMCPCallInProgress = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.mcp_call.in_progress").annotate({ + "description": "The event type, must be `response.mcp_call.in_progress`." + }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item." }) +}).annotate({ "description": "Returned when an MCP tool call has started and is in progress." }) +export type RealtimeServerEventResponseTextDelta = { + readonly "event_id": string + readonly "type": "response.output_text.delta" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "delta": string +} +export const RealtimeServerEventResponseTextDelta = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.output_text.delta").annotate({ + "description": "The event type, must be `response.output_text.delta`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part in the item's content array." + }).check(Schema.isInt()), + "delta": Schema.String.annotate({ "description": "The text delta." }) +}).annotate({ "description": "Returned when the text value of an \"output_text\" content part is updated." }) +export type RealtimeServerEventResponseTextDone = { + readonly "event_id": string + readonly "type": "response.output_text.done" + readonly "response_id": string + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "text": string +} +export const RealtimeServerEventResponseTextDone = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.output_text.done").annotate({ + "description": "The event type, must be `response.output_text.done`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the response." }), + "item_id": Schema.String.annotate({ "description": "The ID of the item." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the response." }).check( + Schema.isInt() + ), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part in the item's content array." + }).check(Schema.isInt()), + "text": Schema.String.annotate({ "description": "The final text content." }) +}).annotate({ + "description": + "Returned when the text value of an \"output_text\" content part is done streaming. Also\nemitted when a Response is interrupted, incomplete, or cancelled.\n" +}) +export type RealtimeTranscriptionSessionCreateResponse = { + readonly "client_secret": { readonly "value": string; readonly "expires_at": number } + readonly "modalities"?: ReadonlyArray<"text" | "audio"> + readonly "input_audio_format"?: string + readonly "input_audio_transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + } + readonly "turn_detection"?: { + readonly "type"?: string + readonly "threshold"?: number + readonly "prefix_padding_ms"?: number + readonly "silence_duration_ms"?: number + } +} +export const RealtimeTranscriptionSessionCreateResponse = Schema.Struct({ + "client_secret": Schema.Struct({ + "value": Schema.String.annotate({ + "description": + "Ephemeral key usable in client environments to authenticate connections\nto the Realtime API. Use this in client-side environments rather than\na standard API token, which should only be used server-side.\n" + }), + "expires_at": Schema.Number.annotate({ + "description": "Timestamp for when the token expires. Currently, all tokens expire\nafter one minute.\n", + "format": "unixtime" + }).check(Schema.isInt()) + }).annotate({ + "description": + "Ephemeral key returned by the API. Only present when the session is\ncreated on the server via REST API.\n" + }), + "modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": "The set of modalities the model can respond with. To disable audio,\nset this to [\"text\"].\n" + }) + ), + "input_audio_format": Schema.optionalKey( + Schema.String.annotate({ + "description": "The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }) + ), + "input_audio_transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model used for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`.\n" + }) + ), + "language": Schema.optionalKey(Schema.String.annotate({ "description": "The language of the input audio.\n" })), + "prompt": Schema.optionalKey( + Schema.String.annotate({ + "description": "The prompt configured for input audio transcription, when present.\n" + }) + ) + }).annotate({ "description": "Configuration of the transcription model.\n" }) + ), + "turn_detection": Schema.optionalKey( + Schema.Struct({ + "type": Schema.optionalKey( + Schema.String.annotate({ "description": "Type of turn detection, only `server_vad` is currently supported.\n" }) + ), + "threshold": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }).check(Schema.isFinite()) + ), + "prefix_padding_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }).check(Schema.isInt()) + ), + "silence_duration_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + }).check(Schema.isInt()) + ) + }).annotate({ + "description": + "Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n" + }) + ) +}).annotate({ + "description": + "A new Realtime transcription session configuration.\n\nWhen a session is created on the server via REST API, the session object\nalso contains an ephemeral key. Default TTL for keys is 10 minutes. This\nproperty is not present when a session is updated via the WebSocket API.\n" +}) +export type RealtimeTranslationClientEventInputAudioBufferAppend = { + readonly "event_id"?: string + readonly "type": "session.input_audio_buffer.append" + readonly "audio": string +} +export const RealtimeTranslationClientEventInputAudioBufferAppend = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("session.input_audio_buffer.append").annotate({ + "description": "The event type, must be `session.input_audio_buffer.append`." + }), + "audio": Schema.String.annotate({ "description": "Base64-encoded 24 kHz PCM16 mono audio bytes." }) +}).annotate({ + "description": + "Send this event to append audio bytes to the translation session input audio buffer.\n\nWebSocket translation sessions accept base64-encoded 24 kHz PCM16 mono\nlittle-endian raw audio bytes. Unsupported websocket audio formats return a\nvalidation error because lower-quality audio materially degrades translation\nquality.\n\nTranslation consumes 200 ms engine frames. For best realtime behavior, append\naudio in 200 ms chunks. If a chunk is shorter, the server buffers it until it\nhas enough audio for one frame. If a chunk is longer, the server splits it into\n200 ms frames and enqueues them back-to-back.\n\nKeep appending silence while the session is active. If a client stops sending\naudio and later resumes, model time treats the resumed audio as contiguous with\nthe previous audio rather than as a real-world pause.\n" +}) +export type RealtimeTranslationClientEventSessionClose = { + readonly "event_id"?: string + readonly "type": "session.close" +} +export const RealtimeTranslationClientEventSessionClose = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("session.close").annotate({ "description": "The event type, must be `session.close`." }) +}).annotate({ + "description": + "Gracefully close the realtime translation session. The server flushes pending\ninput audio and emits any remaining translated output before closing the\nsession.\n" +}) +export type RealtimeTranslationServerEventSessionClosed = { + readonly "event_id": string + readonly "type": "session.closed" +} +export const RealtimeTranslationServerEventSessionClosed = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("session.closed").annotate({ "description": "The event type, must be `session.closed`." }) +}).annotate({ "description": "Returned when a realtime translation session is closed.\n" }) +export type RealtimeTranslationServerEventSessionInputTranscriptDelta = { + readonly "event_id": string + readonly "type": "session.input_transcript.delta" + readonly "delta": string + readonly "elapsed_ms"?: number | null +} +export const RealtimeTranslationServerEventSessionInputTranscriptDelta = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("session.input_transcript.delta").annotate({ + "description": "The event type, must be `session.input_transcript.delta`." + }), + "delta": Schema.String.annotate({ "description": "Append-only source-language transcript text." }), + "elapsed_ms": Schema.optionalKey(Schema.Union([ + Schema.Number.annotate({ + "description": + "Timing metadata for stream alignment, derived from the translation frame\nwhen available. It advances in 200 ms increments, but multiple transcript\ndeltas may share the same `elapsed_ms`. Treat it as alignment metadata,\nnot a unique transcript-delta identifier.\n" + }).check(Schema.isInt()), + Schema.Null + ])) +}).annotate({ + "description": + "Returned when optional source-language transcript text is available. This event\nis emitted only when `audio.input.transcription` is configured.\n\nTranscript deltas are append-only text fragments. Clients should not insert\nunconditional spaces between deltas.\n" +}) +export type RealtimeTranslationServerEventSessionOutputAudioDelta = { + readonly "event_id": string + readonly "type": "session.output_audio.delta" + readonly "delta": string + readonly "sample_rate"?: number + readonly "channels"?: number + readonly "format"?: "pcm16" + readonly "elapsed_ms"?: number | null +} +export const RealtimeTranslationServerEventSessionOutputAudioDelta = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("session.output_audio.delta").annotate({ + "description": "The event type, must be `session.output_audio.delta`." + }), + "delta": Schema.String.annotate({ "description": "Base64-encoded translated audio data." }), + "sample_rate": Schema.optionalKey( + Schema.Number.annotate({ "description": "Sample rate of the audio delta." }).check(Schema.isInt()) + ), + "channels": Schema.optionalKey( + Schema.Number.annotate({ "description": "Number of audio channels." }).check(Schema.isInt()) + ), + "format": Schema.optionalKey(Schema.Literal("pcm16").annotate({ "description": "Audio encoding for `delta`." })), + "elapsed_ms": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Timing metadata for stream alignment, derived from the translation frame\nwhen available. Treat `elapsed_ms` as alignment metadata, not a unique\nevent identifier.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ) +}).annotate({ + "description": + "Returned when translated output audio is available. Output audio deltas are\n200 ms frames of PCM16 audio.\n" +}) +export type RealtimeTranslationServerEventSessionOutputTranscriptDelta = { + readonly "event_id": string + readonly "type": "session.output_transcript.delta" + readonly "delta": string + readonly "elapsed_ms"?: number | null +} +export const RealtimeTranslationServerEventSessionOutputTranscriptDelta = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("session.output_transcript.delta").annotate({ + "description": "The event type, must be `session.output_transcript.delta`." + }), + "delta": Schema.String.annotate({ "description": "Append-only transcript text for the translated output audio." }), + "elapsed_ms": Schema.optionalKey(Schema.Union([ + Schema.Number.annotate({ + "description": + "Timing metadata for stream alignment, derived from the translation frame\nwhen available. It advances in 200 ms increments, but multiple transcript\ndeltas may share the same `elapsed_ms`. Treat it as alignment metadata,\nnot a unique transcript-delta identifier.\n" + }).check(Schema.isInt()), + Schema.Null + ])) +}).annotate({ + "description": + "Returned when translated transcript text is available.\n\nTranscript deltas are append-only text fragments. Clients should not insert\nunconditional spaces between deltas.\n" +}) +export type RealtimeTruncation = "auto" | "disabled" | { + readonly "type": "retention_ratio" + readonly "retention_ratio": number + readonly "token_limits"?: { readonly "post_instructions"?: number } +} +export const RealtimeTruncation = Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the session. `auto` is the default truncation strategy. `disabled` will disable truncation and emit errors when the conversation exceeds the input token limit." + }), + Schema.Struct({ + "type": Schema.Literal("retention_ratio").annotate({ "description": "Use retention ratio truncation." }), + "retention_ratio": Schema.Number.annotate({ + "description": + "Fraction of post-instruction conversation tokens to retain (`0.0` - `1.0`) when the conversation exceeds the input token limit. Setting this to `0.8` means that messages will be dropped until 80% of the maximum allowed tokens are used. This helps reduce the frequency of truncations and improve cache rates.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + "token_limits": Schema.optionalKey( + Schema.Struct({ + "post_instructions": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Maximum tokens allowed in the conversation after instructions (which including tool definitions). For example, setting this to 5,000 would mean that truncation would occur when the conversation exceeds 5,000 tokens after instructions. This cannot be higher than the model's context window size minus the maximum output tokens." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)) + ) + }).annotate({ + "description": + "Optional custom token limits for this truncation strategy. If not provided, the model's default token limits will be used." + }) + ) + }).annotate({ + "title": "Retention ratio truncation", + "description": + "Retain a fraction of the conversation tokens when the conversation exceeds the input token limit. This allows you to amortize truncations across multiple turns, which can help improve cached token usage." + }) +], { mode: "oneOf" }).annotate({ + "title": "Realtime Truncation Controls", + "description": + "When the number of tokens in a conversation exceeds the model's input token limit, the conversation be truncated, meaning messages (starting from the oldest) will not be included in the model's context. A 32k context model with 4,096 max output tokens can only include 28,224 tokens in the context before truncation occurs.\n\nClients can configure truncation behavior to truncate with a lower max token limit, which is an effective way to control token usage and cost.\n\nTruncation will reduce the number of cached tokens on the next turn (busting the cache), since messages are dropped from the beginning of the context. However, clients can also configure truncation to retain messages up to a fraction of the maximum context size, which will reduce the need for future truncations and thus improve the cache rate.\n\nTruncation can be disabled entirely, which means the server will never truncate but would instead return an error if the conversation exceeds the model's input token limit.\n" +}) +export type RealtimeTurnDetection = { + readonly "type": "server_vad" + readonly "threshold"?: number + readonly "prefix_padding_ms"?: number + readonly "silence_duration_ms"?: number + readonly "create_response"?: boolean + readonly "interrupt_response"?: boolean + readonly "idle_timeout_ms"?: number | null +} | { + readonly "type": "semantic_vad" + readonly "eagerness"?: "low" | "medium" | "high" | "auto" + readonly "create_response"?: boolean + readonly "interrupt_response"?: boolean +} | null +export const RealtimeTurnDetection = Schema.Union([ + Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("server_vad").annotate({ + "description": "Type of turn detection, `server_vad` to turn on simple Server VAD.\n" + }), + "threshold": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Used only for `server_vad` mode. Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }).check(Schema.isFinite()) + ), + "prefix_padding_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Used only for `server_vad` mode. Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }).check(Schema.isInt()) + ), + "silence_duration_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Used only for `server_vad` mode. Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + }).check(Schema.isInt()) + ), + "create_response": Schema.optionalKey(Schema.Boolean.annotate({ + "description": + "Whether or not to automatically generate a response when a VAD stop event occurs. If `interrupt_response` is set to `false` this may fail to create a response if the model is already responding.\n\nIf both `create_response` and `interrupt_response` are set to `false`, the model will never respond automatically but VAD events will still be emitted.\n" + })), + "interrupt_response": Schema.optionalKey(Schema.Boolean.annotate({ + "description": + "Whether or not to automatically interrupt (cancel) any ongoing response with output to the default\nconversation (i.e. `conversation` of `auto`) when a VAD start event occurs. If `true` then the response will be cancelled, otherwise it will continue until complete.\n\nIf both `create_response` and `interrupt_response` are set to `false`, the model will never respond automatically but VAD events will still be emitted.\n" + })), + "idle_timeout_ms": Schema.optionalKey(Schema.Union([ + Schema.Number.annotate({ + "description": + "Optional timeout after which a model response will be triggered automatically. This is\nuseful for situations in which a long pause from the user is unexpected, such as a phone\ncall. The model will effectively prompt the user to continue the conversation based\non the current context.\n\nThe timeout value will be applied after the last model response's audio has finished playing,\ni.e. it's set to the `response.done` time plus audio playback duration.\n\nAn `input_audio_buffer.timeout_triggered` event (plus events\nassociated with the Response) will be emitted when the timeout is reached.\nIdle timeout is currently only supported for `server_vad` mode.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(5000)).check(Schema.isLessThanOrEqualTo(30000)), + Schema.Null + ])) + }).annotate({ + "title": "Server VAD", + "description": + "Server-side voice activity detection (VAD) which flips on when user speech is detected and off after a period of silence." + }), + Schema.Struct({ + "type": Schema.Literal("semantic_vad").annotate({ + "description": "Type of turn detection, `semantic_vad` to turn on Semantic VAD.\n" + }), + "eagerness": Schema.optionalKey( + Schema.Literals(["low", "medium", "high", "auto"]).annotate({ + "description": + "Used only for `semantic_vad` mode. The eagerness of the model to respond. `low` will wait longer for the user to continue speaking, `high` will respond more quickly. `auto` is the default and is equivalent to `medium`. `low`, `medium`, and `high` have max timeouts of 8s, 4s, and 2s respectively.\n" + }) + ), + "create_response": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": "Whether or not to automatically generate a response when a VAD stop event occurs.\n" + }) + ), + "interrupt_response": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": + "Whether or not to automatically interrupt any ongoing response with output to the default\nconversation (i.e. `conversation` of `auto`) when a VAD start event occurs.\n" + }) + ) + }).annotate({ + "title": "Semantic VAD", + "description": + "Server-side semantic turn detection which uses a model to determine when the user has finished speaking." + }) + ], { mode: "oneOf" }).annotate({ + "title": "Realtime Turn Detection", + "description": + "Configuration for turn detection, ether Server VAD or Semantic VAD. This can be set to `null` to turn off, in which case the client must manually trigger model response.\n\nServer VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech.\n\nSemantic VAD is more advanced and uses a turn detection model (in conjunction with VAD) to semantically estimate whether the user has finished speaking, then dynamically sets a timeout based on this probability. For example, if user audio trails off with \"uhhm\", the model will score a low probability of turn end and wait longer for the user to continue speaking. This can be useful for more natural conversations, but may have a higher latency.\n\nFor `gpt-realtime-whisper` transcription sessions, turn detection must be\nset to `null`; VAD is not supported.\n" + }), + Schema.Null +]) +export type ReasoningEffort = "none" | "minimal" | "low" | "medium" | "high" | "xhigh" | null +export const ReasoningEffort = Schema.Union([ + Schema.Literals(["none", "minimal", "low", "medium", "high", "xhigh"]).annotate({ + "description": + "Constrains effort on reasoning for\n[reasoning models](https://platform.openai.com/docs/guides/reasoning).\nCurrently supported values are `none`, `minimal`, `low`, `medium`, `high`, and `xhigh`. Reducing\nreasoning effort can result in faster responses and fewer tokens used\non reasoning in a response.\n\n- `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning values in gpt-5.1.\n- All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`.\n- The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort.\n- `xhigh` is supported for all models after `gpt-5.1-codex-max`.\n" + }), + Schema.Null +]) +export type ResponseAudioDeltaEvent = { + readonly "type": "response.audio.delta" + readonly "sequence_number": number + readonly "delta": string +} +export const ResponseAudioDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.audio.delta").annotate({ + "description": "The type of the event. Always `response.audio.delta`.\n" + }), + "sequence_number": Schema.Number.annotate({ + "description": "A sequence number for this chunk of the stream response.\n" + }).check(Schema.isInt()), + "delta": Schema.String.annotate({ "description": "A chunk of Base64 encoded response audio bytes.\n" }) +}).annotate({ "description": "Emitted when there is a partial audio response." }) +export type ResponseAudioDoneEvent = { + readonly "type": "response.audio.done" + readonly "sequence_number": number + readonly "response_id": unknown +} +export const ResponseAudioDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.audio.done").annotate({ + "description": "The type of the event. Always `response.audio.done`.\n" + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of the delta.\n" }).check( + Schema.isInt() + ), + "response_id": Schema.Unknown +}).annotate({ "description": "Emitted when the audio response is complete." }) +export type ResponseAudioTranscriptDeltaEvent = { + readonly "type": "response.audio.transcript.delta" + readonly "delta": string + readonly "sequence_number": number + readonly "response_id": unknown +} +export const ResponseAudioTranscriptDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.audio.transcript.delta").annotate({ + "description": "The type of the event. Always `response.audio.transcript.delta`.\n" + }), + "delta": Schema.String.annotate({ "description": "The partial transcript of the audio response.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "response_id": Schema.Unknown +}).annotate({ "description": "Emitted when there is a partial transcript of audio." }) +export type ResponseAudioTranscriptDoneEvent = { + readonly "type": "response.audio.transcript.done" + readonly "sequence_number": number + readonly "response_id": unknown +} +export const ResponseAudioTranscriptDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.audio.transcript.done").annotate({ + "description": "The type of the event. Always `response.audio.transcript.done`.\n" + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "response_id": Schema.Unknown +}).annotate({ "description": "Emitted when the full audio transcript is completed." }) +export type ResponseCodeInterpreterCallCodeDeltaEvent = { + readonly "type": "response.code_interpreter_call_code.delta" + readonly "output_index": number + readonly "item_id": string + readonly "delta": string + readonly "sequence_number": number +} +export const ResponseCodeInterpreterCallCodeDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.code_interpreter_call_code.delta").annotate({ + "description": "The type of the event. Always `response.code_interpreter_call_code.delta`." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response for which the code is being streamed." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ "description": "The unique identifier of the code interpreter tool call item." }), + "delta": Schema.String.annotate({ + "description": "The partial code snippet being streamed by the code interpreter." + }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of this event, used to order streaming events." + }).check(Schema.isInt()) +}).annotate({ "description": "Emitted when a partial code snippet is streamed by the code interpreter." }) +export type ResponseCodeInterpreterCallCodeDoneEvent = { + readonly "type": "response.code_interpreter_call_code.done" + readonly "output_index": number + readonly "item_id": string + readonly "code": string + readonly "sequence_number": number +} +export const ResponseCodeInterpreterCallCodeDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.code_interpreter_call_code.done").annotate({ + "description": "The type of the event. Always `response.code_interpreter_call_code.done`." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response for which the code is finalized." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ "description": "The unique identifier of the code interpreter tool call item." }), + "code": Schema.String.annotate({ "description": "The final code snippet output by the code interpreter." }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of this event, used to order streaming events." + }).check(Schema.isInt()) +}).annotate({ "description": "Emitted when the code snippet is finalized by the code interpreter." }) +export type ResponseCodeInterpreterCallCompletedEvent = { + readonly "type": "response.code_interpreter_call.completed" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseCodeInterpreterCallCompletedEvent = Schema.Struct({ + "type": Schema.Literal("response.code_interpreter_call.completed").annotate({ + "description": "The type of the event. Always `response.code_interpreter_call.completed`." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response for which the code interpreter call is completed." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ "description": "The unique identifier of the code interpreter tool call item." }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of this event, used to order streaming events." + }).check(Schema.isInt()) +}).annotate({ "description": "Emitted when the code interpreter call is completed." }) +export type ResponseCodeInterpreterCallInProgressEvent = { + readonly "type": "response.code_interpreter_call.in_progress" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseCodeInterpreterCallInProgressEvent = Schema.Struct({ + "type": Schema.Literal("response.code_interpreter_call.in_progress").annotate({ + "description": "The type of the event. Always `response.code_interpreter_call.in_progress`." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response for which the code interpreter call is in progress." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ "description": "The unique identifier of the code interpreter tool call item." }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of this event, used to order streaming events." + }).check(Schema.isInt()) +}).annotate({ "description": "Emitted when a code interpreter call is in progress." }) +export type ResponseCodeInterpreterCallInterpretingEvent = { + readonly "type": "response.code_interpreter_call.interpreting" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseCodeInterpreterCallInterpretingEvent = Schema.Struct({ + "type": Schema.Literal("response.code_interpreter_call.interpreting").annotate({ + "description": "The type of the event. Always `response.code_interpreter_call.interpreting`." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response for which the code interpreter is interpreting code." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ "description": "The unique identifier of the code interpreter tool call item." }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of this event, used to order streaming events." + }).check(Schema.isInt()) +}).annotate({ "description": "Emitted when the code interpreter is actively interpreting the code snippet." }) +export type ResponseCustomToolCallInputDeltaEvent = { + readonly "type": "response.custom_tool_call_input.delta" + readonly "sequence_number": number + readonly "output_index": number + readonly "item_id": string + readonly "delta": string +} +export const ResponseCustomToolCallInputDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.custom_tool_call_input.delta").annotate({ + "description": "The event type identifier." + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "output_index": Schema.Number.annotate({ "description": "The index of the output this delta applies to." }).check( + Schema.isInt() + ), + "item_id": Schema.String.annotate({ + "description": "Unique identifier for the API item associated with this event." + }), + "delta": Schema.String.annotate({ "description": "The incremental input data (delta) for the custom tool call." }) +}).annotate({ + "title": "ResponseCustomToolCallInputDelta", + "description": "Event representing a delta (partial update) to the input of a custom tool call.\n" +}) +export type ResponseCustomToolCallInputDoneEvent = { + readonly "type": "response.custom_tool_call_input.done" + readonly "sequence_number": number + readonly "output_index": number + readonly "item_id": string + readonly "input": string +} +export const ResponseCustomToolCallInputDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.custom_tool_call_input.done").annotate({ + "description": "The event type identifier." + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "output_index": Schema.Number.annotate({ "description": "The index of the output this event applies to." }).check( + Schema.isInt() + ), + "item_id": Schema.String.annotate({ + "description": "Unique identifier for the API item associated with this event." + }), + "input": Schema.String.annotate({ "description": "The complete input data for the custom tool call." }) +}).annotate({ + "title": "ResponseCustomToolCallInputDone", + "description": "Event indicating that input for a custom tool call is complete.\n" +}) +export type ResponseErrorCode = + | "server_error" + | "rate_limit_exceeded" + | "invalid_prompt" + | "vector_store_timeout" + | "invalid_image" + | "invalid_image_format" + | "invalid_base64_image" + | "invalid_image_url" + | "image_too_large" + | "image_too_small" + | "image_parse_error" + | "image_content_policy_violation" + | "invalid_image_mode" + | "image_file_too_large" + | "unsupported_image_media_type" + | "empty_image_file" + | "failed_to_download_image" + | "image_file_not_found" +export const ResponseErrorCode = Schema.Literals([ + "server_error", + "rate_limit_exceeded", + "invalid_prompt", + "vector_store_timeout", + "invalid_image", + "invalid_image_format", + "invalid_base64_image", + "invalid_image_url", + "image_too_large", + "image_too_small", + "image_parse_error", + "image_content_policy_violation", + "invalid_image_mode", + "image_file_too_large", + "unsupported_image_media_type", + "empty_image_file", + "failed_to_download_image", + "image_file_not_found" +]).annotate({ "description": "The error code for the response.\n" }) +export type ResponseErrorEvent = { + readonly "type": "error" + readonly "code": string | null + readonly "message": string + readonly "param": string | null + readonly "sequence_number": number +} +export const ResponseErrorEvent = Schema.Struct({ + "type": Schema.Literal("error").annotate({ "description": "The type of the event. Always `error`.\n" }), + "code": Schema.Union([Schema.String.annotate({ "description": "The error code.\n" }), Schema.Null]), + "message": Schema.String.annotate({ "description": "The error message.\n" }), + "param": Schema.Union([Schema.String.annotate({ "description": "The error parameter.\n" }), Schema.Null]), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when an error occurs." }) +export type ResponseFileSearchCallCompletedEvent = { + readonly "type": "response.file_search_call.completed" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseFileSearchCallCompletedEvent = Schema.Struct({ + "type": Schema.Literal("response.file_search_call.completed").annotate({ + "description": "The type of the event. Always `response.file_search_call.completed`.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the file search call is initiated.\n" + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The ID of the output item that the file search call is initiated.\n" + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when a file search call is completed (results found)." }) +export type ResponseFileSearchCallInProgressEvent = { + readonly "type": "response.file_search_call.in_progress" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseFileSearchCallInProgressEvent = Schema.Struct({ + "type": Schema.Literal("response.file_search_call.in_progress").annotate({ + "description": "The type of the event. Always `response.file_search_call.in_progress`.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the file search call is initiated.\n" + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The ID of the output item that the file search call is initiated.\n" + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when a file search call is initiated." }) +export type ResponseFileSearchCallSearchingEvent = { + readonly "type": "response.file_search_call.searching" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseFileSearchCallSearchingEvent = Schema.Struct({ + "type": Schema.Literal("response.file_search_call.searching").annotate({ + "description": "The type of the event. Always `response.file_search_call.searching`.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the file search call is searching.\n" + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The ID of the output item that the file search call is initiated.\n" + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when a file search is currently searching." }) +export type ResponseFormatJsonObject = { readonly "type": "json_object" } +export const ResponseFormatJsonObject = Schema.Struct({ + "type": Schema.Literal("json_object").annotate({ + "description": "The type of response format being defined. Always `json_object`." + }) +}).annotate({ + "title": "JSON object", + "description": + "JSON object response format. An older method of generating JSON responses.\nUsing `json_schema` is recommended for models that support it. Note that the\nmodel will not generate JSON without a system or user message instructing it\nto do so.\n" +}) +export type ResponseFormatJsonSchemaSchema = {} +export const ResponseFormatJsonSchemaSchema = Schema.Struct({}).annotate({ + "title": "JSON schema", + "description": + "The schema for the response format, described as a JSON Schema object.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n" +}) +export type ResponseFormatText = { readonly "type": "text" } +export const ResponseFormatText = Schema.Struct({ + "type": Schema.Literal("text").annotate({ + "description": "The type of response format being defined. Always `text`." + }) +}).annotate({ "title": "Text", "description": "Default response format. Used to generate text responses.\n" }) +export type ResponseFunctionCallArgumentsDeltaEvent = { + readonly "type": "response.function_call_arguments.delta" + readonly "item_id": string + readonly "output_index": number + readonly "sequence_number": number + readonly "delta": string +} +export const ResponseFunctionCallArgumentsDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.function_call_arguments.delta").annotate({ + "description": "The type of the event. Always `response.function_call_arguments.delta`.\n" + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the output item that the function-call arguments delta is added to.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the function-call arguments delta is added to.\n" + }).check(Schema.isInt()), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "delta": Schema.String.annotate({ "description": "The function-call arguments delta that is added.\n" }) +}).annotate({ "description": "Emitted when there is a partial function-call arguments delta." }) +export type ResponseFunctionCallArgumentsDoneEvent = { + readonly "type": "response.function_call_arguments.done" + readonly "item_id": string + readonly "name"?: string + readonly "output_index": number + readonly "sequence_number": number + readonly "arguments": string +} +export const ResponseFunctionCallArgumentsDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.function_call_arguments.done"), + "item_id": Schema.String.annotate({ "description": "The ID of the item." }), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the function that was called." })), + "output_index": Schema.Number.annotate({ "description": "The index of the output item." }).check(Schema.isInt()), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "arguments": Schema.String.annotate({ "description": "The function-call arguments." }) +}).annotate({ "description": "Emitted when function-call arguments are finalized." }) +export type ResponseImageGenCallCompletedEvent = { + readonly "type": "response.image_generation_call.completed" + readonly "output_index": number + readonly "sequence_number": number + readonly "item_id": string +} +export const ResponseImageGenCallCompletedEvent = Schema.Struct({ + "type": Schema.Literal("response.image_generation_call.completed").annotate({ + "description": "The type of the event. Always 'response.image_generation_call.completed'." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response's output array." + }).check(Schema.isInt()), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "item_id": Schema.String.annotate({ + "description": "The unique identifier of the image generation item being processed." + }) +}).annotate({ + "title": "ResponseImageGenCallCompletedEvent", + "description": "Emitted when an image generation tool call has completed and the final image is available.\n" +}) +export type ResponseImageGenCallGeneratingEvent = { + readonly "type": "response.image_generation_call.generating" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseImageGenCallGeneratingEvent = Schema.Struct({ + "type": Schema.Literal("response.image_generation_call.generating").annotate({ + "description": "The type of the event. Always 'response.image_generation_call.generating'." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response's output array." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The unique identifier of the image generation item being processed." + }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of the image generation item being processed." + }).check(Schema.isInt()) +}).annotate({ + "title": "ResponseImageGenCallGeneratingEvent", + "description": "Emitted when an image generation tool call is actively generating an image (intermediate state).\n" +}) +export type ResponseImageGenCallInProgressEvent = { + readonly "type": "response.image_generation_call.in_progress" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseImageGenCallInProgressEvent = Schema.Struct({ + "type": Schema.Literal("response.image_generation_call.in_progress").annotate({ + "description": "The type of the event. Always 'response.image_generation_call.in_progress'." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response's output array." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The unique identifier of the image generation item being processed." + }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of the image generation item being processed." + }).check(Schema.isInt()) +}).annotate({ + "title": "ResponseImageGenCallInProgressEvent", + "description": "Emitted when an image generation tool call is in progress.\n" +}) +export type ResponseImageGenCallPartialImageEvent = { + readonly "type": "response.image_generation_call.partial_image" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number + readonly "partial_image_index": number + readonly "partial_image_b64": string +} +export const ResponseImageGenCallPartialImageEvent = Schema.Struct({ + "type": Schema.Literal("response.image_generation_call.partial_image").annotate({ + "description": "The type of the event. Always 'response.image_generation_call.partial_image'." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response's output array." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The unique identifier of the image generation item being processed." + }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of the image generation item being processed." + }).check(Schema.isInt()), + "partial_image_index": Schema.Number.annotate({ + "description": "0-based index for the partial image (backend is 1-based, but this is 0-based for the user)." + }).check(Schema.isInt()), + "partial_image_b64": Schema.String.annotate({ + "description": "Base64-encoded partial image data, suitable for rendering as an image." + }) +}).annotate({ + "title": "ResponseImageGenCallPartialImageEvent", + "description": "Emitted when a partial image is available during image generation streaming.\n" +}) +export type ResponseLogProb = { + readonly "token": string + readonly "logprob": number + readonly "top_logprobs"?: ReadonlyArray<{ readonly "token"?: string; readonly "logprob"?: number }> +} +export const ResponseLogProb = Schema.Struct({ + "token": Schema.String.annotate({ "description": "A possible text token." }), + "logprob": Schema.Number.annotate({ "description": "The log probability of this token.\n" }).check(Schema.isFinite()), + "top_logprobs": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "token": Schema.optionalKey(Schema.String.annotate({ "description": "A possible text token." })), + "logprob": Schema.optionalKey( + Schema.Number.annotate({ "description": "The log probability of this token." }).check(Schema.isFinite()) + ) + }) + ).annotate({ "description": "The log probabilities of up to 20 of the most likely tokens.\n" }) + ) +}).annotate({ + "description": + "A logprob is the logarithmic probability that the model assigns to producing \na particular token at a given position in the sequence. Less-negative (higher) \nlogprob values indicate greater model confidence in that token choice.\n" +}) +export type ResponseMCPCallArgumentsDeltaEvent = { + readonly "type": "response.mcp_call_arguments.delta" + readonly "output_index": number + readonly "item_id": string + readonly "delta": string + readonly "sequence_number": number +} +export const ResponseMCPCallArgumentsDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.mcp_call_arguments.delta").annotate({ + "description": "The type of the event. Always 'response.mcp_call_arguments.delta'." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response's output array." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The unique identifier of the MCP tool call item being processed." + }), + "delta": Schema.String.annotate({ + "description": "A JSON string containing the partial update to the arguments for the MCP tool call.\n" + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "ResponseMCPCallArgumentsDeltaEvent", + "description": "Emitted when there is a delta (partial update) to the arguments of an MCP tool call.\n" +}) +export type ResponseMCPCallArgumentsDoneEvent = { + readonly "type": "response.mcp_call_arguments.done" + readonly "output_index": number + readonly "item_id": string + readonly "arguments": string + readonly "sequence_number": number +} +export const ResponseMCPCallArgumentsDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.mcp_call_arguments.done").annotate({ + "description": "The type of the event. Always 'response.mcp_call_arguments.done'." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response's output array." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The unique identifier of the MCP tool call item being processed." + }), + "arguments": Schema.String.annotate({ + "description": "A JSON string containing the finalized arguments for the MCP tool call.\n" + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "ResponseMCPCallArgumentsDoneEvent", + "description": "Emitted when the arguments for an MCP tool call are finalized.\n" +}) +export type ResponseMCPCallCompletedEvent = { + readonly "type": "response.mcp_call.completed" + readonly "item_id": string + readonly "output_index": number + readonly "sequence_number": number +} +export const ResponseMCPCallCompletedEvent = Schema.Struct({ + "type": Schema.Literal("response.mcp_call.completed").annotate({ + "description": "The type of the event. Always 'response.mcp_call.completed'." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item that completed." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item that completed." }).check( + Schema.isInt() + ), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "ResponseMCPCallCompletedEvent", + "description": "Emitted when an MCP tool call has completed successfully.\n" +}) +export type ResponseMCPCallFailedEvent = { + readonly "type": "response.mcp_call.failed" + readonly "item_id": string + readonly "output_index": number + readonly "sequence_number": number +} +export const ResponseMCPCallFailedEvent = Schema.Struct({ + "type": Schema.Literal("response.mcp_call.failed").annotate({ + "description": "The type of the event. Always 'response.mcp_call.failed'." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item that failed." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item that failed." }).check( + Schema.isInt() + ), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ "title": "ResponseMCPCallFailedEvent", "description": "Emitted when an MCP tool call has failed.\n" }) +export type ResponseMCPCallInProgressEvent = { + readonly "type": "response.mcp_call.in_progress" + readonly "sequence_number": number + readonly "output_index": number + readonly "item_id": string +} +export const ResponseMCPCallInProgressEvent = Schema.Struct({ + "type": Schema.Literal("response.mcp_call.in_progress").annotate({ + "description": "The type of the event. Always 'response.mcp_call.in_progress'." + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response's output array." + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "The unique identifier of the MCP tool call item being processed." + }) +}).annotate({ + "title": "ResponseMCPCallInProgressEvent", + "description": "Emitted when an MCP tool call is in progress.\n" +}) +export type ResponseMCPListToolsCompletedEvent = { + readonly "type": "response.mcp_list_tools.completed" + readonly "item_id": string + readonly "output_index": number + readonly "sequence_number": number +} +export const ResponseMCPListToolsCompletedEvent = Schema.Struct({ + "type": Schema.Literal("response.mcp_list_tools.completed").annotate({ + "description": "The type of the event. Always 'response.mcp_list_tools.completed'." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item that produced this output." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item that was processed." }).check( + Schema.isInt() + ), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "ResponseMCPListToolsCompletedEvent", + "description": "Emitted when the list of available MCP tools has been successfully retrieved.\n" +}) +export type ResponseMCPListToolsFailedEvent = { + readonly "type": "response.mcp_list_tools.failed" + readonly "item_id": string + readonly "output_index": number + readonly "sequence_number": number +} +export const ResponseMCPListToolsFailedEvent = Schema.Struct({ + "type": Schema.Literal("response.mcp_list_tools.failed").annotate({ + "description": "The type of the event. Always 'response.mcp_list_tools.failed'." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item that failed." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item that failed." }).check( + Schema.isInt() + ), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "ResponseMCPListToolsFailedEvent", + "description": "Emitted when the attempt to list available MCP tools has failed.\n" +}) +export type ResponseMCPListToolsInProgressEvent = { + readonly "type": "response.mcp_list_tools.in_progress" + readonly "item_id": string + readonly "output_index": number + readonly "sequence_number": number +} +export const ResponseMCPListToolsInProgressEvent = Schema.Struct({ + "type": Schema.Literal("response.mcp_list_tools.in_progress").annotate({ + "description": "The type of the event. Always 'response.mcp_list_tools.in_progress'." + }), + "item_id": Schema.String.annotate({ "description": "The ID of the MCP tool call item that is being processed." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item that is being processed." }) + .check(Schema.isInt()), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "ResponseMCPListToolsInProgressEvent", + "description": "Emitted when the system is in the process of retrieving the list of available MCP tools.\n" +}) +export type ResponseModalities = ReadonlyArray<"text" | "audio"> | null +export const ResponseModalities = Schema.Union([ + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": + "Output types that you would like the model to generate.\nMost models are capable of generating text, which is the default:\n\n`[\"text\"]`\n\nThe `gpt-4o-audio-preview` model can also be used to\n[generate audio](/docs/guides/audio). To request that this model generate\nboth text and audio responses, you can use:\n\n`[\"text\", \"audio\"]`\n" + }), + Schema.Null +]) +export type ResponseOutputTextAnnotationAddedEvent = { + readonly "type": "response.output_text.annotation.added" + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "annotation_index": number + readonly "sequence_number": number + readonly "annotation": {} +} +export const ResponseOutputTextAnnotationAddedEvent = Schema.Struct({ + "type": Schema.Literal("response.output_text.annotation.added").annotate({ + "description": "The type of the event. Always 'response.output_text.annotation.added'." + }), + "item_id": Schema.String.annotate({ + "description": "The unique identifier of the item to which the annotation is being added." + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item in the response's output array." + }).check(Schema.isInt()), + "content_index": Schema.Number.annotate({ "description": "The index of the content part within the output item." }) + .check(Schema.isInt()), + "annotation_index": Schema.Number.annotate({ "description": "The index of the annotation within the content part." }) + .check(Schema.isInt()), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "annotation": Schema.Struct({}).annotate({ + "description": "The annotation object being added. (See annotation schema for details.)" + }) +}).annotate({ + "title": "ResponseOutputTextAnnotationAddedEvent", + "description": "Emitted when an annotation is added to output text content.\n" +}) +export type ResponsePromptVariables = {} | null +export const ResponsePromptVariables = Schema.Union([ + Schema.Struct({}).annotate({ + "title": "Prompt Variables", + "description": + "Optional map of values to substitute in for variables in your\nprompt. The substitution values can either be strings, or other\nResponse input types like images or files.\n" + }), + Schema.Null +]) +export type ResponseReasoningSummaryPartAddedEvent = { + readonly "type": "response.reasoning_summary_part.added" + readonly "item_id": string + readonly "output_index": number + readonly "summary_index": number + readonly "sequence_number": number + readonly "part": { readonly "type": "summary_text"; readonly "text": string } +} +export const ResponseReasoningSummaryPartAddedEvent = Schema.Struct({ + "type": Schema.Literal("response.reasoning_summary_part.added").annotate({ + "description": "The type of the event. Always `response.reasoning_summary_part.added`.\n" + }), + "item_id": Schema.String.annotate({ "description": "The ID of the item this summary part is associated with.\n" }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item this summary part is associated with.\n" + }).check(Schema.isInt()), + "summary_index": Schema.Number.annotate({ + "description": "The index of the summary part within the reasoning summary.\n" + }).check(Schema.isInt()), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ), + "part": Schema.Struct({ + "type": Schema.Literal("summary_text").annotate({ + "description": "The type of the summary part. Always `summary_text`." + }), + "text": Schema.String.annotate({ "description": "The text of the summary part." }) + }).annotate({ "description": "The summary part that was added.\n" }) +}).annotate({ "description": "Emitted when a new reasoning summary part is added." }) +export type ResponseReasoningSummaryPartDoneEvent = { + readonly "type": "response.reasoning_summary_part.done" + readonly "item_id": string + readonly "output_index": number + readonly "summary_index": number + readonly "sequence_number": number + readonly "part": { readonly "type": "summary_text"; readonly "text": string } +} +export const ResponseReasoningSummaryPartDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.reasoning_summary_part.done").annotate({ + "description": "The type of the event. Always `response.reasoning_summary_part.done`.\n" + }), + "item_id": Schema.String.annotate({ "description": "The ID of the item this summary part is associated with.\n" }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item this summary part is associated with.\n" + }).check(Schema.isInt()), + "summary_index": Schema.Number.annotate({ + "description": "The index of the summary part within the reasoning summary.\n" + }).check(Schema.isInt()), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ), + "part": Schema.Struct({ + "type": Schema.Literal("summary_text").annotate({ + "description": "The type of the summary part. Always `summary_text`." + }), + "text": Schema.String.annotate({ "description": "The text of the summary part." }) + }).annotate({ "description": "The completed summary part.\n" }) +}).annotate({ "description": "Emitted when a reasoning summary part is completed." }) +export type ResponseReasoningSummaryTextDeltaEvent = { + readonly "type": "response.reasoning_summary_text.delta" + readonly "item_id": string + readonly "output_index": number + readonly "summary_index": number + readonly "delta": string + readonly "sequence_number": number +} +export const ResponseReasoningSummaryTextDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.reasoning_summary_text.delta").annotate({ + "description": "The type of the event. Always `response.reasoning_summary_text.delta`.\n" + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the item this summary text delta is associated with.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item this summary text delta is associated with.\n" + }).check(Schema.isInt()), + "summary_index": Schema.Number.annotate({ + "description": "The index of the summary part within the reasoning summary.\n" + }).check(Schema.isInt()), + "delta": Schema.String.annotate({ "description": "The text delta that was added to the summary.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when a delta is added to a reasoning summary text." }) +export type ResponseReasoningSummaryTextDoneEvent = { + readonly "type": "response.reasoning_summary_text.done" + readonly "item_id": string + readonly "output_index": number + readonly "summary_index": number + readonly "text": string + readonly "sequence_number": number +} +export const ResponseReasoningSummaryTextDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.reasoning_summary_text.done").annotate({ + "description": "The type of the event. Always `response.reasoning_summary_text.done`.\n" + }), + "item_id": Schema.String.annotate({ "description": "The ID of the item this summary text is associated with.\n" }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item this summary text is associated with.\n" + }).check(Schema.isInt()), + "summary_index": Schema.Number.annotate({ + "description": "The index of the summary part within the reasoning summary.\n" + }).check(Schema.isInt()), + "text": Schema.String.annotate({ "description": "The full text of the completed reasoning summary.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when a reasoning summary text is completed." }) +export type ResponseReasoningTextDeltaEvent = { + readonly "type": "response.reasoning_text.delta" + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "delta": string + readonly "sequence_number": number +} +export const ResponseReasoningTextDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.reasoning_text.delta").annotate({ + "description": "The type of the event. Always `response.reasoning_text.delta`.\n" + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the item this reasoning text delta is associated with.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item this reasoning text delta is associated with.\n" + }).check(Schema.isInt()), + "content_index": Schema.Number.annotate({ + "description": "The index of the reasoning content part this delta is associated with.\n" + }).check(Schema.isInt()), + "delta": Schema.String.annotate({ "description": "The text delta that was added to the reasoning content.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when a delta is added to a reasoning text." }) +export type ResponseReasoningTextDoneEvent = { + readonly "type": "response.reasoning_text.done" + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "text": string + readonly "sequence_number": number +} +export const ResponseReasoningTextDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.reasoning_text.done").annotate({ + "description": "The type of the event. Always `response.reasoning_text.done`.\n" + }), + "item_id": Schema.String.annotate({ "description": "The ID of the item this reasoning text is associated with.\n" }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item this reasoning text is associated with.\n" + }).check(Schema.isInt()), + "content_index": Schema.Number.annotate({ "description": "The index of the reasoning content part.\n" }).check( + Schema.isInt() + ), + "text": Schema.String.annotate({ "description": "The full text of the completed reasoning content.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when a reasoning text is completed." }) +export type ResponseRefusalDeltaEvent = { + readonly "type": "response.refusal.delta" + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "delta": string + readonly "sequence_number": number +} +export const ResponseRefusalDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.refusal.delta").annotate({ + "description": "The type of the event. Always `response.refusal.delta`.\n" + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the output item that the refusal text is added to.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the refusal text is added to.\n" + }).check(Schema.isInt()), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part that the refusal text is added to.\n" + }).check(Schema.isInt()), + "delta": Schema.String.annotate({ "description": "The refusal text that is added.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when there is a partial refusal text." }) +export type ResponseRefusalDoneEvent = { + readonly "type": "response.refusal.done" + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "refusal": string + readonly "sequence_number": number +} +export const ResponseRefusalDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.refusal.done").annotate({ + "description": "The type of the event. Always `response.refusal.done`.\n" + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the output item that the refusal text is finalized.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the refusal text is finalized.\n" + }).check(Schema.isInt()), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part that the refusal text is finalized.\n" + }).check(Schema.isInt()), + "refusal": Schema.String.annotate({ "description": "The refusal text that is finalized.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when refusal text is finalized." }) +export type ResponseStreamOptions = { readonly "include_obfuscation"?: boolean } | null +export const ResponseStreamOptions = Schema.Union([ + Schema.Struct({ + "include_obfuscation": Schema.optionalKey(Schema.Boolean.annotate({ + "description": + "When true, stream obfuscation will be enabled. Stream obfuscation adds\nrandom characters to an `obfuscation` field on streaming delta events to\nnormalize payload sizes as a mitigation to certain side-channel attacks.\nThese obfuscation fields are included by default, but add a small amount\nof overhead to the data stream. You can set `include_obfuscation` to\nfalse to optimize for bandwidth if you trust the network links between\nyour application and the OpenAI API.\n" + })) + }).annotate({ "description": "Options for streaming responses. Only set this when you set `stream: true`.\n" }), + Schema.Null +]) +export type ResponseUsage = { + readonly "input_tokens": number + readonly "input_tokens_details": { readonly "cached_tokens": number } + readonly "output_tokens": number + readonly "output_tokens_details": { readonly "reasoning_tokens": number } + readonly "total_tokens": number +} +export const ResponseUsage = Schema.Struct({ + "input_tokens": Schema.Number.annotate({ "description": "The number of input tokens." }).check(Schema.isInt()), + "input_tokens_details": Schema.Struct({ + "cached_tokens": Schema.Number.annotate({ + "description": + "The number of tokens that were retrieved from the cache. \n[More on prompt caching](/docs/guides/prompt-caching).\n" + }).check(Schema.isInt()) + }).annotate({ "description": "A detailed breakdown of the input tokens." }), + "output_tokens": Schema.Number.annotate({ "description": "The number of output tokens." }).check(Schema.isInt()), + "output_tokens_details": Schema.Struct({ + "reasoning_tokens": Schema.Number.annotate({ "description": "The number of reasoning tokens." }).check( + Schema.isInt() + ) + }).annotate({ "description": "A detailed breakdown of the output tokens." }), + "total_tokens": Schema.Number.annotate({ "description": "The total number of tokens used." }).check(Schema.isInt()) +}).annotate({ + "description": + "Represents token usage details including input tokens, output tokens,\na breakdown of output tokens, and the total tokens used.\n" +}) +export type ResponseWebSearchCallCompletedEvent = { + readonly "type": "response.web_search_call.completed" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseWebSearchCallCompletedEvent = Schema.Struct({ + "type": Schema.Literal("response.web_search_call.completed").annotate({ + "description": "The type of the event. Always `response.web_search_call.completed`.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the web search call is associated with.\n" + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "Unique ID for the output item associated with the web search call.\n" + }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of the web search call being processed." + }).check(Schema.isInt()) +}).annotate({ "description": "Emitted when a web search call is completed." }) +export type ResponseWebSearchCallInProgressEvent = { + readonly "type": "response.web_search_call.in_progress" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseWebSearchCallInProgressEvent = Schema.Struct({ + "type": Schema.Literal("response.web_search_call.in_progress").annotate({ + "description": "The type of the event. Always `response.web_search_call.in_progress`.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the web search call is associated with.\n" + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "Unique ID for the output item associated with the web search call.\n" + }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of the web search call being processed." + }).check(Schema.isInt()) +}).annotate({ "description": "Emitted when a web search call is initiated." }) +export type ResponseWebSearchCallSearchingEvent = { + readonly "type": "response.web_search_call.searching" + readonly "output_index": number + readonly "item_id": string + readonly "sequence_number": number +} +export const ResponseWebSearchCallSearchingEvent = Schema.Struct({ + "type": Schema.Literal("response.web_search_call.searching").annotate({ + "description": "The type of the event. Always `response.web_search_call.searching`.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the web search call is associated with.\n" + }).check(Schema.isInt()), + "item_id": Schema.String.annotate({ + "description": "Unique ID for the output item associated with the web search call.\n" + }), + "sequence_number": Schema.Number.annotate({ + "description": "The sequence number of the web search call being processed." + }).check(Schema.isInt()) +}).annotate({ "description": "Emitted when a web search call is executing." }) +export type Role = { + readonly "object": "role" + readonly "id": string + readonly "name": string + readonly "description": string | null + readonly "permissions": ReadonlyArray + readonly "resource_type": string + readonly "predefined_role": boolean +} +export const Role = Schema.Struct({ + "object": Schema.Literal("role").annotate({ "description": "Always `role`." }), + "id": Schema.String.annotate({ "description": "Identifier for the role." }), + "name": Schema.String.annotate({ "description": "Unique name for the role." }), + "description": Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "Optional description of the role." + }), + "permissions": Schema.Array(Schema.String).annotate({ "description": "Permissions granted by the role." }), + "resource_type": Schema.String.annotate({ + "description": "Resource type the role is bound to (for example `api.organization` or `api.project`)." + }), + "predefined_role": Schema.Boolean.annotate({ "description": "Whether the role is predefined and managed by OpenAI." }) +}).annotate({ "description": "Details about a role that can be assigned through the public Roles API." }) +export type RoleDeletedResource = { + readonly "object": "role.deleted" + readonly "id": string + readonly "deleted": boolean +} +export const RoleDeletedResource = Schema.Struct({ + "object": Schema.Literal("role.deleted").annotate({ "description": "Always `role.deleted`." }), + "id": Schema.String.annotate({ "description": "Identifier of the deleted role." }), + "deleted": Schema.Boolean.annotate({ "description": "Whether the role was deleted." }) +}).annotate({ "description": "Confirmation payload returned after deleting a role." }) +export type RunCompletionUsage = { + readonly "completion_tokens": number + readonly "prompt_tokens": number + readonly "total_tokens": number +} | null +export const RunCompletionUsage = Schema.Union([ + Schema.Struct({ + "completion_tokens": Schema.Number.annotate({ + "description": "Number of completion tokens used over the course of the run." + }).check(Schema.isInt()), + "prompt_tokens": Schema.Number.annotate({ + "description": "Number of prompt tokens used over the course of the run." + }).check(Schema.isInt()), + "total_tokens": Schema.Number.annotate({ "description": "Total number of tokens used (prompt + completion)." }) + .check(Schema.isInt()) + }).annotate({ + "description": + "Usage statistics related to the run. This value will be `null` if the run is not in a terminal state (i.e. `in_progress`, `queued`, etc.)." + }), + Schema.Null +]) +export type RunGraderResponse = { + readonly "reward": number + readonly "metadata": { + readonly "name": string + readonly "type": string + readonly "errors": { + readonly "formula_parse_error": boolean + readonly "sample_parse_error": boolean + readonly "truncated_observation_error": boolean + readonly "unresponsive_reward_error": boolean + readonly "invalid_variable_error": boolean + readonly "other_error": boolean + readonly "python_grader_server_error": boolean + readonly "python_grader_server_error_type": string | null + readonly "python_grader_runtime_error": boolean + readonly "python_grader_runtime_error_details": string | null + readonly "model_grader_server_error": boolean + readonly "model_grader_refusal_error": boolean + readonly "model_grader_parse_error": boolean + readonly "model_grader_server_error_details": string | null + } + readonly "execution_time": number + readonly "scores": {} + readonly "token_usage": number | null + readonly "sampled_model_name": string | null + } + readonly "sub_rewards": {} + readonly "model_grader_token_usage_per_model": {} +} +export const RunGraderResponse = Schema.Struct({ + "reward": Schema.Number.check(Schema.isFinite()), + "metadata": Schema.Struct({ + "name": Schema.String, + "type": Schema.String, + "errors": Schema.Struct({ + "formula_parse_error": Schema.Boolean, + "sample_parse_error": Schema.Boolean, + "truncated_observation_error": Schema.Boolean, + "unresponsive_reward_error": Schema.Boolean, + "invalid_variable_error": Schema.Boolean, + "other_error": Schema.Boolean, + "python_grader_server_error": Schema.Boolean, + "python_grader_server_error_type": Schema.Union([Schema.String, Schema.Null]), + "python_grader_runtime_error": Schema.Boolean, + "python_grader_runtime_error_details": Schema.Union([Schema.String, Schema.Null]), + "model_grader_server_error": Schema.Boolean, + "model_grader_refusal_error": Schema.Boolean, + "model_grader_parse_error": Schema.Boolean, + "model_grader_server_error_details": Schema.Union([Schema.String, Schema.Null]) + }), + "execution_time": Schema.Number.check(Schema.isFinite()), + "scores": Schema.Struct({}), + "token_usage": Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]), + "sampled_model_name": Schema.Union([Schema.String, Schema.Null]) + }), + "sub_rewards": Schema.Struct({}), + "model_grader_token_usage_per_model": Schema.Struct({}) +}) +export type RunStepCompletionUsage = { + readonly "completion_tokens": number + readonly "prompt_tokens": number + readonly "total_tokens": number +} | null +export const RunStepCompletionUsage = Schema.Union([ + Schema.Struct({ + "completion_tokens": Schema.Number.annotate({ + "description": "Number of completion tokens used over the course of the run step." + }).check(Schema.isInt()), + "prompt_tokens": Schema.Number.annotate({ + "description": "Number of prompt tokens used over the course of the run step." + }).check(Schema.isInt()), + "total_tokens": Schema.Number.annotate({ "description": "Total number of tokens used (prompt + completion)." }) + .check(Schema.isInt()) + }).annotate({ + "description": + "Usage statistics related to the run step. This value will be `null` while the run step's status is `in_progress`." + }), + Schema.Null +]) +export type RunStepDeltaStepDetailsToolCallsCodeObject = { + readonly "index": number + readonly "id"?: string + readonly "type": "code_interpreter" + readonly "code_interpreter"?: { + readonly "input"?: string + readonly "outputs"?: ReadonlyArray< + { readonly "index": number; readonly "type": "logs"; readonly "logs"?: string } | { + readonly "index": number + readonly "type": "image" + readonly "image"?: { readonly "file_id"?: string } + } + > + } +} +export const RunStepDeltaStepDetailsToolCallsCodeObject = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the tool call in the tool calls array." }).check( + Schema.isInt() + ), + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the tool call." })), + "type": Schema.Literal("code_interpreter").annotate({ + "description": "The type of tool call. This is always going to be `code_interpreter` for this type of tool call." + }), + "code_interpreter": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey( + Schema.String.annotate({ "description": "The input to the Code Interpreter tool call." }) + ), + "outputs": Schema.optionalKey( + Schema.Array(Schema.Union([ + Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the output in the outputs array." }).check( + Schema.isInt() + ), + "type": Schema.Literal("logs").annotate({ "description": "Always `logs`." }), + "logs": Schema.optionalKey( + Schema.String.annotate({ "description": "The text output from the Code Interpreter tool call." }) + ) + }).annotate({ + "title": "Code interpreter log output", + "description": "Text output from the Code Interpreter tool call as part of a run step." + }), + Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the output in the outputs array." }).check( + Schema.isInt() + ), + "type": Schema.Literal("image").annotate({ "description": "Always `image`." }), + "image": Schema.optionalKey( + Schema.Struct({ + "file_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The [file](/docs/api-reference/files) ID of the image." }) + ) + }) + ) + }).annotate({ "title": "Code interpreter image output" }) + ], { mode: "oneOf" })).annotate({ + "description": + "The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type." + }) + ) + }).annotate({ "description": "The Code Interpreter tool call definition." }) + ) +}).annotate({ + "title": "Code interpreter tool call", + "description": "Details of the Code Interpreter tool call the run step was involved in." +}) +export type RunStepDeltaStepDetailsToolCallsFileSearchObject = { + readonly "index": number + readonly "id"?: string + readonly "type": "file_search" + readonly "file_search": {} +} +export const RunStepDeltaStepDetailsToolCallsFileSearchObject = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the tool call in the tool calls array." }).check( + Schema.isInt() + ), + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the tool call object." })), + "type": Schema.Literal("file_search").annotate({ + "description": "The type of tool call. This is always going to be `file_search` for this type of tool call." + }), + "file_search": Schema.Struct({}).annotate({ "description": "For now, this is always going to be an empty object." }) +}).annotate({ "title": "File search tool call" }) +export type RunStepDeltaStepDetailsToolCallsFunctionObject = { + readonly "index": number + readonly "id"?: string + readonly "type": "function" + readonly "function"?: { readonly "name"?: string; readonly "arguments"?: string; readonly "output"?: string | null } +} +export const RunStepDeltaStepDetailsToolCallsFunctionObject = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the tool call in the tool calls array." }).check( + Schema.isInt() + ), + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the tool call object." })), + "type": Schema.Literal("function").annotate({ + "description": "The type of tool call. This is always going to be `function` for this type of tool call." + }), + "function": Schema.optionalKey( + Schema.Struct({ + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the function." })), + "arguments": Schema.optionalKey( + Schema.String.annotate({ "description": "The arguments passed to the function." }) + ), + "output": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet." + }), + Schema.Null + ]) + ) + }).annotate({ "description": "The definition of the function that was called." }) + ) +}).annotate({ "title": "Function tool call" }) +export type RunStepDetailsToolCallsCodeObject = { + readonly "id": string + readonly "type": "code_interpreter" + readonly "code_interpreter": { + readonly "input": string + readonly "outputs": ReadonlyArray< + { readonly "type": "logs"; readonly "logs": string } | { + readonly "type": "image" + readonly "image": { readonly "file_id": string } + } + > + } +} +export const RunStepDetailsToolCallsCodeObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The ID of the tool call." }), + "type": Schema.Literal("code_interpreter").annotate({ + "description": "The type of tool call. This is always going to be `code_interpreter` for this type of tool call." + }), + "code_interpreter": Schema.Struct({ + "input": Schema.String.annotate({ "description": "The input to the Code Interpreter tool call." }), + "outputs": Schema.Array( + Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("logs").annotate({ "description": "Always `logs`." }), + "logs": Schema.String.annotate({ "description": "The text output from the Code Interpreter tool call." }) + }).annotate({ + "title": "Code Interpreter log output", + "description": "Text output from the Code Interpreter tool call as part of a run step." + }), + Schema.Struct({ + "type": Schema.Literal("image").annotate({ "description": "Always `image`." }), + "image": Schema.Struct({ + "file_id": Schema.String.annotate({ + "description": "The [file](/docs/api-reference/files) ID of the image." + }) + }) + }).annotate({ "title": "Code Interpreter image output" }) + ], { mode: "oneOf" }) + ).annotate({ + "description": + "The outputs from the Code Interpreter tool call. Code Interpreter can output one or more items, including text (`logs`) or images (`image`). Each of these are represented by a different object type." + }) + }).annotate({ "description": "The Code Interpreter tool call definition." }) +}).annotate({ + "title": "Code Interpreter tool call", + "description": "Details of the Code Interpreter tool call the run step was involved in." +}) +export type RunStepDetailsToolCallsFileSearchResultObject = { + readonly "file_id": string + readonly "file_name": string + readonly "score": number + readonly "content"?: ReadonlyArray<{ readonly "type"?: "text"; readonly "text"?: string }> +} +export const RunStepDetailsToolCallsFileSearchResultObject = Schema.Struct({ + "file_id": Schema.String.annotate({ "description": "The ID of the file that result was found in." }), + "file_name": Schema.String.annotate({ "description": "The name of the file that result was found in." }), + "score": Schema.Number.annotate({ + "description": "The score of the result. All values must be a floating point number between 0 and 1." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + "content": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "type": Schema.optionalKey(Schema.Literal("text").annotate({ "description": "The type of the content." })), + "text": Schema.optionalKey(Schema.String.annotate({ "description": "The text content of the file." })) + }) + ).annotate({ + "description": + "The content of the result that was found. The content is only included if requested via the include query parameter." + }) + ) +}).annotate({ "title": "File search tool call result", "description": "A result instance of the file search." }) +export type RunStepDetailsToolCallsFunctionObject = { + readonly "id": string + readonly "type": "function" + readonly "function": { readonly "name": string; readonly "arguments": string; readonly "output": string | null } +} +export const RunStepDetailsToolCallsFunctionObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The ID of the tool call object." }), + "type": Schema.Literal("function").annotate({ + "description": "The type of tool call. This is always going to be `function` for this type of tool call." + }), + "function": Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the function." }), + "arguments": Schema.String.annotate({ "description": "The arguments passed to the function." }), + "output": Schema.Union([ + Schema.String.annotate({ + "description": + "The output of the function. This will be `null` if the outputs have not been [submitted](/docs/api-reference/runs/submitToolOutputs) yet." + }), + Schema.Null + ]) + }).annotate({ "description": "The definition of the function that was called." }) +}).annotate({ "title": "Function tool call" }) +export type RunToolCallObject = { + readonly "id": string + readonly "type": "function" + readonly "function": { readonly "name": string; readonly "arguments": string } +} +export const RunToolCallObject = Schema.Struct({ + "id": Schema.String.annotate({ + "description": + "The ID of the tool call. This ID must be referenced when you submit the tool outputs in using the [Submit tool outputs to run](/docs/api-reference/runs/submitToolOutputs) endpoint." + }), + "type": Schema.Literal("function").annotate({ + "description": "The type of tool call the output is required for. For now, this is always `function`." + }), + "function": Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the function." }), + "arguments": Schema.String.annotate({ + "description": "The arguments that the model expects you to pass to the function." + }) + }).annotate({ "description": "The function definition." }) +}).annotate({ "description": "Tool call objects" }) +export type ServiceTier = "auto" | "default" | "flex" | "scale" | "priority" | null +export const ServiceTier = Schema.Union([ + Schema.Literals(["auto", "default", "flex", "scale", "priority"]).annotate({ + "description": + "Specifies the processing type used for serving the request.\n - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'.\n - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model.\n - If set to '[flex](/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier.\n - When not set, the default behavior is 'auto'.\n\n When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter.\n" + }), + Schema.Null +]) +export type SpeechAudioDeltaEvent = { readonly "type": "speech.audio.delta"; readonly "audio": string } +export const SpeechAudioDeltaEvent = Schema.Struct({ + "type": Schema.Literal("speech.audio.delta").annotate({ + "description": "The type of the event. Always `speech.audio.delta`.\n" + }), + "audio": Schema.String.annotate({ "description": "A chunk of Base64-encoded audio data.\n" }) +}).annotate({ "description": "Emitted for each chunk of audio data generated during speech synthesis." }) +export type SpeechAudioDoneEvent = { + readonly "type": "speech.audio.done" + readonly "usage": { + readonly "input_tokens": number + readonly "output_tokens": number + readonly "total_tokens": number + } +} +export const SpeechAudioDoneEvent = Schema.Struct({ + "type": Schema.Literal("speech.audio.done").annotate({ + "description": "The type of the event. Always `speech.audio.done`.\n" + }), + "usage": Schema.Struct({ + "input_tokens": Schema.Number.annotate({ "description": "Number of input tokens in the prompt." }).check( + Schema.isInt() + ), + "output_tokens": Schema.Number.annotate({ "description": "Number of output tokens generated." }).check( + Schema.isInt() + ), + "total_tokens": Schema.Number.annotate({ "description": "Total number of tokens used (input + output)." }).check( + Schema.isInt() + ) + }).annotate({ "description": "Token usage statistics for the request.\n" }) +}).annotate({ "description": "Emitted when the speech synthesis is complete and all audio has been streamed." }) +export type StaticChunkingStrategy = { + readonly "max_chunk_size_tokens": number + readonly "chunk_overlap_tokens": number +} +export const StaticChunkingStrategy = Schema.Struct({ + "max_chunk_size_tokens": Schema.Number.annotate({ + "description": + "The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(100)).check(Schema.isLessThanOrEqualTo(4096)), + "chunk_overlap_tokens": Schema.Number.annotate({ + "description": + "The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" + }).check(Schema.isInt()) +}) +export type StopConfiguration = string | null | ReadonlyArray | null +export const StopConfiguration = Schema.Union([ + Schema.Union([ + Schema.Union([Schema.String, Schema.Null]), + Schema.Array(Schema.String).check(Schema.isMinLength(1)).check(Schema.isMaxLength(4)) + ], { mode: "oneOf" }).annotate({ + "description": + "Not supported with latest reasoning models `o3` and `o4-mini`.\n\nUp to 4 sequences where the API will stop generating further tokens. The\nreturned text will not contain the stop sequence.\n" + }), + Schema.Null +]) +export type SubmitToolOutputsRunRequest = { + readonly "tool_outputs": ReadonlyArray<{ readonly "tool_call_id"?: string; readonly "output"?: string }> + readonly "stream"?: boolean | null +} +export const SubmitToolOutputsRunRequest = Schema.Struct({ + "tool_outputs": Schema.Array(Schema.Struct({ + "tool_call_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The ID of the tool call in the `required_action` object within the run object the output is being submitted for." + }) + ), + "output": Schema.optionalKey( + Schema.String.annotate({ "description": "The output of the tool call to be submitted to continue the run." }) + ) + })).annotate({ "description": "A list of tools for which the outputs are being submitted." }), + "stream": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": + "If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" + }), + Schema.Null + ]) + ) +}) +export type ToggleCertificatesRequest = { readonly "certificate_ids": ReadonlyArray } +export const ToggleCertificatesRequest = Schema.Struct({ + "certificate_ids": Schema.Array(Schema.String).check(Schema.isMinLength(1)).check(Schema.isMaxLength(10)) +}) +export type ToolChoiceAllowed = { + readonly "type": "allowed_tools" + readonly "mode": "auto" | "required" + readonly "tools": ReadonlyArray<{}> +} +export const ToolChoiceAllowed = Schema.Struct({ + "type": Schema.Literal("allowed_tools").annotate({ + "description": "Allowed tool configuration type. Always `allowed_tools`." + }), + "mode": Schema.Literals(["auto", "required"]).annotate({ + "description": + "Constrains the tools available to the model to a pre-defined set.\n\n`auto` allows the model to pick from among the allowed tools and generate a\nmessage.\n\n`required` requires the model to call one or more of the allowed tools.\n" + }), + "tools": Schema.Array( + Schema.Struct({}).annotate({ "description": "A tool definition that the model should be allowed to call.\n" }) + ).annotate({ + "description": + "A list of tool definitions that the model should be allowed to call.\n\nFor the Responses API, the list of tool definitions might look like:\n```json\n[\n { \"type\": \"function\", \"name\": \"get_weather\" },\n { \"type\": \"mcp\", \"server_label\": \"deepwiki\" },\n { \"type\": \"image_generation\" }\n]\n```\n" + }) +}).annotate({ + "title": "Allowed tools", + "description": "Constrains the tools available to the model to a pre-defined set.\n" +}) +export type ToolChoiceCustom = { readonly "type": "custom"; readonly "name": string } +export const ToolChoiceCustom = Schema.Struct({ + "type": Schema.Literal("custom").annotate({ "description": "For custom tool calling, the type is always `custom`." }), + "name": Schema.String.annotate({ "description": "The name of the custom tool to call." }) +}).annotate({ + "title": "Custom tool", + "description": "Use this option to force the model to call a specific custom tool.\n" +}) +export type ToolChoiceFunction = { readonly "type": "function"; readonly "name": string } +export const ToolChoiceFunction = Schema.Struct({ + "type": Schema.Literal("function").annotate({ + "description": "For function calling, the type is always `function`." + }), + "name": Schema.String.annotate({ "description": "The name of the function to call." }) +}).annotate({ + "title": "Function tool", + "description": "Use this option to force the model to call a specific function.\n" +}) +export type ToolChoiceMCP = { readonly "type": "mcp"; readonly "server_label": string; readonly "name"?: string | null } +export const ToolChoiceMCP = Schema.Struct({ + "type": Schema.Literal("mcp").annotate({ "description": "For MCP tools, the type is always `mcp`." }), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server to use.\n" }), + "name": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The name of the tool to call on the server.\n" }), + Schema.Null + ]) + ) +}).annotate({ + "title": "MCP tool", + "description": "Use this option to force the model to call a specific tool on a remote MCP server.\n" +}) +export type ToolChoiceOptions = "none" | "auto" | "required" +export const ToolChoiceOptions = Schema.Literals(["none", "auto", "required"]).annotate({ + "title": "Tool choice mode", + "description": + "Controls which (if any) tool is called by the model.\n\n`none` means the model will not call any tool and instead generates a message.\n\n`auto` means the model can pick between generating a message or calling one or\nmore tools.\n\n`required` means the model must call one or more tools.\n" +}) +export type ToolChoiceTypes = { + readonly "type": + | "file_search" + | "web_search_preview" + | "computer" + | "computer_use_preview" + | "computer_use" + | "web_search_preview_2025_03_11" + | "image_generation" + | "code_interpreter" +} +export const ToolChoiceTypes = Schema.Struct({ + "type": Schema.Literals([ + "file_search", + "web_search_preview", + "computer", + "computer_use_preview", + "computer_use", + "web_search_preview_2025_03_11", + "image_generation", + "code_interpreter" + ]).annotate({ + "description": + "The type of hosted tool the model should to use. Learn more about\n[built-in tools](/docs/guides/tools).\n\nAllowed values are:\n- `file_search`\n- `web_search_preview`\n- `computer`\n- `computer_use_preview`\n- `computer_use`\n- `code_interpreter`\n- `image_generation`\n" + }) +}).annotate({ + "title": "Hosted tool", + "description": + "Indicates that the model should use a built-in tool to generate a response.\n[Learn more about built-in tools](/docs/guides/tools).\n" +}) +export type TranscriptTextDeltaEvent = { + readonly "type": "transcript.text.delta" + readonly "delta": string + readonly "logprobs"?: ReadonlyArray< + { readonly "token"?: string; readonly "logprob"?: number; readonly "bytes"?: ReadonlyArray } + > + readonly "segment_id"?: string +} +export const TranscriptTextDeltaEvent = Schema.Struct({ + "type": Schema.Literal("transcript.text.delta").annotate({ + "description": "The type of the event. Always `transcript.text.delta`.\n" + }), + "delta": Schema.String.annotate({ "description": "The text delta that was additionally transcribed.\n" }), + "logprobs": Schema.optionalKey( + Schema.Array(Schema.Struct({ + "token": Schema.optionalKey( + Schema.String.annotate({ "description": "The token that was used to generate the log probability.\n" }) + ), + "logprob": Schema.optionalKey( + Schema.Number.annotate({ "description": "The log probability of the token.\n" }).check(Schema.isFinite()) + ), + "bytes": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": "The bytes that were used to generate the log probability.\n" + }) + ) + })).annotate({ + "description": + "The log probabilities of the delta. Only included if you [create a transcription](/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`.\n" + }) + ), + "segment_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "Identifier of the diarized segment that this delta belongs to. Only present when using `gpt-4o-transcribe-diarize`.\n" + }) + ) +}).annotate({ + "description": + "Emitted when there is an additional text delta. This is also the first event emitted when the transcription starts. Only emitted when you [create a transcription](/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`." +}) +export type TranscriptTextSegmentEvent = { + readonly "type": "transcript.text.segment" + readonly "id": string + readonly "start": number + readonly "end": number + readonly "text": string + readonly "speaker": string +} +export const TranscriptTextSegmentEvent = Schema.Struct({ + "type": Schema.Literal("transcript.text.segment").annotate({ + "description": "The type of the event. Always `transcript.text.segment`." + }), + "id": Schema.String.annotate({ "description": "Unique identifier for the segment." }), + "start": Schema.Number.annotate({ "description": "Start timestamp of the segment in seconds.", "format": "double" }) + .check(Schema.isFinite()), + "end": Schema.Number.annotate({ "description": "End timestamp of the segment in seconds.", "format": "double" }) + .check(Schema.isFinite()), + "text": Schema.String.annotate({ "description": "Transcript text for this segment." }), + "speaker": Schema.String.annotate({ "description": "Speaker label for this segment." }) +}).annotate({ + "description": + "Emitted when a diarized transcription returns a completed segment with speaker information. Only emitted when you [create a transcription](/docs/api-reference/audio/create-transcription) with `stream` set to `true` and `response_format` set to `diarized_json`.\n" +}) +export type TranscriptTextUsageDuration = { readonly "type": "duration"; readonly "seconds": number } +export const TranscriptTextUsageDuration = Schema.Struct({ + "type": Schema.Literal("duration").annotate({ + "description": "The type of the usage object. Always `duration` for this variant." + }), + "seconds": Schema.Number.annotate({ "description": "Duration of the input audio in seconds.", "format": "double" }) + .check(Schema.isFinite()) +}).annotate({ "title": "Duration Usage", "description": "Usage statistics for models billed by audio input duration." }) +export type TranscriptTextUsageTokens = { + readonly "type": "tokens" + readonly "input_tokens": number + readonly "input_token_details"?: { readonly "text_tokens"?: number; readonly "audio_tokens"?: number } + readonly "output_tokens": number + readonly "total_tokens": number +} +export const TranscriptTextUsageTokens = Schema.Struct({ + "type": Schema.Literal("tokens").annotate({ + "description": "The type of the usage object. Always `tokens` for this variant." + }), + "input_tokens": Schema.Number.annotate({ "description": "Number of input tokens billed for this request." }).check( + Schema.isInt() + ), + "input_token_details": Schema.optionalKey( + Schema.Struct({ + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Number of text tokens billed for this request." }).check( + Schema.isInt() + ) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Number of audio tokens billed for this request." }).check( + Schema.isInt() + ) + ) + }).annotate({ "description": "Details about the input tokens billed for this request." }) + ), + "output_tokens": Schema.Number.annotate({ "description": "Number of output tokens generated." }).check( + Schema.isInt() + ), + "total_tokens": Schema.Number.annotate({ "description": "Total number of tokens used (input + output)." }).check( + Schema.isInt() + ) +}).annotate({ "title": "Token Usage", "description": "Usage statistics for models billed by token usage." }) +export type TranscriptionDiarizedSegment = { + readonly "type": "transcript.text.segment" + readonly "id": string + readonly "start": number + readonly "end": number + readonly "text": string + readonly "speaker": string +} +export const TranscriptionDiarizedSegment = Schema.Struct({ + "type": Schema.Literal("transcript.text.segment").annotate({ + "description": "The type of the segment. Always `transcript.text.segment`.\n" + }), + "id": Schema.String.annotate({ "description": "Unique identifier for the segment." }), + "start": Schema.Number.annotate({ "description": "Start timestamp of the segment in seconds.", "format": "double" }) + .check(Schema.isFinite()), + "end": Schema.Number.annotate({ "description": "End timestamp of the segment in seconds.", "format": "double" }) + .check(Schema.isFinite()), + "text": Schema.String.annotate({ "description": "Transcript text for this segment." }), + "speaker": Schema.String.annotate({ + "description": + "Speaker label for this segment. When known speakers are provided, the label matches `known_speaker_names[]`. Otherwise speakers are labeled sequentially using capital letters (`A`, `B`, ...).\n" + }) +}).annotate({ "description": "A segment of diarized transcript text with speaker metadata." }) +export type TranscriptionInclude = "logprobs" +export const TranscriptionInclude = Schema.Literal("logprobs") +export type TranscriptionSegment = { + readonly "id": number + readonly "seek": number + readonly "start": number + readonly "end": number + readonly "text": string + readonly "tokens": ReadonlyArray + readonly "temperature": number + readonly "avg_logprob": number + readonly "compression_ratio": number + readonly "no_speech_prob": number +} +export const TranscriptionSegment = Schema.Struct({ + "id": Schema.Number.annotate({ "description": "Unique identifier of the segment." }).check(Schema.isInt()), + "seek": Schema.Number.annotate({ "description": "Seek offset of the segment." }).check(Schema.isInt()), + "start": Schema.Number.annotate({ "description": "Start time of the segment in seconds.", "format": "double" }).check( + Schema.isFinite() + ), + "end": Schema.Number.annotate({ "description": "End time of the segment in seconds.", "format": "double" }).check( + Schema.isFinite() + ), + "text": Schema.String.annotate({ "description": "Text content of the segment." }), + "tokens": Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": "Array of token IDs for the text content." + }), + "temperature": Schema.Number.annotate({ + "description": "Temperature parameter used for generating the segment.", + "format": "float" + }).check(Schema.isFinite()), + "avg_logprob": Schema.Number.annotate({ + "description": "Average logprob of the segment. If the value is lower than -1, consider the logprobs failed.", + "format": "float" + }).check(Schema.isFinite()), + "compression_ratio": Schema.Number.annotate({ + "description": + "Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed.", + "format": "float" + }).check(Schema.isFinite()), + "no_speech_prob": Schema.Number.annotate({ + "description": + "Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent.", + "format": "float" + }).check(Schema.isFinite()) +}) +export type TranscriptionWord = { readonly "word": string; readonly "start": number; readonly "end": number } +export const TranscriptionWord = Schema.Struct({ + "word": Schema.String.annotate({ "description": "The text content of the word." }), + "start": Schema.Number.annotate({ "description": "Start time of the word in seconds.", "format": "double" }).check( + Schema.isFinite() + ), + "end": Schema.Number.annotate({ "description": "End time of the word in seconds.", "format": "double" }).check( + Schema.isFinite() + ) +}) +export type UpdateGroupBody = { readonly "name": string } +export const UpdateGroupBody = Schema.Struct({ + "name": Schema.String.annotate({ "description": "New display name for the group." }).check(Schema.isMinLength(1)) + .check(Schema.isMaxLength(255)) +}).annotate({ "description": "Request payload for updating the details of an existing group." }) +export type UpdateVoiceConsentRequest = { readonly "name": string } +export const UpdateVoiceConsentRequest = Schema.Struct({ + "name": Schema.String.annotate({ "description": "The updated label for this consent recording." }) +}) +export type Upload = { + readonly "id": string + readonly "created_at": number + readonly "filename": string + readonly "bytes": number + readonly "purpose": string + readonly "status": "pending" | "completed" | "cancelled" | "expired" + readonly "expires_at": number + readonly "object"?: "upload" + readonly "file"?: { + readonly "id": string + readonly "bytes": number + readonly "created_at": number + readonly "expires_at"?: number | null + readonly "filename": string + readonly "object": "file" + readonly "purpose": + | "assistants" + | "assistants_output" + | "batch" + | "batch_output" + | "fine-tune" + | "fine-tune-results" + | "vision" + | "user_data" + readonly "status": "uploaded" | "processed" | "error" + readonly "status_details"?: string | null + readonly [x: string]: unknown + } +} +export const Upload = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The Upload unique identifier, which can be referenced in API endpoints." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the Upload was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "filename": Schema.String.annotate({ "description": "The name of the file to be uploaded." }), + "bytes": Schema.Number.annotate({ "description": "The intended number of bytes to be uploaded." }).check( + Schema.isInt() + ), + "purpose": Schema.String.annotate({ + "description": + "The intended purpose of the file. [Please refer here](/docs/api-reference/files/object#files/object-purpose) for acceptable values." + }), + "status": Schema.Literals(["pending", "completed", "cancelled", "expired"]).annotate({ + "description": "The status of the Upload." + }), + "expires_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the Upload will expire.", + "format": "unixtime" + }).check(Schema.isInt()), + "object": Schema.optionalKey( + Schema.Literal("upload").annotate({ "description": "The object type, which is always \"upload\"." }) + ), + "file": Schema.optionalKey(Schema.Union([ + Schema.StructWithRest( + Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The file identifier, which can be referenced in the API endpoints." + }), + "bytes": Schema.Number.annotate({ "description": "The size of the file, in bytes." }).check(Schema.isInt()), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the file was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "expires_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the file will expire.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "filename": Schema.String.annotate({ "description": "The name of the file." }), + "object": Schema.Literal("file").annotate({ "description": "The object type, which is always `file`." }), + "purpose": Schema.Literals([ + "assistants", + "assistants_output", + "batch", + "batch_output", + "fine-tune", + "fine-tune-results", + "vision", + "user_data" + ]).annotate({ + "description": + "The intended purpose of the file. Supported values are `assistants`, `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results`, `vision`, and `user_data`." + }), + "status": Schema.Literals(["uploaded", "processed", "error"]).annotate({ + "description": + "Deprecated. The current status of the file, which can be either `uploaded`, `processed`, or `error`." + }), + "status_details": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Deprecated. For details on why a fine-tuning training file failed validation, see the `error` field on `fine_tuning.job`." + }) + ) + }), + [Schema.Record(Schema.String, Schema.Json)] + ).annotate({ + "description": "The `File` object represents a document that has been uploaded to OpenAI.", + "title": "OpenAIFile" + }) + ])) +}).annotate({ "title": "Upload", "description": "The Upload object can accept byte chunks in the form of Parts.\n" }) +export type UploadCertificateRequest = { readonly "name"?: string; readonly "certificate": string } +export const UploadCertificateRequest = Schema.Struct({ + "name": Schema.optionalKey(Schema.String.annotate({ "description": "An optional name for the certificate" })), + "certificate": Schema.String.annotate({ "description": "The certificate content in PEM format" }) +}) +export type UploadPart = { + readonly "id": string + readonly "created_at": number + readonly "upload_id": string + readonly "object": "upload.part" +} +export const UploadPart = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The upload Part unique identifier, which can be referenced in API endpoints." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the Part was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "upload_id": Schema.String.annotate({ "description": "The ID of the Upload object that this Part was added to." }), + "object": Schema.Literal("upload.part").annotate({ "description": "The object type, which is always `upload.part`." }) +}).annotate({ + "title": "UploadPart", + "description": "The upload Part represents a chunk of bytes we can add to an Upload object.\n" +}) +export type UsageAudioSpeechesResult = { + readonly "object": "organization.usage.audio_speeches.result" + readonly "characters": number + readonly "num_model_requests": number + readonly "project_id"?: string | null + readonly "user_id"?: string | null + readonly "api_key_id"?: string | null + readonly "model"?: string | null +} +export const UsageAudioSpeechesResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.audio_speeches.result"), + "characters": Schema.Number.annotate({ "description": "The number of characters processed." }).check(Schema.isInt()), + "num_model_requests": Schema.Number.annotate({ "description": "The count of requests made to the model." }).check( + Schema.isInt() + ), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "user_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "api_key_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated audio speeches usage details of the specific time bucket." }) +export type UsageAudioTranscriptionsResult = { + readonly "object": "organization.usage.audio_transcriptions.result" + readonly "seconds": number + readonly "num_model_requests": number + readonly "project_id"?: string | null + readonly "user_id"?: string | null + readonly "api_key_id"?: string | null + readonly "model"?: string | null +} +export const UsageAudioTranscriptionsResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.audio_transcriptions.result"), + "seconds": Schema.Number.annotate({ "description": "The number of seconds processed.", "format": "int64" }).check( + Schema.isInt() + ), + "num_model_requests": Schema.Number.annotate({ "description": "The count of requests made to the model." }).check( + Schema.isInt() + ), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "user_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "api_key_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated audio transcriptions usage details of the specific time bucket." }) +export type UsageCodeInterpreterSessionsResult = { + readonly "object": "organization.usage.code_interpreter_sessions.result" + readonly "num_sessions": number + readonly "project_id"?: string | null +} +export const UsageCodeInterpreterSessionsResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.code_interpreter_sessions.result"), + "num_sessions": Schema.Number.annotate({ "description": "The number of code interpreter sessions." }).check( + Schema.isInt() + ), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated code interpreter sessions usage details of the specific time bucket." }) +export type UsageCompletionsResult = { + readonly "object": "organization.usage.completions.result" + readonly "input_tokens": number + readonly "input_cached_tokens"?: number + readonly "output_tokens": number + readonly "input_audio_tokens"?: number + readonly "output_audio_tokens"?: number + readonly "num_model_requests": number + readonly "project_id"?: string | null + readonly "user_id"?: string | null + readonly "api_key_id"?: string | null + readonly "model"?: string | null + readonly "batch"?: boolean | null + readonly "service_tier"?: string | null +} +export const UsageCompletionsResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.completions.result"), + "input_tokens": Schema.Number.annotate({ + "description": + "The aggregated number of text input tokens used, including cached tokens. For customers subscribe to scale tier, this includes scale tier tokens." + }).check(Schema.isInt()), + "input_cached_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The aggregated number of text input tokens that has been cached from previous requests. For customers subscribe to scale tier, this includes scale tier tokens." + }).check(Schema.isInt()) + ), + "output_tokens": Schema.Number.annotate({ + "description": + "The aggregated number of text output tokens used. For customers subscribe to scale tier, this includes scale tier tokens." + }).check(Schema.isInt()), + "input_audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The aggregated number of audio input tokens used, including cached tokens." + }).check(Schema.isInt()) + ), + "output_audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The aggregated number of audio output tokens used." }).check( + Schema.isInt() + ) + ), + "num_model_requests": Schema.Number.annotate({ "description": "The count of requests made to the model." }).check( + Schema.isInt() + ), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "user_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "api_key_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + }), + Schema.Null + ]) + ), + "batch": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": "When `group_by=batch`, this field tells whether the grouped usage result is batch or not." + }), + Schema.Null + ]) + ), + "service_tier": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=service_tier`, this field provides the service tier of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated completions usage details of the specific time bucket." }) +export type UsageEmbeddingsResult = { + readonly "object": "organization.usage.embeddings.result" + readonly "input_tokens": number + readonly "num_model_requests": number + readonly "project_id"?: string | null + readonly "user_id"?: string | null + readonly "api_key_id"?: string | null + readonly "model"?: string | null +} +export const UsageEmbeddingsResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.embeddings.result"), + "input_tokens": Schema.Number.annotate({ "description": "The aggregated number of input tokens used." }).check( + Schema.isInt() + ), + "num_model_requests": Schema.Number.annotate({ "description": "The count of requests made to the model." }).check( + Schema.isInt() + ), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "user_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "api_key_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated embeddings usage details of the specific time bucket." }) +export type UsageFileSearchCallsResult = { + readonly "object": "organization.usage.file_searches.result" + readonly "num_requests": number + readonly "project_id"?: string | null + readonly "user_id"?: string | null + readonly "api_key_id"?: string | null + readonly "vector_store_id"?: string | null +} +export const UsageFileSearchCallsResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.file_searches.result"), + "num_requests": Schema.Number.annotate({ "description": "The count of file search calls." }).check(Schema.isInt()), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "user_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "api_key_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "vector_store_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "When `group_by=vector_store_id`, this field provides the vector store ID of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated file search calls usage details of the specific time bucket." }) +export type UsageImagesResult = { + readonly "object": "organization.usage.images.result" + readonly "images": number + readonly "num_model_requests": number + readonly "source"?: string | null + readonly "size"?: string | null + readonly "project_id"?: string | null + readonly "user_id"?: string | null + readonly "api_key_id"?: string | null + readonly "model"?: string | null +} +export const UsageImagesResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.images.result"), + "images": Schema.Number.annotate({ "description": "The number of images processed." }).check(Schema.isInt()), + "num_model_requests": Schema.Number.annotate({ "description": "The count of requests made to the model." }).check( + Schema.isInt() + ), + "source": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "When `group_by=source`, this field provides the source of the grouped usage result, possible values are `image.generation`, `image.edit`, `image.variation`." + }), + Schema.Null + ]) + ), + "size": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=size`, this field provides the image size of the grouped usage result." + }), + Schema.Null + ]) + ), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "user_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "api_key_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated images usage details of the specific time bucket." }) +export type UsageModerationsResult = { + readonly "object": "organization.usage.moderations.result" + readonly "input_tokens": number + readonly "num_model_requests": number + readonly "project_id"?: string | null + readonly "user_id"?: string | null + readonly "api_key_id"?: string | null + readonly "model"?: string | null +} +export const UsageModerationsResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.moderations.result"), + "input_tokens": Schema.Number.annotate({ "description": "The aggregated number of input tokens used." }).check( + Schema.isInt() + ), + "num_model_requests": Schema.Number.annotate({ "description": "The count of requests made to the model." }).check( + Schema.isInt() + ), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "user_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "api_key_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated moderations usage details of the specific time bucket." }) +export type UsageVectorStoresResult = { + readonly "object": "organization.usage.vector_stores.result" + readonly "usage_bytes": number + readonly "project_id"?: string | null +} +export const UsageVectorStoresResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.vector_stores.result"), + "usage_bytes": Schema.Number.annotate({ "description": "The vector stores usage in bytes." }).check(Schema.isInt()), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated vector stores usage details of the specific time bucket." }) +export type UsageWebSearchCallsResult = { + readonly "object": "organization.usage.web_searches.result" + readonly "num_model_requests": number + readonly "num_requests": number + readonly "project_id"?: string | null + readonly "user_id"?: string | null + readonly "api_key_id"?: string | null + readonly "model"?: string | null + readonly "context_level"?: string | null +} +export const UsageWebSearchCallsResult = Schema.Struct({ + "object": Schema.Literal("organization.usage.web_searches.result"), + "num_model_requests": Schema.Number.annotate({ "description": "The count of model requests." }).check(Schema.isInt()), + "num_requests": Schema.Number.annotate({ "description": "The count of web search calls." }).check(Schema.isInt()), + "project_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=project_id`, this field provides the project ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "user_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=user_id`, this field provides the user ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "api_key_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=api_key_id`, this field provides the API key ID of the grouped usage result." + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "When `group_by=model`, this field provides the model name of the grouped usage result." + }), + Schema.Null + ]) + ), + "context_level": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "When `group_by=context_level`, this field provides the search context size of the grouped usage result." + }), + Schema.Null + ]) + ) +}).annotate({ "description": "The aggregated web search calls usage details of the specific time bucket." }) +export type User = { + readonly "object": "organization.user" + readonly "id": string + readonly "name"?: string | null + readonly "email"?: string | null + readonly "role"?: string | null + readonly "added_at": number + readonly "is_default"?: boolean + readonly "created"?: number + readonly "user"?: { + readonly "object": "user" + readonly "id": string + readonly "email"?: string | null + readonly "name"?: string | null + readonly "picture"?: string | null + readonly "enabled"?: boolean | null + readonly "banned"?: boolean | null + readonly "banned_at"?: number | null + } + readonly "is_service_account"?: boolean + readonly "is_scale_tier_authorized_purchaser"?: boolean | null + readonly "is_scim_managed"?: boolean + readonly "api_key_last_used_at"?: number | null + readonly "technical_level"?: string | null + readonly "developer_persona"?: string | null + readonly "projects"?: { + readonly "object": "list" + readonly "data": ReadonlyArray< + { readonly "id"?: string | null; readonly "name"?: string | null; readonly "role"?: string | null } + > + } | null +} +export const User = Schema.Struct({ + "object": Schema.Literal("organization.user").annotate({ + "description": "The object type, which is always `organization.user`" + }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "name": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The name of the user" }) + ), + "email": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The email address of the user" }) + ), + "role": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "`owner` or `reader`" }) + ), + "added_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the user was added.", + "format": "unixtime" + }).check(Schema.isInt()), + "is_default": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether this is the organization's default user." }) + ), + "created": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the user was created.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "user": Schema.optionalKey( + Schema.Struct({ + "object": Schema.Literal("user"), + "id": Schema.String, + "email": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "name": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "picture": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "enabled": Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + "banned": Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + "banned_at": Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ "format": "unixtime" }).check(Schema.isInt()), Schema.Null]) + ) + }).annotate({ "description": "Nested user details." }) + ), + "is_service_account": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether the user is a service account." }) + ), + "is_scale_tier_authorized_purchaser": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": "Whether the user is an authorized purchaser for Scale Tier." + }) + ), + "is_scim_managed": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether the user is managed through SCIM." }) + ), + "api_key_last_used_at": Schema.optionalKey( + Schema.Union([Schema.Number.annotate({ "format": "unixtime" }).check(Schema.isInt()), Schema.Null]).annotate({ + "description": "The Unix timestamp (in seconds) of the user's last API key usage." + }) + ), + "technical_level": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The technical level metadata for the user." }) + ), + "developer_persona": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "The developer persona metadata for the user." + }) + ), + "projects": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "object": Schema.Literal("list"), + "data": Schema.Array( + Schema.Struct({ + "id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "name": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "role": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])) + }) + ) + }), + Schema.Null + ]).annotate({ "description": "Projects associated with the user, if included." }) + ) +}).annotate({ "description": "Represents an individual `user` within an organization." }) +export type UserDeleteResponse = { + readonly "object": "organization.user.deleted" + readonly "id": string + readonly "deleted": boolean +} +export const UserDeleteResponse = Schema.Struct({ + "object": Schema.Literal("organization.user.deleted"), + "id": Schema.String, + "deleted": Schema.Boolean +}) +export type UserRoleUpdateRequest = { + readonly "role"?: string | null + readonly "role_id"?: string | null + readonly "technical_level"?: string | null + readonly "developer_persona"?: string | null +} +export const UserRoleUpdateRequest = Schema.Struct({ + "role": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "`owner` or `reader`" }) + ), + "role_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "Role ID to assign to the user." }) + ), + "technical_level": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "Technical level metadata." }) + ), + "developer_persona": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "Developer persona metadata." }) + ) +}) +export type VadConfig = { + readonly "type": "server_vad" + readonly "prefix_padding_ms"?: number + readonly "silence_duration_ms"?: number + readonly "threshold"?: number +} +export const VadConfig = Schema.Struct({ + "type": Schema.Literal("server_vad").annotate({ + "description": "Must be set to `server_vad` to enable manual chunking using server side VAD." + }), + "prefix_padding_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Amount of audio to include before the VAD detected speech (in \nmilliseconds).\n" + }).check(Schema.isInt()) + ), + "silence_duration_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Duration of silence to detect speech stop (in milliseconds).\nWith shorter values the model will respond more quickly, \nbut may jump in on short pauses from the user.\n" + }).check(Schema.isInt()) + ), + "threshold": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Sensitivity threshold (0.0 to 1.0) for voice activity detection. A \nhigher threshold will require louder audio to activate the model, and \nthus might perform better in noisy environments.\n" + }).check(Schema.isFinite()) + ) +}) +export type VectorStoreExpirationAfter = { readonly "anchor": "last_active_at"; readonly "days": number } +export const VectorStoreExpirationAfter = Schema.Struct({ + "anchor": Schema.Literal("last_active_at").annotate({ + "description": "Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`." + }), + "days": Schema.Number.annotate({ + "description": "The number of days after the anchor time that the vector store will expire." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(365)) +}).annotate({ "title": "Vector store expiration policy", "description": "The expiration policy for a vector store." }) +export type VectorStoreFileAttributes = {} | null +export const VectorStoreFileAttributes = Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard. Keys are strings\nwith a maximum length of 64 characters. Values are strings with a maximum\nlength of 512 characters, booleans, or numbers.\n" + }).check(Schema.isMaxProperties(16)).check(Schema.isPropertyNames(Schema.String.check(Schema.isMaxLength(64)))), + Schema.Null +]) +export type VectorStoreFileBatchObject = { + readonly "id": string + readonly "object": "vector_store.files_batch" + readonly "created_at": number + readonly "vector_store_id": string + readonly "status": "in_progress" | "completed" | "cancelled" | "failed" + readonly "file_counts": { + readonly "in_progress": number + readonly "completed": number + readonly "failed": number + readonly "cancelled": number + readonly "total": number + } +} +export const VectorStoreFileBatchObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints." }), + "object": Schema.Literal("vector_store.files_batch").annotate({ + "description": "The object type, which is always `vector_store.file_batch`." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the vector store files batch was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "vector_store_id": Schema.String.annotate({ + "description": + "The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to." + }), + "status": Schema.Literals(["in_progress", "completed", "cancelled", "failed"]).annotate({ + "description": + "The status of the vector store files batch, which can be either `in_progress`, `completed`, `cancelled` or `failed`." + }), + "file_counts": Schema.Struct({ + "in_progress": Schema.Number.annotate({ "description": "The number of files that are currently being processed." }) + .check(Schema.isInt()), + "completed": Schema.Number.annotate({ "description": "The number of files that have been processed." }).check( + Schema.isInt() + ), + "failed": Schema.Number.annotate({ "description": "The number of files that have failed to process." }).check( + Schema.isInt() + ), + "cancelled": Schema.Number.annotate({ "description": "The number of files that where cancelled." }).check( + Schema.isInt() + ), + "total": Schema.Number.annotate({ "description": "The total number of files." }).check(Schema.isInt()) + }) +}).annotate({ "title": "Vector store file batch", "description": "A batch of files attached to a vector store." }) +export type VectorStoreFileContentResponse = { + readonly "object": "vector_store.file_content.page" + readonly "data": ReadonlyArray<{ readonly "type"?: string; readonly "text"?: string }> + readonly "has_more": boolean + readonly "next_page": string | null +} +export const VectorStoreFileContentResponse = Schema.Struct({ + "object": Schema.Literal("vector_store.file_content.page").annotate({ + "description": "The object type, which is always `vector_store.file_content.page`" + }), + "data": Schema.Array( + Schema.Struct({ + "type": Schema.optionalKey( + Schema.String.annotate({ "description": "The content type (currently only `\"text\"`)" }) + ), + "text": Schema.optionalKey(Schema.String.annotate({ "description": "The text content" })) + }) + ).annotate({ "description": "Parsed content of the file." }), + "has_more": Schema.Boolean.annotate({ "description": "Indicates if there are more content pages to fetch." }), + "next_page": Schema.Union([ + Schema.String.annotate({ "description": "The token for the next page, if any." }), + Schema.Null + ]) +}).annotate({ "description": "Represents the parsed content of a vector store file." }) +export type VectorStoreSearchResultContentObject = { readonly "type": "text"; readonly "text": string } +export const VectorStoreSearchResultContentObject = Schema.Struct({ + "type": Schema.Literal("text").annotate({ "description": "The type of content." }), + "text": Schema.String.annotate({ "description": "The text content returned from search." }) +}) +export type Verbosity = "low" | "medium" | "high" | null +export const Verbosity = Schema.Union([ + Schema.Literals(["low", "medium", "high"]).annotate({ + "description": + "Constrains the verbosity of the model's response. Lower values will result in\nmore concise responses, while higher values will result in more verbose responses.\nCurrently supported values are `low`, `medium`, and `high`.\n" + }), + Schema.Null +]) +export type VoiceConsentDeletedResource = { + readonly "id": string + readonly "object": "audio.voice_consent" + readonly "deleted": boolean +} +export const VoiceConsentDeletedResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The consent recording identifier." }), + "object": Schema.Literal("audio.voice_consent"), + "deleted": Schema.Boolean +}) +export type VoiceConsentResource = { + readonly "object": "audio.voice_consent" + readonly "id": string + readonly "name": string + readonly "language": string + readonly "created_at": number +} +export const VoiceConsentResource = Schema.Struct({ + "object": Schema.Literal("audio.voice_consent").annotate({ + "description": "The object type, which is always `audio.voice_consent`." + }), + "id": Schema.String.annotate({ "description": "The consent recording identifier." }), + "name": Schema.String.annotate({ "description": "The label provided when the consent recording was uploaded." }), + "language": Schema.String.annotate({ + "description": "The BCP 47 language tag for the consent phrase (for example, `en-US`)." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the consent recording was created.", + "format": "unixtime" + }).check(Schema.isInt()) +}).annotate({ + "title": "Voice consent", + "description": "A consent recording used to authorize creation of a custom voice." +}) +export type VoiceIdsShared = + | string + | "alloy" + | "ash" + | "ballad" + | "coral" + | "echo" + | "sage" + | "shimmer" + | "verse" + | "marin" + | "cedar" +export const VoiceIdsShared = Schema.Union([ + Schema.String, + Schema.Literals(["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse", "marin", "cedar"]) +]) +export type VoiceResource = { + readonly "object": "audio.voice" + readonly "id": string + readonly "name": string + readonly "created_at": number +} +export const VoiceResource = Schema.Struct({ + "object": Schema.Literal("audio.voice").annotate({ + "description": "The object type, which is always `audio.voice`." + }), + "id": Schema.String.annotate({ "description": "The voice identifier, which can be referenced in API endpoints." }), + "name": Schema.String.annotate({ "description": "The name of the voice." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the voice was created.", + "format": "unixtime" + }).check(Schema.isInt()) +}).annotate({ "title": "Voice", "description": "A custom voice that can be used for audio output." }) +export type WebSearchApproximateLocation = { + readonly "type"?: "approximate" + readonly "country"?: string | null + readonly "region"?: string | null + readonly "city"?: string | null + readonly "timezone"?: string | null +} | null +export const WebSearchApproximateLocation = Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("approximate").annotate({ + "description": "The type of location approximation. Always `approximate`." + }) + ), + "country": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`." + }), + Schema.Null + ]) + ), + "region": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "Free text input for the region of the user, e.g. `California`." }), + Schema.Null + ]) + ), + "city": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "Free text input for the city of the user, e.g. `San Francisco`." }), + Schema.Null + ]) + ), + "timezone": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`." + }), + Schema.Null + ]) + ) + }).annotate({ "title": "Web search approximate location", "description": "The approximate location of the user.\n" }), + Schema.Null +]) +export type WebSearchContextSize = "low" | "medium" | "high" +export const WebSearchContextSize = Schema.Literals(["low", "medium", "high"]).annotate({ + "description": + "High level guidance for the amount of context window space to use for the \nsearch. One of `low`, `medium`, or `high`. `medium` is the default.\n" +}) +export type WebSearchLocation = { + readonly "country"?: string + readonly "region"?: string + readonly "city"?: string + readonly "timezone"?: string +} +export const WebSearchLocation = Schema.Struct({ + "country": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The two-letter \n[ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user,\ne.g. `US`.\n" + }) + ), + "region": Schema.optionalKey( + Schema.String.annotate({ "description": "Free text input for the region of the user, e.g. `California`.\n" }) + ), + "city": Schema.optionalKey( + Schema.String.annotate({ "description": "Free text input for the city of the user, e.g. `San Francisco`.\n" }) + ), + "timezone": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The [IANA timezone](https://timeapi.io/documentation/iana-timezones) \nof the user, e.g. `America/Los_Angeles`.\n" + }) + ) +}).annotate({ "title": "Web search location", "description": "Approximate location parameters for the search." }) +export type WebSearchToolCall = { + readonly "id": string + readonly "type": "web_search_call" + readonly "status": "in_progress" | "searching" | "completed" | "failed" + readonly "action": + | { + readonly "type": "search" + readonly "query"?: string + readonly "queries"?: ReadonlyArray + readonly "sources"?: ReadonlyArray<{ readonly "type": "url"; readonly "url": string }> + } + | { readonly "type": "open_page"; readonly "url"?: string | null } + | { readonly "type": "find_in_page"; readonly "url": string; readonly "pattern": string } +} +export const WebSearchToolCall = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the web search tool call.\n" }), + "type": Schema.Literal("web_search_call").annotate({ + "description": "The type of the web search tool call. Always `web_search_call`.\n" + }), + "status": Schema.Literals(["in_progress", "searching", "completed", "failed"]).annotate({ + "description": "The status of the web search tool call.\n" + }), + "action": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("search").annotate({ "description": "The action type.\n" }), + "query": Schema.optionalKey(Schema.String.annotate({ "description": "[DEPRECATED] The search query.\n" })), + "queries": Schema.optionalKey( + Schema.Array(Schema.String.annotate({ "description": "A search query.\n" })).annotate({ + "title": "Search queries", + "description": "The search queries.\n" + }) + ), + "sources": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "type": Schema.Literal("url").annotate({ "description": "The type of source. Always `url`.\n" }), + "url": Schema.String.annotate({ "description": "The URL of the source.\n", "format": "uri" }) + }).annotate({ "title": "Web search source", "description": "A source used in the search.\n" }) + ).annotate({ "title": "Web search sources", "description": "The sources used in the search.\n" }) + ) + }).annotate({ + "title": "Search action", + "description": + "An object describing the specific action taken in this web search call.\nIncludes details on how the model used the web (search, open_page, find_in_page).\n" + }), + Schema.Struct({ + "type": Schema.Literal("open_page").annotate({ "description": "The action type. Always `open_page`.\n" }), + "url": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "format": "uri" }), Schema.Null]).annotate({ + "description": "The URL opened by the model.\n" + }) + ) + }).annotate({ + "title": "Open page action", + "description": + "An object describing the specific action taken in this web search call.\nIncludes details on how the model used the web (search, open_page, find_in_page).\n" + }), + Schema.Struct({ + "type": Schema.Literal("find_in_page").annotate({ "description": "The action type.\n" }), + "url": Schema.String.annotate({ + "description": "The URL of the page searched for the pattern.\n", + "format": "uri" + }), + "pattern": Schema.String.annotate({ "description": "The pattern or text to search for within the page.\n" }) + }).annotate({ + "title": "Find action", + "description": + "An object describing the specific action taken in this web search call.\nIncludes details on how the model used the web (search, open_page, find_in_page).\n" + }) + ], { mode: "oneOf" }) +}).annotate({ + "title": "Web search tool call", + "description": + "The results of a web search tool call. See the\n[web search guide](/docs/guides/tools-web-search) for more information.\n" +}) +export type SkillReferenceParam = { + readonly "type": "skill_reference" + readonly "skill_id": string + readonly "version"?: string +} +export const SkillReferenceParam = Schema.Struct({ + "type": Schema.Literal("skill_reference").annotate({ + "description": "References a skill created with the /v1/skills endpoint." + }), + "skill_id": Schema.String.annotate({ "description": "The ID of the referenced skill." }).check(Schema.isMinLength(1)) + .check(Schema.isMaxLength(64)), + "version": Schema.optionalKey( + Schema.String.annotate({ + "description": "Optional skill version. Use a positive integer or 'latest'. Omit for default." + }) + ) +}) +export type InlineSkillParam = { + readonly "type": "inline" + readonly "name": string + readonly "description": string + readonly "source": { readonly "type": "base64"; readonly "media_type": "application/zip"; readonly "data": string } +} +export const InlineSkillParam = Schema.Struct({ + "type": Schema.Literal("inline").annotate({ "description": "Defines an inline skill for this request." }), + "name": Schema.String.annotate({ "description": "The name of the skill." }), + "description": Schema.String.annotate({ "description": "The description of the skill." }), + "source": Schema.Struct({ + "type": Schema.Literal("base64").annotate({ + "description": "The type of the inline skill source. Must be `base64`." + }), + "media_type": Schema.Literal("application/zip").annotate({ + "description": "The media type of the inline skill payload. Must be `application/zip`." + }), + "data": Schema.String.annotate({ "description": "Base64-encoded skill zip bundle." }).check(Schema.isMinLength(1)) + .check(Schema.isMaxLength(70254592)) + }).annotate({ "description": "Inline skill payload" }) +}) +export type ContainerNetworkPolicyDisabledParam = { readonly "type": "disabled" } +export const ContainerNetworkPolicyDisabledParam = Schema.Struct({ + "type": Schema.Literal("disabled").annotate({ "description": "Disable outbound network access. Always `disabled`." }) +}) +export type ContainerNetworkPolicyDomainSecretParam = { + readonly "domain": string + readonly "name": string + readonly "value": string +} +export const ContainerNetworkPolicyDomainSecretParam = Schema.Struct({ + "domain": Schema.String.annotate({ "description": "The domain associated with the secret." }).check( + Schema.isMinLength(1) + ), + "name": Schema.String.annotate({ "description": "The name of the secret to inject for the domain." }).check( + Schema.isMinLength(1) + ), + "value": Schema.String.annotate({ "description": "The secret value to inject for the domain." }).check( + Schema.isMinLength(1) + ).check(Schema.isMaxLength(10485760)) +}) +export type IncludeEnum = + | "file_search_call.results" + | "web_search_call.results" + | "web_search_call.action.sources" + | "message.input_image.image_url" + | "computer_call_output.output.image_url" + | "code_interpreter_call.outputs" + | "reasoning.encrypted_content" + | "message.output_text.logprobs" +export const IncludeEnum = Schema.Literals([ + "file_search_call.results", + "web_search_call.results", + "web_search_call.action.sources", + "message.input_image.image_url", + "computer_call_output.output.image_url", + "code_interpreter_call.outputs", + "reasoning.encrypted_content", + "message.output_text.logprobs" +]).annotate({ + "description": + "Specify additional output data to include in the model response. Currently supported values are:\n- `web_search_call.results`: Include the search results of the web search tool call.\n- `web_search_call.action.sources`: Include the sources of the web search tool call.\n- `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items.\n- `computer_call_output.output.image_url`: Include image urls from the computer call output.\n- `file_search_call.results`: Include the search results of the file search tool call.\n- `message.input_image.image_url`: Include image urls from the input message.\n- `message.output_text.logprobs`: Include logprobs with assistant messages.\n- `reasoning.encrypted_content`: Includes an encrypted version of reasoning tokens in reasoning item outputs. This enables reasoning items to be used in multi-turn conversations when using the Responses API statelessly (like when the `store` parameter is set to `false`, or when an organization is enrolled in the zero data retention program)." +}) +export type InputTextContent = { readonly "type": "input_text"; readonly "text": string } +export const InputTextContent = Schema.Struct({ + "type": Schema.Literal("input_text").annotate({ "description": "The type of the input item. Always `input_text`." }), + "text": Schema.String.annotate({ "description": "The text input to the model." }) +}).annotate({ "title": "Input text", "description": "A text input to the model." }) +export type FileCitationBody = { + readonly "type": "file_citation" + readonly "file_id": string + readonly "index": number + readonly "filename": string +} +export const FileCitationBody = Schema.Struct({ + "type": Schema.Literal("file_citation").annotate({ + "description": "The type of the file citation. Always `file_citation`." + }), + "file_id": Schema.String.annotate({ "description": "The ID of the file." }), + "index": Schema.Number.annotate({ "description": "The index of the file in the list of files." }).check( + Schema.isInt() + ), + "filename": Schema.String.annotate({ "description": "The filename of the file cited." }) +}).annotate({ "title": "File citation", "description": "A citation to a file." }) +export type UrlCitationBody = { + readonly "type": "url_citation" + readonly "url": string + readonly "start_index": number + readonly "end_index": number + readonly "title": string +} +export const UrlCitationBody = Schema.Struct({ + "type": Schema.Literal("url_citation").annotate({ + "description": "The type of the URL citation. Always `url_citation`." + }), + "url": Schema.String.annotate({ "description": "The URL of the web resource.", "format": "uri" }), + "start_index": Schema.Number.annotate({ + "description": "The index of the first character of the URL citation in the message." + }).check(Schema.isInt()), + "end_index": Schema.Number.annotate({ + "description": "The index of the last character of the URL citation in the message." + }).check(Schema.isInt()), + "title": Schema.String.annotate({ "description": "The title of the web resource." }) +}).annotate({ + "title": "URL citation", + "description": "A citation for a web resource used to generate a model response." +}) +export type ContainerFileCitationBody = { + readonly "type": "container_file_citation" + readonly "container_id": string + readonly "file_id": string + readonly "start_index": number + readonly "end_index": number + readonly "filename": string +} +export const ContainerFileCitationBody = Schema.Struct({ + "type": Schema.Literal("container_file_citation").annotate({ + "description": "The type of the container file citation. Always `container_file_citation`." + }), + "container_id": Schema.String.annotate({ "description": "The ID of the container file." }), + "file_id": Schema.String.annotate({ "description": "The ID of the file." }), + "start_index": Schema.Number.annotate({ + "description": "The index of the first character of the container file citation in the message." + }).check(Schema.isInt()), + "end_index": Schema.Number.annotate({ + "description": "The index of the last character of the container file citation in the message." + }).check(Schema.isInt()), + "filename": Schema.String.annotate({ "description": "The filename of the container file cited." }) +}).annotate({ + "title": "Container file citation", + "description": "A citation for a container file used to generate a model response." +}) +export type TopLogProb = { + readonly "token": string + readonly "logprob": number + readonly "bytes": ReadonlyArray +} +export const TopLogProb = Schema.Struct({ + "token": Schema.String, + "logprob": Schema.Number.check(Schema.isFinite()), + "bytes": Schema.Array(Schema.Number.check(Schema.isInt())) +}).annotate({ "title": "Top log probability", "description": "The top log probability of a token." }) +export type TextContent = { readonly "type": "text"; readonly "text": string } +export const TextContent = Schema.Struct({ "type": Schema.Literal("text"), "text": Schema.String }).annotate({ + "title": "Text Content", + "description": "A text content." +}) +export type SummaryTextContent = { readonly "type": "summary_text"; readonly "text": string } +export const SummaryTextContent = Schema.Struct({ + "type": Schema.Literal("summary_text").annotate({ "description": "The type of the object. Always `summary_text`." }), + "text": Schema.String.annotate({ "description": "A summary of the reasoning output from the model so far." }) +}).annotate({ "title": "Summary text", "description": "A summary text from the model." }) +export type ReasoningTextContent = { readonly "type": "reasoning_text"; readonly "text": string } +export const ReasoningTextContent = Schema.Struct({ + "type": Schema.Literal("reasoning_text").annotate({ + "description": "The type of the reasoning text. Always `reasoning_text`." + }), + "text": Schema.String.annotate({ "description": "The reasoning text from the model." }) +}).annotate({ "title": "Reasoning text", "description": "Reasoning text from the model." }) +export type RefusalContent = { readonly "type": "refusal"; readonly "refusal": string } +export const RefusalContent = Schema.Struct({ + "type": Schema.Literal("refusal").annotate({ "description": "The type of the refusal. Always `refusal`." }), + "refusal": Schema.String.annotate({ "description": "The refusal explanation from the model." }) +}).annotate({ "title": "Refusal", "description": "A refusal from the model." }) +export type InputImageContent = { + readonly "type": "input_image" + readonly "image_url"?: string | null + readonly "file_id"?: string | null + readonly "detail": "low" | "high" | "auto" | "original" +} +export const InputImageContent = Schema.Struct({ + "type": Schema.Literal("input_image").annotate({ + "description": "The type of the input item. Always `input_image`." + }), + "image_url": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL.", + "format": "uri" + }), + Schema.Null + ]) + ), + "file_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The ID of the file to be sent to the model." }), + Schema.Null + ]) + ), + "detail": Schema.Literals(["low", "high", "auto", "original"]).annotate({ + "description": + "The detail level of the image to be sent to the model. One of `high`, `low`, `auto`, or `original`. Defaults to `auto`." + }) +}).annotate({ + "title": "Input image", + "description": "An image input to the model. Learn about [image inputs](/docs/guides/vision)." +}) +export type ComputerScreenshotContent = { + readonly "type": "computer_screenshot" + readonly "image_url": string | null + readonly "file_id": string | null + readonly "detail": "low" | "high" | "auto" | "original" +} +export const ComputerScreenshotContent = Schema.Struct({ + "type": Schema.Literal("computer_screenshot").annotate({ + "description": + "Specifies the event type. For a computer screenshot, this property is always set to `computer_screenshot`." + }), + "image_url": Schema.Union([ + Schema.String.annotate({ "description": "The URL of the screenshot image.", "format": "uri" }), + Schema.Null + ]), + "file_id": Schema.Union([ + Schema.String.annotate({ "description": "The identifier of an uploaded file that contains the screenshot." }), + Schema.Null + ]), + "detail": Schema.Literals(["low", "high", "auto", "original"]).annotate({ + "description": + "The detail level of the screenshot image to be sent to the model. One of `high`, `low`, `auto`, or `original`. Defaults to `auto`." + }) +}).annotate({ "title": "Computer screenshot", "description": "A screenshot of a computer." }) +export type InputFileContent = { + readonly "type": "input_file" + readonly "file_id"?: string | null + readonly "filename"?: string + readonly "file_data"?: string + readonly "file_url"?: string + readonly "detail"?: "low" | "high" +} +export const InputFileContent = Schema.Struct({ + "type": Schema.Literal("input_file").annotate({ "description": "The type of the input item. Always `input_file`." }), + "file_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The ID of the file to be sent to the model." }), + Schema.Null + ]) + ), + "filename": Schema.optionalKey( + Schema.String.annotate({ "description": "The name of the file to be sent to the model." }) + ), + "file_data": Schema.optionalKey( + Schema.String.annotate({ "description": "The content of the file to be sent to the model.\n" }) + ), + "file_url": Schema.optionalKey( + Schema.String.annotate({ "description": "The URL of the file to be sent to the model.", "format": "uri" }) + ), + "detail": Schema.optionalKey( + Schema.Literals(["low", "high"]).annotate({ + "description": + "The detail level of the file to be sent to the model. Use `low` for the default rendering behavior, or `high` to render the file at higher quality. Defaults to `low`." + }) + ) +}).annotate({ "title": "Input file", "description": "A file input to the model." }) +export type ClickParam = { + readonly "type": "click" + readonly "button": "left" | "right" | "wheel" | "back" | "forward" + readonly "x": number + readonly "y": number + readonly "keys"?: ReadonlyArray | null +} +export const ClickParam = Schema.Struct({ + "type": Schema.Literal("click").annotate({ + "description": "Specifies the event type. For a click action, this property is always `click`." + }), + "button": Schema.Literals(["left", "right", "wheel", "back", "forward"]).annotate({ + "description": + "Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`." + }), + "x": Schema.Number.annotate({ "description": "The x-coordinate where the click occurred." }).check(Schema.isInt()), + "y": Schema.Number.annotate({ "description": "The y-coordinate where the click occurred." }).check(Schema.isInt()), + "keys": Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ "description": "The keys being held while clicking." }), + Schema.Null + ]) + ) +}).annotate({ "title": "Click", "description": "A click action." }) +export type DoubleClickAction = { + readonly "type": "double_click" + readonly "x": number + readonly "y": number + readonly "keys": ReadonlyArray | null +} +export const DoubleClickAction = Schema.Struct({ + "type": Schema.Literal("double_click").annotate({ + "description": "Specifies the event type. For a double click action, this property is always set to `double_click`." + }), + "x": Schema.Number.annotate({ "description": "The x-coordinate where the double click occurred." }).check( + Schema.isInt() + ), + "y": Schema.Number.annotate({ "description": "The y-coordinate where the double click occurred." }).check( + Schema.isInt() + ), + "keys": Schema.Union([ + Schema.Array(Schema.String).annotate({ "description": "The keys being held while double-clicking." }), + Schema.Null + ]) +}).annotate({ "title": "DoubleClick", "description": "A double click action." }) +export type CoordParam = { readonly "x": number; readonly "y": number } +export const CoordParam = Schema.Struct({ + "x": Schema.Number.annotate({ "description": "The x-coordinate." }).check(Schema.isInt()), + "y": Schema.Number.annotate({ "description": "The y-coordinate." }).check(Schema.isInt()) +}).annotate({ "title": "Coordinate", "description": "An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`." }) +export type KeyPressAction = { readonly "type": "keypress"; readonly "keys": ReadonlyArray } +export const KeyPressAction = Schema.Struct({ + "type": Schema.Literal("keypress").annotate({ + "description": "Specifies the event type. For a keypress action, this property is always set to `keypress`." + }), + "keys": Schema.Array( + Schema.String.annotate({ "description": "One of the keys the model is requesting to be pressed." }) + ).annotate({ + "description": + "The combination of keys the model is requesting to be pressed. This is an array of strings, each representing a key." + }) +}).annotate({ "title": "KeyPress", "description": "A collection of keypresses the model would like to perform." }) +export type MoveParam = { + readonly "type": "move" + readonly "x": number + readonly "y": number + readonly "keys"?: ReadonlyArray | null +} +export const MoveParam = Schema.Struct({ + "type": Schema.Literal("move").annotate({ + "description": "Specifies the event type. For a move action, this property is always set to `move`." + }), + "x": Schema.Number.annotate({ "description": "The x-coordinate to move to." }).check(Schema.isInt()), + "y": Schema.Number.annotate({ "description": "The y-coordinate to move to." }).check(Schema.isInt()), + "keys": Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ "description": "The keys being held while moving the mouse." }), + Schema.Null + ]) + ) +}).annotate({ "title": "Move", "description": "A mouse move action." }) +export type ScreenshotParam = { readonly "type": "screenshot" } +export const ScreenshotParam = Schema.Struct({ + "type": Schema.Literal("screenshot").annotate({ + "description": "Specifies the event type. For a screenshot action, this property is always set to `screenshot`." + }) +}).annotate({ "title": "Screenshot", "description": "A screenshot action." }) +export type ScrollParam = { + readonly "type": "scroll" + readonly "x": number + readonly "y": number + readonly "scroll_x": number + readonly "scroll_y": number + readonly "keys"?: ReadonlyArray | null +} +export const ScrollParam = Schema.Struct({ + "type": Schema.Literal("scroll").annotate({ + "description": "Specifies the event type. For a scroll action, this property is always set to `scroll`." + }), + "x": Schema.Number.annotate({ "description": "The x-coordinate where the scroll occurred." }).check(Schema.isInt()), + "y": Schema.Number.annotate({ "description": "The y-coordinate where the scroll occurred." }).check(Schema.isInt()), + "scroll_x": Schema.Number.annotate({ "description": "The horizontal scroll distance." }).check(Schema.isInt()), + "scroll_y": Schema.Number.annotate({ "description": "The vertical scroll distance." }).check(Schema.isInt()), + "keys": Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ "description": "The keys being held while scrolling." }), + Schema.Null + ]) + ) +}).annotate({ "title": "Scroll", "description": "A scroll action." }) +export type TypeParam = { readonly "type": "type"; readonly "text": string } +export const TypeParam = Schema.Struct({ + "type": Schema.Literal("type").annotate({ + "description": "Specifies the event type. For a type action, this property is always set to `type`." + }), + "text": Schema.String.annotate({ "description": "The text to type." }) +}).annotate({ "title": "Type", "description": "An action to type in text." }) +export type WaitParam = { readonly "type": "wait" } +export const WaitParam = Schema.Struct({ + "type": Schema.Literal("wait").annotate({ + "description": "Specifies the event type. For a wait action, this property is always set to `wait`." + }) +}).annotate({ "title": "Wait", "description": "A wait action." }) +export type ComputerCallSafetyCheckParam = { + readonly "id": string + readonly "code"?: string | null + readonly "message"?: string | null +} +export const ComputerCallSafetyCheckParam = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The ID of the pending safety check." }), + "code": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "The type of the pending safety check." }), Schema.Null]) + ), + "message": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "Details about the pending safety check." }), Schema.Null]) + ) +}).annotate({ "description": "A pending safety check for the computer call." }) +export type ToolSearchCall = { + readonly "type": "tool_search_call" + readonly "id": string + readonly "call_id": string | null + readonly "execution": "server" | "client" + readonly "arguments": unknown + readonly "status": "in_progress" | "completed" | "incomplete" + readonly "created_by"?: string +} +export const ToolSearchCall = Schema.Struct({ + "type": Schema.Literal("tool_search_call").annotate({ + "description": "The type of the item. Always `tool_search_call`." + }), + "id": Schema.String.annotate({ "description": "The unique ID of the tool search call item." }), + "call_id": Schema.Union([ + Schema.String.annotate({ "description": "The unique ID of the tool search call generated by the model." }), + Schema.Null + ]), + "execution": Schema.Literals(["server", "client"]).annotate({ + "description": "Whether tool search was executed by the server or by the client." + }), + "arguments": Schema.Unknown.annotate({ "description": "Arguments used for the tool search call." }), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the tool search call item that was recorded." + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item." }) + ) +}) +export type FunctionTool = { + readonly "type": "function" + readonly "name": string + readonly "description"?: string | null + readonly "parameters": {} | null + readonly "strict": boolean | null + readonly "defer_loading"?: boolean +} +export const FunctionTool = Schema.Struct({ + "type": Schema.Literal("function").annotate({ "description": "The type of the function tool. Always `function`." }), + "name": Schema.String.annotate({ "description": "The name of the function to call." }), + "description": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "A description of the function. Used by the model to determine whether or not to call the function." + }), + Schema.Null + ]) + ), + "parameters": Schema.Union([ + Schema.Struct({}).annotate({ "description": "A JSON schema object describing the parameters of the function." }), + Schema.Null + ]), + "strict": Schema.Union([ + Schema.Boolean.annotate({ "description": "Whether to enforce strict parameter validation. Default `true`." }), + Schema.Null + ]), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether this function is deferred and loaded via tool search." }) + ) +}).annotate({ + "title": "Function", + "description": + "Defines a function in your own code the model can choose to call. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling)." +}) +export type ComputerTool = { readonly "type": "computer" } +export const ComputerTool = Schema.Struct({ + "type": Schema.Literal("computer").annotate({ "description": "The type of the computer tool. Always `computer`." }) +}).annotate({ + "title": "Computer", + "description": + "A tool that controls a virtual computer. Learn more about the [computer tool](https://platform.openai.com/docs/guides/tools-computer-use)." +}) +export type ComputerUsePreviewTool = { + readonly "type": "computer_use_preview" + readonly "environment": "windows" | "mac" | "linux" | "ubuntu" | "browser" + readonly "display_width": number + readonly "display_height": number +} +export const ComputerUsePreviewTool = Schema.Struct({ + "type": Schema.Literal("computer_use_preview").annotate({ + "description": "The type of the computer use tool. Always `computer_use_preview`." + }), + "environment": Schema.Literals(["windows", "mac", "linux", "ubuntu", "browser"]).annotate({ + "description": "The type of computer environment to control." + }), + "display_width": Schema.Number.annotate({ "description": "The width of the computer display." }).check( + Schema.isInt() + ), + "display_height": Schema.Number.annotate({ "description": "The height of the computer display." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "Computer use preview", + "description": + "A tool that controls a virtual computer. Learn more about the [computer tool](https://platform.openai.com/docs/guides/tools-computer-use)." +}) +export type InputFidelity = "high" | "low" +export const InputFidelity = Schema.Literals(["high", "low"]).annotate({ + "description": + "Control how much effort the model will exert to match the style and features, especially facial features, of input images. This parameter is only supported for `gpt-image-1` and `gpt-image-1.5` and later models, unsupported for `gpt-image-1-mini`. Supports `high` and `low`. Defaults to `low`." +}) +export type LocalShellToolParam = { readonly "type": "local_shell" } +export const LocalShellToolParam = Schema.Struct({ + "type": Schema.Literal("local_shell").annotate({ + "description": "The type of the local shell tool. Always `local_shell`." + }) +}).annotate({ + "title": "Local shell tool", + "description": "A tool that allows the model to execute shell commands in a local environment." +}) +export type LocalSkillParam = { readonly "name": string; readonly "description": string; readonly "path": string } +export const LocalSkillParam = Schema.Struct({ + "name": Schema.String.annotate({ "description": "The name of the skill." }), + "description": Schema.String.annotate({ "description": "The description of the skill." }), + "path": Schema.String.annotate({ "description": "The path to the directory containing the skill." }) +}) +export type ContainerReferenceParam = { readonly "type": "container_reference"; readonly "container_id": string } +export const ContainerReferenceParam = Schema.Struct({ + "type": Schema.Literal("container_reference").annotate({ + "description": "References a container created with the /v1/containers endpoint" + }), + "container_id": Schema.String.annotate({ "description": "The ID of the referenced container." }) +}) +export type CustomTextFormatParam = { readonly "type": "text" } +export const CustomTextFormatParam = Schema.Struct({ + "type": Schema.Literal("text").annotate({ "description": "Unconstrained text format. Always `text`." }) +}).annotate({ "title": "Text format", "description": "Unconstrained free-form text." }) +export type CustomGrammarFormatParam = { + readonly "type": "grammar" + readonly "syntax": "lark" | "regex" + readonly "definition": string +} +export const CustomGrammarFormatParam = Schema.Struct({ + "type": Schema.Literal("grammar").annotate({ "description": "Grammar format. Always `grammar`." }), + "syntax": Schema.Literals(["lark", "regex"]).annotate({ + "description": "The syntax of the grammar definition. One of `lark` or `regex`." + }), + "definition": Schema.String.annotate({ "description": "The grammar definition." }) +}).annotate({ "title": "Grammar format", "description": "A grammar defined by the user." }) +export type EmptyModelParam = {} +export const EmptyModelParam = Schema.Struct({}) +export type ToolSearchToolParam = { + readonly "type": "tool_search" + readonly "execution"?: "server" | "client" + readonly "description"?: string | null + readonly "parameters"?: {} | null +} +export const ToolSearchToolParam = Schema.Struct({ + "type": Schema.Literal("tool_search").annotate({ "description": "The type of the tool. Always `tool_search`." }), + "execution": Schema.optionalKey( + Schema.Literals(["server", "client"]).annotate({ + "description": "Whether tool search is executed by the server or by the client." + }) + ), + "description": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "Description shown to the model for a client-executed tool search tool." + }), + Schema.Null + ]) + ), + "parameters": Schema.optionalKey( + Schema.Union([ + Schema.Struct({}).annotate({ "description": "Parameter schema for a client-executed tool search tool." }), + Schema.Null + ]) + ) +}).annotate({ + "title": "Tool search tool", + "description": "Hosted or BYOT tool search configuration for deferred tools." +}) +export type SearchContentType = "text" | "image" +export const SearchContentType = Schema.Literals(["text", "image"]) +export type ApplyPatchToolParam = { readonly "type": "apply_patch" } +export const ApplyPatchToolParam = Schema.Struct({ + "type": Schema.Literal("apply_patch").annotate({ "description": "The type of the tool. Always `apply_patch`." }) +}).annotate({ + "title": "Apply patch tool", + "description": "Allows the assistant to create, delete, or update files using unified diffs." +}) +export type CompactionBody = { + readonly "type": "compaction" + readonly "id": string + readonly "encrypted_content": string + readonly "created_by"?: string +} +export const CompactionBody = Schema.Struct({ + "type": Schema.Literal("compaction").annotate({ "description": "The type of the item. Always `compaction`." }), + "id": Schema.String.annotate({ "description": "The unique ID of the compaction item." }), + "encrypted_content": Schema.String.annotate({ + "description": "The encrypted content that was produced by compaction." + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item." }) + ) +}).annotate({ + "title": "Compaction item", + "description": + "A compaction item generated by the [`v1/responses/compact` API](/docs/api-reference/responses/compact)." +}) +export type CodeInterpreterOutputLogs = { readonly "type": "logs"; readonly "logs": string } +export const CodeInterpreterOutputLogs = Schema.Struct({ + "type": Schema.Literal("logs").annotate({ "description": "The type of the output. Always `logs`." }), + "logs": Schema.String.annotate({ "description": "The logs output from the code interpreter." }) +}).annotate({ "title": "Code interpreter output logs", "description": "The logs output from the code interpreter." }) +export type CodeInterpreterOutputImage = { readonly "type": "image"; readonly "url": string } +export const CodeInterpreterOutputImage = Schema.Struct({ + "type": Schema.Literal("image").annotate({ "description": "The type of the output. Always `image`." }), + "url": Schema.String.annotate({ + "description": "The URL of the image output from the code interpreter.", + "format": "uri" + }) +}).annotate({ "title": "Code interpreter output image", "description": "The image output from the code interpreter." }) +export type LocalShellExecAction = { + readonly "type": "exec" + readonly "command": ReadonlyArray + readonly "timeout_ms"?: number | null + readonly "working_directory"?: string | null + readonly "env": {} + readonly "user"?: string | null +} +export const LocalShellExecAction = Schema.Struct({ + "type": Schema.Literal("exec").annotate({ "description": "The type of the local shell action. Always `exec`." }), + "command": Schema.Array(Schema.String).annotate({ "description": "The command to run." }), + "timeout_ms": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "Optional timeout in milliseconds for the command." }).check( + Schema.isInt() + ), + Schema.Null + ]) + ), + "working_directory": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "Optional working directory to run the command in." }), + Schema.Null + ]) + ), + "env": Schema.Struct({}).annotate({ "description": "Environment variables to set for the command." }), + "user": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "Optional user to run the command as." }), Schema.Null]) + ) +}).annotate({ "title": "Local shell exec action", "description": "Execute a shell command on the server." }) +export type LocalEnvironmentResource = { readonly "type": "local" } +export const LocalEnvironmentResource = Schema.Struct({ + "type": Schema.Literal("local").annotate({ "description": "The environment type. Always `local`." }) +}).annotate({ + "title": "Local Environment", + "description": "Represents the use of a local environment to perform shell actions." +}) +export type ContainerReferenceResource = { readonly "type": "container_reference"; readonly "container_id": string } +export const ContainerReferenceResource = Schema.Struct({ + "type": Schema.Literal("container_reference").annotate({ + "description": "The environment type. Always `container_reference`." + }), + "container_id": Schema.String +}).annotate({ "title": "Container Reference", "description": "Represents a container created with /v1/containers." }) +export type FunctionShellCallOutputTimeoutOutcome = { readonly "type": "timeout" } +export const FunctionShellCallOutputTimeoutOutcome = Schema.Struct({ + "type": Schema.Literal("timeout").annotate({ "description": "The outcome type. Always `timeout`." }) +}).annotate({ + "title": "Shell call timeout outcome", + "description": "Indicates that the shell call exceeded its configured time limit." +}) +export type FunctionShellCallOutputExitOutcome = { readonly "type": "exit"; readonly "exit_code": number } +export const FunctionShellCallOutputExitOutcome = Schema.Struct({ + "type": Schema.Literal("exit").annotate({ "description": "The outcome type. Always `exit`." }), + "exit_code": Schema.Number.annotate({ "description": "Exit code from the shell process." }).check(Schema.isInt()) +}).annotate({ + "title": "Shell call exit outcome", + "description": "Indicates that the shell commands finished and returned an exit code." +}) +export type ApplyPatchCreateFileOperation = { + readonly "type": "create_file" + readonly "path": string + readonly "diff": string +} +export const ApplyPatchCreateFileOperation = Schema.Struct({ + "type": Schema.Literal("create_file").annotate({ "description": "Create a new file with the provided diff." }), + "path": Schema.String.annotate({ "description": "Path of the file to create." }), + "diff": Schema.String.annotate({ "description": "Diff to apply." }) +}).annotate({ + "title": "Apply patch create file operation", + "description": "Instruction describing how to create a file via the apply_patch tool." +}) +export type ApplyPatchDeleteFileOperation = { readonly "type": "delete_file"; readonly "path": string } +export const ApplyPatchDeleteFileOperation = Schema.Struct({ + "type": Schema.Literal("delete_file").annotate({ "description": "Delete the specified file." }), + "path": Schema.String.annotate({ "description": "Path of the file to delete." }) +}).annotate({ + "title": "Apply patch delete file operation", + "description": "Instruction describing how to delete a file via the apply_patch tool." +}) +export type ApplyPatchUpdateFileOperation = { + readonly "type": "update_file" + readonly "path": string + readonly "diff": string +} +export const ApplyPatchUpdateFileOperation = Schema.Struct({ + "type": Schema.Literal("update_file").annotate({ "description": "Update an existing file with the provided diff." }), + "path": Schema.String.annotate({ "description": "Path of the file to update." }), + "diff": Schema.String.annotate({ "description": "Diff to apply." }) +}).annotate({ + "title": "Apply patch update file operation", + "description": "Instruction describing how to update a file via the apply_patch tool." +}) +export type ApplyPatchToolCallOutput = { + readonly "type": "apply_patch_call_output" + readonly "id": string + readonly "call_id": string + readonly "status": "completed" | "failed" + readonly "output"?: string | null + readonly "created_by"?: string +} +export const ApplyPatchToolCallOutput = Schema.Struct({ + "type": Schema.Literal("apply_patch_call_output").annotate({ + "description": "The type of the item. Always `apply_patch_call_output`." + }), + "id": Schema.String.annotate({ + "description": "The unique ID of the apply patch tool call output. Populated when this item is returned via API." + }), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the apply patch tool call generated by the model." + }), + "status": Schema.Literals(["completed", "failed"]).annotate({ + "description": "The status of the apply patch tool call output. One of `completed` or `failed`." + }), + "output": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "Optional textual output returned by the apply patch tool." }), + Schema.Null + ]) + ), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the entity that created this tool call output." }) + ) +}).annotate({ + "title": "Apply patch tool call output", + "description": "The output emitted by an apply patch tool call." +}) +export type InputTextContentParam = { readonly "type": "input_text"; readonly "text": string } +export const InputTextContentParam = Schema.Struct({ + "type": Schema.Literal("input_text").annotate({ "description": "The type of the input item. Always `input_text`." }), + "text": Schema.String.annotate({ "description": "The text input to the model." }).check(Schema.isMaxLength(10485760)) +}).annotate({ "title": "Input text", "description": "A text input to the model." }) +export type InputImageContentParamAutoParam = { + readonly "type": "input_image" + readonly "image_url"?: string | null + readonly "file_id"?: string | null + readonly "detail"?: "low" | "high" | "auto" | "original" | null +} +export const InputImageContentParamAutoParam = Schema.Struct({ + "type": Schema.Literal("input_image").annotate({ + "description": "The type of the input item. Always `input_image`." + }), + "image_url": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL.", + "format": "uri" + }).check(Schema.isMaxLength(20971520)), + Schema.Null + ]) + ), + "file_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The ID of the file to be sent to the model." }), + Schema.Null + ]) + ), + "detail": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["low", "high", "auto", "original"]).annotate({ + "description": + "The detail level of the image to be sent to the model. One of `high`, `low`, `auto`, or `original`. Defaults to `auto`." + }), + Schema.Null + ]) + ) +}).annotate({ + "title": "Input image", + "description": "An image input to the model. Learn about [image inputs](/docs/guides/vision)" +}) +export type InputFileContentParam = { + readonly "type": "input_file" + readonly "file_id"?: string | null + readonly "filename"?: string | null + readonly "file_data"?: string | null + readonly "file_url"?: string | null + readonly "detail"?: "low" | "high" +} +export const InputFileContentParam = Schema.Struct({ + "type": Schema.Literal("input_file").annotate({ "description": "The type of the input item. Always `input_file`." }), + "file_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The ID of the file to be sent to the model." }), + Schema.Null + ]) + ), + "filename": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The name of the file to be sent to the model." }), + Schema.Null + ]) + ), + "file_data": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The base64-encoded data of the file to be sent to the model." }).check( + Schema.isMaxLength(73400320) + ), + Schema.Null + ]) + ), + "file_url": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The URL of the file to be sent to the model.", "format": "uri" }), + Schema.Null + ]) + ), + "detail": Schema.optionalKey( + Schema.Literals(["low", "high"]).annotate({ + "description": + "The detail level of the file to be sent to the model. Use `low` for the default rendering behavior, or `high` to render the file at higher quality. Defaults to `low`." + }) + ) +}).annotate({ "title": "Input file", "description": "A file input to the model." }) +export type FunctionShellCallOutputTimeoutOutcomeParam = { readonly "type": "timeout" } +export const FunctionShellCallOutputTimeoutOutcomeParam = Schema.Struct({ + "type": Schema.Literal("timeout").annotate({ "description": "The outcome type. Always `timeout`." }) +}).annotate({ + "title": "Shell call timeout outcome", + "description": "Indicates that the shell call exceeded its configured time limit." +}) +export type FunctionShellCallOutputExitOutcomeParam = { readonly "type": "exit"; readonly "exit_code": number } +export const FunctionShellCallOutputExitOutcomeParam = Schema.Struct({ + "type": Schema.Literal("exit").annotate({ "description": "The outcome type. Always `exit`." }), + "exit_code": Schema.Number.annotate({ "description": "The exit code returned by the shell process." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "Shell call exit outcome", + "description": "Indicates that the shell commands finished and returned an exit code." +}) +export type ApplyPatchCreateFileOperationParam = { + readonly "type": "create_file" + readonly "path": string + readonly "diff": string +} +export const ApplyPatchCreateFileOperationParam = Schema.Struct({ + "type": Schema.Literal("create_file").annotate({ "description": "The operation type. Always `create_file`." }), + "path": Schema.String.annotate({ "description": "Path of the file to create relative to the workspace root." }).check( + Schema.isMinLength(1) + ), + "diff": Schema.String.annotate({ "description": "Unified diff content to apply when creating the file." }).check( + Schema.isMaxLength(10485760) + ) +}).annotate({ + "title": "Apply patch create file operation", + "description": "Instruction for creating a new file via the apply_patch tool." +}) +export type ApplyPatchDeleteFileOperationParam = { readonly "type": "delete_file"; readonly "path": string } +export const ApplyPatchDeleteFileOperationParam = Schema.Struct({ + "type": Schema.Literal("delete_file").annotate({ "description": "The operation type. Always `delete_file`." }), + "path": Schema.String.annotate({ "description": "Path of the file to delete relative to the workspace root." }).check( + Schema.isMinLength(1) + ) +}).annotate({ + "title": "Apply patch delete file operation", + "description": "Instruction for deleting an existing file via the apply_patch tool." +}) +export type ApplyPatchUpdateFileOperationParam = { + readonly "type": "update_file" + readonly "path": string + readonly "diff": string +} +export const ApplyPatchUpdateFileOperationParam = Schema.Struct({ + "type": Schema.Literal("update_file").annotate({ "description": "The operation type. Always `update_file`." }), + "path": Schema.String.annotate({ "description": "Path of the file to update relative to the workspace root." }).check( + Schema.isMinLength(1) + ), + "diff": Schema.String.annotate({ "description": "Unified diff content to apply to the existing file." }).check( + Schema.isMaxLength(10485760) + ) +}).annotate({ + "title": "Apply patch update file operation", + "description": "Instruction for updating an existing file via the apply_patch tool." +}) +export type CompactionTriggerItemParam = { readonly "type": "compaction_trigger" } +export const CompactionTriggerItemParam = Schema.Struct({ + "type": Schema.Literal("compaction_trigger").annotate({ + "description": "The type of the item. Always `compaction_trigger`." + }) +}).annotate({ + "title": "Compaction trigger", + "description": "Compacts the current context. Must be the final input item." +}) +export type ItemReferenceParam = { readonly "type"?: "item_reference" | null; readonly "id": string } +export const ItemReferenceParam = Schema.Struct({ + "type": Schema.optionalKey( + Schema.Union([ + Schema.Literal("item_reference").annotate({ + "description": "The type of item to reference. Always `item_reference`." + }), + Schema.Null + ]) + ), + "id": Schema.String.annotate({ "description": "The ID of the item to reference." }) +}).annotate({ "title": "Item reference", "description": "An internal identifier for an item to reference." }) +export type ConversationResource = { + readonly "id": string + readonly "object": "conversation" + readonly "metadata": unknown + readonly "created_at": number +} +export const ConversationResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the conversation." }), + "object": Schema.Literal("conversation").annotate({ + "description": "The object type, which is always `conversation`." + }), + "metadata": Schema.Unknown.annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard.\n Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters." + }), + "created_at": Schema.Number.annotate({ + "description": "The time at which the conversation was created, measured in seconds since the Unix epoch.", + "format": "unixtime" + }).check(Schema.isInt()) +}) +export type ImageGenOutputTokensDetails = { readonly "image_tokens": number; readonly "text_tokens": number } +export const ImageGenOutputTokensDetails = Schema.Struct({ + "image_tokens": Schema.Number.annotate({ "description": "The number of image output tokens generated by the model." }) + .check(Schema.isInt()), + "text_tokens": Schema.Number.annotate({ "description": "The number of text output tokens generated by the model." }) + .check(Schema.isInt()) +}).annotate({ + "title": "Image generation output token details", + "description": "The output token details for the image generation." +}) +export type ImageGenInputUsageDetails = { readonly "text_tokens": number; readonly "image_tokens": number } +export const ImageGenInputUsageDetails = Schema.Struct({ + "text_tokens": Schema.Number.annotate({ "description": "The number of text tokens in the input prompt." }).check( + Schema.isInt() + ), + "image_tokens": Schema.Number.annotate({ "description": "The number of image tokens in the input prompt." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "Input usage details", + "description": "The input tokens detailed information for the image generation." +}) +export type SpecificApplyPatchParam = { readonly "type": "apply_patch" } +export const SpecificApplyPatchParam = Schema.Struct({ + "type": Schema.Literal("apply_patch").annotate({ "description": "The tool to call. Always `apply_patch`." }) +}).annotate({ + "title": "Specific apply patch tool choice", + "description": "Forces the model to call the apply_patch tool when executing a tool call." +}) +export type SpecificFunctionShellParam = { readonly "type": "shell" } +export const SpecificFunctionShellParam = Schema.Struct({ + "type": Schema.Literal("shell").annotate({ "description": "The tool to call. Always `shell`." }) +}).annotate({ + "title": "Specific shell tool choice", + "description": "Forces the model to call the shell tool when a tool call is required." +}) +export type ConversationParam_2 = { readonly "id": string } +export const ConversationParam_2 = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the conversation." }) +}).annotate({ "title": "Conversation object", "description": "The conversation that this response belongs to." }) +export type ContextManagementParam = { readonly "type": string; readonly "compact_threshold"?: number | null } +export const ContextManagementParam = Schema.Struct({ + "type": Schema.String.annotate({ + "description": "The context management entry type. Currently only 'compaction' is supported." + }), + "compact_threshold": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "Token threshold at which compaction should be triggered for this entry." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1000)), + Schema.Null + ]) + ) +}) +export type Conversation_2 = { readonly "id": string } +export const Conversation_2 = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The unique ID of the conversation that this response was associated with." + }) +}).annotate({ + "title": "Conversation", + "description": + "The conversation that this response belonged to. Input items and output items from this response were automatically added to this conversation." +}) +export type UpdateConversationBody = { readonly "metadata": {} | null } +export const UpdateConversationBody = Schema.Struct({ + "metadata": Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null + ]).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard.\n Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters." + }) +}) +export type DeletedConversationResource = { + readonly "object": "conversation.deleted" + readonly "deleted": boolean + readonly "id": string +} +export const DeletedConversationResource = Schema.Struct({ + "object": Schema.Literal("conversation.deleted"), + "deleted": Schema.Boolean, + "id": Schema.String +}) +export type OrderEnum = "asc" | "desc" +export const OrderEnum = Schema.Literals(["asc", "desc"]) +export type VideoResource = { + readonly "id": string + readonly "object": "video" + readonly "model": + | string + | "sora-2" + | "sora-2-pro" + | "sora-2-2025-10-06" + | "sora-2-pro-2025-10-06" + | "sora-2-2025-12-08" + readonly "status": "queued" | "in_progress" | "completed" | "failed" + readonly "progress": number + readonly "created_at": number + readonly "completed_at": number | null + readonly "expires_at": number | null + readonly "prompt": string | null + readonly "size": "720x1280" | "1280x720" | "1024x1792" | "1792x1024" + readonly "seconds": string + readonly "remixed_from_video_id": string | null + readonly "error": { readonly "code": string; readonly "message": string } | null +} +export const VideoResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Unique identifier for the video job." }), + "object": Schema.Literal("video").annotate({ "description": "The object type, which is always `video`." }), + "model": Schema.Union([ + Schema.String, + Schema.Literals(["sora-2", "sora-2-pro", "sora-2-2025-10-06", "sora-2-pro-2025-10-06", "sora-2-2025-12-08"]) + ]).annotate({ "description": "The video generation model that produced the job." }), + "status": Schema.Literals(["queued", "in_progress", "completed", "failed"]).annotate({ + "description": "Current lifecycle status of the video job." + }), + "progress": Schema.Number.annotate({ "description": "Approximate completion percentage for the generation task." }) + .check(Schema.isInt()), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (seconds) for when the job was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "completed_at": Schema.Union([ + Schema.Number.annotate({ + "description": "Unix timestamp (seconds) for when the job completed, if finished.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "expires_at": Schema.Union([ + Schema.Number.annotate({ + "description": "Unix timestamp (seconds) for when the downloadable assets expire, if set.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "prompt": Schema.Union([ + Schema.String.annotate({ "description": "The prompt that was used to generate the video." }), + Schema.Null + ]), + "size": Schema.Literals(["720x1280", "1280x720", "1024x1792", "1792x1024"]).annotate({ + "description": "The resolution of the generated video." + }), + "seconds": Schema.String.annotate({ + "description": "Duration of the generated clip in seconds. For extensions, this is the stitched total duration." + }), + "remixed_from_video_id": Schema.Union([ + Schema.String.annotate({ "description": "Identifier of the source video if this video is a remix." }), + Schema.Null + ]), + "error": Schema.Union([ + Schema.Struct({ + "code": Schema.String.annotate({ "description": "A machine-readable error code that was returned." }), + "message": Schema.String.annotate({ + "description": "A human-readable description of the error that was returned." + }) + }).annotate({ + "title": "Error", + "description": "Error payload that explains why generation failed, if applicable." + }), + Schema.Null + ]) +}).annotate({ "title": "Video job", "description": "Structured information describing a generated video job." }) +export type ImageRefParam_2 = { readonly "image_url"?: string; readonly "file_id"?: string } +export const ImageRefParam_2 = Schema.Struct({ + "image_url": Schema.optionalKey( + Schema.String.annotate({ "description": "A fully qualified URL or base64-encoded data URL.", "format": "uri" }) + .check(Schema.isMaxLength(20971520)) + ), + "file_id": Schema.optionalKey(Schema.String) +}) +export type CreateVideoJsonBody = { + readonly "model"?: + | string + | "sora-2" + | "sora-2-pro" + | "sora-2-2025-10-06" + | "sora-2-pro-2025-10-06" + | "sora-2-2025-12-08" + readonly "prompt": string + readonly "input_reference"?: { readonly "image_url"?: string; readonly "file_id"?: string } + readonly "seconds"?: "4" | "8" | "12" + readonly "size"?: "720x1280" | "1280x720" | "1024x1792" | "1792x1024" +} +export const CreateVideoJsonBody = Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals(["sora-2", "sora-2-pro", "sora-2-2025-10-06", "sora-2-pro-2025-10-06", "sora-2-2025-12-08"]) + ]).annotate({ + "description": "The video generation model to use (allowed values: sora-2, sora-2-pro). Defaults to `sora-2`." + }) + ), + "prompt": Schema.String.annotate({ "description": "Text prompt that describes the video to generate." }).check( + Schema.isMinLength(1) + ).check(Schema.isMaxLength(32000)), + "input_reference": Schema.optionalKey( + Schema.Struct({ + "image_url": Schema.optionalKey( + Schema.String.annotate({ "description": "A fully qualified URL or base64-encoded data URL.", "format": "uri" }) + .check(Schema.isMaxLength(20971520)) + ), + "file_id": Schema.optionalKey(Schema.String) + }).annotate({ + "description": + "Optional reference object that guides generation. Provide exactly one of `image_url` or `file_id`." + }) + ), + "seconds": Schema.optionalKey( + Schema.Literals(["4", "8", "12"]).annotate({ + "description": "Clip duration in seconds (allowed values: 4, 8, 12). Defaults to 4 seconds." + }) + ), + "size": Schema.optionalKey( + Schema.Literals(["720x1280", "1280x720", "1024x1792", "1792x1024"]).annotate({ + "description": + "Output resolution formatted as width x height (allowed values: 720x1280, 1280x720, 1024x1792, 1792x1024). Defaults to 720x1280." + }) + ) +}).annotate({ + "title": "Create video JSON request", + "description": "JSON parameters for creating a new video generation job." +}) +export type CreateVideoCharacterBody = { readonly "video": string; readonly "name": string } +export const CreateVideoCharacterBody = Schema.Struct({ + "video": Schema.String.annotate({ "description": "Video file used to create a character.", "format": "binary" }), + "name": Schema.String.annotate({ "description": "Display name for this API character." }).check(Schema.isMinLength(1)) + .check(Schema.isMaxLength(80)) +}).annotate({ + "title": "Create character request", + "description": "Parameters for creating a character from an uploaded video." +}) +export type VideoCharacterResource = { + readonly "id": string | null + readonly "name": string | null + readonly "created_at": number +} +export const VideoCharacterResource = Schema.Struct({ + "id": Schema.Union([ + Schema.String.annotate({ "description": "Identifier for the character creation cameo." }), + Schema.Null + ]), + "name": Schema.Union([Schema.String.annotate({ "description": "Display name for the character." }), Schema.Null]), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the character was created.", + "format": "unixtime" + }).check(Schema.isInt()) +}) +export type VideoReferenceInputParam = { readonly "id": string } +export const VideoReferenceInputParam = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier of the completed video." }) +}).annotate({ "description": "Reference to the completed video." }) +export type CreateVideoEditJsonBody = { readonly "video": { readonly "id": string }; readonly "prompt": string } +export const CreateVideoEditJsonBody = Schema.Struct({ + "video": Schema.Struct({ "id": Schema.String.annotate({ "description": "The identifier of the completed video." }) }) + .annotate({ "description": "Reference to the completed video to edit." }), + "prompt": Schema.String.annotate({ "description": "Text prompt that describes how to edit the source video." }).check( + Schema.isMinLength(1) + ).check(Schema.isMaxLength(32000)) +}).annotate({ + "title": "Create video edit JSON request", + "description": "JSON parameters for editing an existing generated video." +}) +export type CreateVideoExtendJsonBody = { + readonly "video": { readonly "id": string } + readonly "prompt": string + readonly "seconds": "4" | "8" | "12" +} +export const CreateVideoExtendJsonBody = Schema.Struct({ + "video": Schema.Struct({ "id": Schema.String.annotate({ "description": "The identifier of the completed video." }) }) + .annotate({ "description": "Reference to the completed video to extend." }), + "prompt": Schema.String.annotate({ "description": "Updated text prompt that directs the extension generation." }) + .check(Schema.isMinLength(1)).check(Schema.isMaxLength(32000)), + "seconds": Schema.Literals(["4", "8", "12"]).annotate({ + "description": "Length of the newly generated extension segment in seconds (allowed values: 4, 8, 12, 16, 20)." + }) +}).annotate({ + "title": "Create video extension JSON request", + "description": "JSON parameters for extending an existing generated video." +}) +export type DeletedVideoResource = { + readonly "object": "video.deleted" + readonly "deleted": boolean + readonly "id": string +} +export const DeletedVideoResource = Schema.Struct({ + "object": Schema.Literal("video.deleted").annotate({ + "description": "The object type that signals the deletion response." + }), + "deleted": Schema.Boolean.annotate({ "description": "Indicates that the video resource was deleted." }), + "id": Schema.String.annotate({ "description": "Identifier of the deleted video." }) +}).annotate({ + "title": "Deleted video response", + "description": "Confirmation payload returned after deleting a video." +}) +export type VideoContentVariant = "video" | "thumbnail" | "spritesheet" +export const VideoContentVariant = Schema.Literals(["video", "thumbnail", "spritesheet"]) +export type CreateVideoRemixBody = { readonly "prompt": string } +export const CreateVideoRemixBody = Schema.Struct({ + "prompt": Schema.String.annotate({ "description": "Updated text prompt that directs the remix generation." }).check( + Schema.isMinLength(1) + ).check(Schema.isMaxLength(32000)) +}).annotate({ + "title": "Create video remix request", + "description": "Parameters for remixing an existing generated video." +}) +export type TokenCountsResource = { readonly "object": "response.input_tokens"; readonly "input_tokens": number } +export const TokenCountsResource = Schema.Struct({ + "object": Schema.Literal("response.input_tokens"), + "input_tokens": Schema.Number.check(Schema.isInt()) +}).annotate({ "title": "Token counts" }) +export type SkillResource = { + readonly "id": string + readonly "object": "skill" + readonly "name": string + readonly "description": string + readonly "created_at": number + readonly "default_version": string + readonly "latest_version": string +} +export const SkillResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Unique identifier for the skill." }), + "object": Schema.Literal("skill").annotate({ "description": "The object type, which is `skill`." }), + "name": Schema.String.annotate({ "description": "Name of the skill." }), + "description": Schema.String.annotate({ "description": "Description of the skill." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (seconds) for when the skill was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "default_version": Schema.String.annotate({ "description": "Default version for the skill." }), + "latest_version": Schema.String.annotate({ "description": "Latest version for the skill." }) +}) +export type CreateSkillBody = { readonly "files": ReadonlyArray | string } +export const CreateSkillBody = Schema.Struct({ + "files": Schema.Union([ + Schema.Array(Schema.String.annotate({ "format": "binary" })).annotate({ + "description": "Skill files to upload (directory upload) or a single zip file." + }).check(Schema.isMaxLength(500)), + Schema.String.annotate({ "description": "Skill zip file to upload.", "format": "binary" }) + ], { mode: "oneOf" }) +}).annotate({ + "title": "Create skill request", + "description": "Uploads a skill either as a directory (multipart `files[]`) or as a single zip file." +}) +export type SetDefaultSkillVersionBody = { readonly "default_version": string } +export const SetDefaultSkillVersionBody = Schema.Struct({ + "default_version": Schema.String.annotate({ "description": "The skill version number to set as default." }) +}).annotate({ "title": "Update skill request", "description": "Updates the default version pointer for a skill." }) +export type DeletedSkillResource = { + readonly "object": "skill.deleted" + readonly "deleted": boolean + readonly "id": string +} +export const DeletedSkillResource = Schema.Struct({ + "object": Schema.Literal("skill.deleted"), + "deleted": Schema.Boolean, + "id": Schema.String +}) +export type SkillVersionResource = { + readonly "object": "skill.version" + readonly "id": string + readonly "skill_id": string + readonly "version": string + readonly "created_at": number + readonly "name": string + readonly "description": string +} +export const SkillVersionResource = Schema.Struct({ + "object": Schema.Literal("skill.version").annotate({ "description": "The object type, which is `skill.version`." }), + "id": Schema.String.annotate({ "description": "Unique identifier for the skill version." }), + "skill_id": Schema.String.annotate({ "description": "Identifier of the skill for this version." }), + "version": Schema.String.annotate({ "description": "Version number for this skill." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (seconds) for when the version was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "name": Schema.String.annotate({ "description": "Name of the skill version." }), + "description": Schema.String.annotate({ "description": "Description of the skill version." }) +}) +export type CreateSkillVersionBody = { readonly "files": ReadonlyArray | string; readonly "default"?: boolean } +export const CreateSkillVersionBody = Schema.Struct({ + "files": Schema.Union([ + Schema.Array(Schema.String.annotate({ "format": "binary" })).annotate({ + "description": "Skill files to upload (directory upload) or a single zip file." + }).check(Schema.isMaxLength(500)), + Schema.String.annotate({ "description": "Skill zip file to upload.", "format": "binary" }) + ], { mode: "oneOf" }), + "default": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether to set this version as the default." }) + ) +}).annotate({ "title": "Create skill version request", "description": "Uploads a new immutable version of a skill." }) +export type DeletedSkillVersionResource = { + readonly "object": "skill.version.deleted" + readonly "deleted": boolean + readonly "id": string + readonly "version": string +} +export const DeletedSkillVersionResource = Schema.Struct({ + "object": Schema.Literal("skill.version.deleted"), + "deleted": Schema.Boolean, + "id": Schema.String, + "version": Schema.String.annotate({ "description": "The deleted skill version." }) +}) +export type ChatSessionResource = { + readonly "id": string + readonly "object": "chatkit.session" + readonly "expires_at": number + readonly "client_secret": string + readonly "workflow": { + readonly "id": string + readonly "version": string | null + readonly "state_variables": {} | null + readonly "tracing": { readonly "enabled": boolean } + } + readonly "user": string + readonly "rate_limits": { readonly "max_requests_per_1_minute": number } + readonly "max_requests_per_1_minute": number + readonly "status": "active" | "expired" | "cancelled" + readonly "chatkit_configuration": { + readonly "automatic_thread_titling": { readonly "enabled": boolean } + readonly "file_upload": { + readonly "enabled": boolean + readonly "max_file_size": number | null + readonly "max_files": number | null + } + readonly "history": { readonly "enabled": boolean; readonly "recent_threads": number | null } + } +} +export const ChatSessionResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier for the ChatKit session." }), + "object": Schema.Literal("chatkit.session").annotate({ + "description": "Type discriminator that is always `chatkit.session`." + }), + "expires_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) for when the session expires.", + "format": "unixtime" + }).check(Schema.isInt()), + "client_secret": Schema.String.annotate({ + "description": "Ephemeral client secret that authenticates session requests." + }), + "workflow": Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier of the workflow backing the session." }), + "version": Schema.Union([ + Schema.String.annotate({ + "description": + "Specific workflow version used for the session. Defaults to null when using the latest deployment." + }), + Schema.Null + ]), + "state_variables": Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "State variable key-value pairs applied when invoking the workflow. Defaults to null when no overrides were provided." + }), + Schema.Null + ]), + "tracing": Schema.Struct({ + "enabled": Schema.Boolean.annotate({ "description": "Indicates whether tracing is enabled." }) + }).annotate({ "title": "Tracing Configuration", "description": "Tracing settings applied to the workflow." }) + }).annotate({ "title": "Workflow", "description": "Workflow metadata for the session." }), + "user": Schema.String.annotate({ "description": "User identifier associated with the session." }), + "rate_limits": Schema.Struct({ + "max_requests_per_1_minute": Schema.Number.annotate({ + "description": "Maximum allowed requests per one-minute window." + }).check(Schema.isInt()) + }).annotate({ "title": "Rate limits", "description": "Resolved rate limit values." }), + "max_requests_per_1_minute": Schema.Number.annotate({ + "description": "Convenience copy of the per-minute request limit." + }).check(Schema.isInt()), + "status": Schema.Literals(["active", "expired", "cancelled"]).annotate({ + "description": "Current lifecycle state of the session." + }), + "chatkit_configuration": Schema.Struct({ + "automatic_thread_titling": Schema.Struct({ + "enabled": Schema.Boolean.annotate({ "description": "Whether automatic thread titling is enabled." }) + }).annotate({ "title": "Automatic thread titling", "description": "Automatic thread titling preferences." }), + "file_upload": Schema.Struct({ + "enabled": Schema.Boolean.annotate({ "description": "Indicates if uploads are enabled for the session." }), + "max_file_size": Schema.Union([ + Schema.Number.annotate({ "description": "Maximum upload size in megabytes." }).check(Schema.isInt()), + Schema.Null + ]), + "max_files": Schema.Union([ + Schema.Number.annotate({ "description": "Maximum number of uploads allowed during the session." }).check( + Schema.isInt() + ), + Schema.Null + ]) + }).annotate({ "title": "File upload settings", "description": "Upload settings for the session." }), + "history": Schema.Struct({ + "enabled": Schema.Boolean.annotate({ "description": "Indicates if chat history is persisted for the session." }), + "recent_threads": Schema.Union([ + Schema.Number.annotate({ + "description": + "Number of prior threads surfaced in history views. Defaults to null when all history is retained." + }).check(Schema.isInt()), + Schema.Null + ]) + }).annotate({ "title": "History settings", "description": "History retention configuration." }) + }).annotate({ + "title": "ChatKit configuration", + "description": "Resolved ChatKit feature configuration for the session." + }) +}).annotate({ + "title": "The chat session object", + "description": "Represents a ChatKit session and its resolved configuration." +}) +export type CreateChatSessionBody = { + readonly "workflow": { + readonly "id": string + readonly "version"?: string + readonly "state_variables"?: {} + readonly "tracing"?: { readonly "enabled"?: boolean } + } + readonly "user": string + readonly "expires_after"?: { readonly "anchor": "created_at"; readonly "seconds": number } + readonly "rate_limits"?: { readonly "max_requests_per_1_minute"?: number } + readonly "chatkit_configuration"?: { + readonly "automatic_thread_titling"?: { readonly "enabled"?: boolean } + readonly "file_upload"?: { + readonly "enabled"?: boolean + readonly "max_file_size"?: number + readonly "max_files"?: number + } + readonly "history"?: { readonly "enabled"?: boolean; readonly "recent_threads"?: number } + } +} +export const CreateChatSessionBody = Schema.Struct({ + "workflow": Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier for the workflow invoked by the session." }), + "version": Schema.optionalKey( + Schema.String.annotate({ + "description": "Specific workflow version to run. Defaults to the latest deployed version." + }) + ), + "state_variables": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": + "State variables forwarded to the workflow. Keys may be up to 64 characters, values must be primitive types, and the map defaults to an empty object." + }).check(Schema.isMaxProperties(64)) + ), + "tracing": Schema.optionalKey( + Schema.Struct({ + "enabled": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether tracing is enabled during the session. Defaults to true." }) + ) + }).annotate({ + "title": "Tracing Configuration", + "description": + "Optional tracing overrides for the workflow invocation. When omitted, tracing is enabled by default." + }) + ) + }).annotate({ "title": "Workflow settings", "description": "Workflow that powers the session." }), + "user": Schema.String.annotate({ + "description": + "A free-form string that identifies your end user; ensures this Session can access other objects that have the same `user` scope." + }).check(Schema.isMinLength(1)), + "expires_after": Schema.optionalKey( + Schema.Struct({ + "anchor": Schema.Literal("created_at").annotate({ + "description": "Base timestamp used to calculate expiration. Currently fixed to `created_at`." + }), + "seconds": Schema.Number.annotate({ + "description": "Number of seconds after the anchor when the session expires.", + "format": "int64" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(600)) + }).annotate({ + "title": "Expiration overrides", + "description": "Optional override for session expiration timing in seconds from creation. Defaults to 10 minutes." + }) + ), + "rate_limits": Schema.optionalKey( + Schema.Struct({ + "max_requests_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Maximum number of requests allowed per minute for the session. Defaults to 10." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)) + ) + }).annotate({ + "title": "Rate limit overrides", + "description": "Optional override for per-minute request limits. When omitted, defaults to 10." + }) + ), + "chatkit_configuration": Schema.optionalKey( + Schema.Struct({ + "automatic_thread_titling": Schema.optionalKey( + Schema.Struct({ + "enabled": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Enable automatic thread title generation. Defaults to true." }) + ) + }).annotate({ + "title": "Automatic thread titling configuration", + "description": + "Configuration for automatic thread titling. When omitted, automatic thread titling is enabled by default." + }) + ), + "file_upload": Schema.optionalKey( + Schema.Struct({ + "enabled": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Enable uploads for this session. Defaults to false." }) + ), + "max_file_size": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Maximum size in megabytes for each uploaded file. Defaults to 512 MB, which is the maximum allowable size." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(512)) + ), + "max_files": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Maximum number of files that can be uploaded to the session. Defaults to 10." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)) + ) + }).annotate({ + "title": "File upload configuration", + "description": + "Configuration for upload enablement and limits. When omitted, uploads are disabled by default (max_files 10, max_file_size 512 MB)." + }) + ), + "history": Schema.optionalKey( + Schema.Struct({ + "enabled": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": "Enables chat users to access previous ChatKit threads. Defaults to true." + }) + ), + "recent_threads": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Number of recent ChatKit threads users have access to. Defaults to unlimited when unset." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)) + ) + }).annotate({ + "title": "Chat history configuration", + "description": + "Configuration for chat history retention. When omitted, history is enabled by default with no limit on recent_threads (null)." + }) + ) + }).annotate({ + "title": "ChatKit configuration overrides", + "description": "Optional overrides for ChatKit runtime configuration features" + }) + ) +}).annotate({ + "title": "Create chat session request", + "description": "Parameters for provisioning a new ChatKit session." +}) +export type UserMessageInputText = { readonly "type": "input_text"; readonly "text": string } +export const UserMessageInputText = Schema.Struct({ + "type": Schema.Literal("input_text").annotate({ "description": "Type discriminator that is always `input_text`." }), + "text": Schema.String.annotate({ "description": "Plain-text content supplied by the user." }) +}).annotate({ "title": "User message input", "description": "Text block that a user contributed to the thread." }) +export type UserMessageQuotedText = { readonly "type": "quoted_text"; readonly "text": string } +export const UserMessageQuotedText = Schema.Struct({ + "type": Schema.Literal("quoted_text").annotate({ "description": "Type discriminator that is always `quoted_text`." }), + "text": Schema.String.annotate({ "description": "Quoted text content." }) +}).annotate({ + "title": "User message quoted text", + "description": "Quoted snippet that the user referenced in their message." +}) +export type Attachment = { + readonly "type": "image" | "file" + readonly "id": string + readonly "name": string + readonly "mime_type": string + readonly "preview_url": string | null +} +export const Attachment = Schema.Struct({ + "type": Schema.Literals(["image", "file"]).annotate({ "description": "Attachment discriminator." }), + "id": Schema.String.annotate({ "description": "Identifier for the attachment." }), + "name": Schema.String.annotate({ "description": "Original display name for the attachment." }), + "mime_type": Schema.String.annotate({ "description": "MIME type of the attachment." }), + "preview_url": Schema.Union([ + Schema.String.annotate({ "description": "Preview URL for rendering the attachment inline.", "format": "uri" }), + Schema.Null + ]) +}).annotate({ "title": "Attachment", "description": "Attachment metadata included on thread items." }) +export type FileAnnotation = { + readonly "type": "file" + readonly "source": { readonly "type": "file"; readonly "filename": string } +} +export const FileAnnotation = Schema.Struct({ + "type": Schema.Literal("file").annotate({ + "description": "Type discriminator that is always `file` for this annotation." + }), + "source": Schema.Struct({ + "type": Schema.Literal("file").annotate({ "description": "Type discriminator that is always `file`." }), + "filename": Schema.String.annotate({ "description": "Filename referenced by the annotation." }) + }).annotate({ "title": "File annotation source", "description": "File attachment referenced by the annotation." }) +}).annotate({ "title": "File annotation", "description": "Annotation that references an uploaded file." }) +export type UrlAnnotation = { + readonly "type": "url" + readonly "source": { readonly "type": "url"; readonly "url": string } +} +export const UrlAnnotation = Schema.Struct({ + "type": Schema.Literal("url").annotate({ + "description": "Type discriminator that is always `url` for this annotation." + }), + "source": Schema.Struct({ + "type": Schema.Literal("url").annotate({ "description": "Type discriminator that is always `url`." }), + "url": Schema.String.annotate({ "description": "URL referenced by the annotation.", "format": "uri" }) + }).annotate({ "title": "URL annotation source", "description": "URL referenced by the annotation." }) +}).annotate({ "title": "URL annotation", "description": "Annotation that references a URL." }) +export type WidgetMessageItem = { + readonly "id": string + readonly "object": "chatkit.thread_item" + readonly "created_at": number + readonly "thread_id": string + readonly "type": "chatkit.widget" + readonly "widget": string +} +export const WidgetMessageItem = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier of the thread item." }), + "object": Schema.Literal("chatkit.thread_item").annotate({ + "description": "Type discriminator that is always `chatkit.thread_item`." + }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) for when the item was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "thread_id": Schema.String.annotate({ "description": "Identifier of the parent thread." }), + "type": Schema.Literal("chatkit.widget").annotate({ + "description": "Type discriminator that is always `chatkit.widget`." + }), + "widget": Schema.String.annotate({ "description": "Serialized widget payload rendered in the UI." }) +}).annotate({ "title": "Widget message", "description": "Thread item that renders a widget payload." }) +export type ClientToolCallItem = { + readonly "id": string + readonly "object": "chatkit.thread_item" + readonly "created_at": number + readonly "thread_id": string + readonly "type": "chatkit.client_tool_call" + readonly "status": "in_progress" | "completed" + readonly "call_id": string + readonly "name": string + readonly "arguments": string + readonly "output": string | null +} +export const ClientToolCallItem = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier of the thread item." }), + "object": Schema.Literal("chatkit.thread_item").annotate({ + "description": "Type discriminator that is always `chatkit.thread_item`." + }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) for when the item was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "thread_id": Schema.String.annotate({ "description": "Identifier of the parent thread." }), + "type": Schema.Literal("chatkit.client_tool_call").annotate({ + "description": "Type discriminator that is always `chatkit.client_tool_call`." + }), + "status": Schema.Literals(["in_progress", "completed"]).annotate({ + "description": "Execution status for the tool call." + }), + "call_id": Schema.String.annotate({ "description": "Identifier for the client tool call." }), + "name": Schema.String.annotate({ "description": "Tool name that was invoked." }), + "arguments": Schema.String.annotate({ "description": "JSON-encoded arguments that were sent to the tool." }), + "output": Schema.Union([ + Schema.String.annotate({ + "description": "JSON-encoded output captured from the tool. Defaults to null while execution is in progress." + }), + Schema.Null + ]) +}).annotate({ + "title": "Client tool call", + "description": "Record of a client side tool invocation initiated by the assistant." +}) +export type TaskItem = { + readonly "id": string + readonly "object": "chatkit.thread_item" + readonly "created_at": number + readonly "thread_id": string + readonly "type": "chatkit.task" + readonly "task_type": "custom" | "thought" + readonly "heading": string | null + readonly "summary": string | null +} +export const TaskItem = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier of the thread item." }), + "object": Schema.Literal("chatkit.thread_item").annotate({ + "description": "Type discriminator that is always `chatkit.thread_item`." + }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) for when the item was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "thread_id": Schema.String.annotate({ "description": "Identifier of the parent thread." }), + "type": Schema.Literal("chatkit.task").annotate({ + "description": "Type discriminator that is always `chatkit.task`." + }), + "task_type": Schema.Literals(["custom", "thought"]).annotate({ "description": "Subtype for the task." }), + "heading": Schema.Union([ + Schema.String.annotate({ "description": "Optional heading for the task. Defaults to null when not provided." }), + Schema.Null + ]), + "summary": Schema.Union([ + Schema.String.annotate({ + "description": "Optional summary that describes the task. Defaults to null when omitted." + }), + Schema.Null + ]) +}).annotate({ + "title": "Task item", + "description": "Task emitted by the workflow to show progress and status updates." +}) +export type TaskGroupTask = { + readonly "type": "custom" | "thought" + readonly "heading": string | null + readonly "summary": string | null +} +export const TaskGroupTask = Schema.Struct({ + "type": Schema.Literals(["custom", "thought"]).annotate({ "description": "Subtype for the grouped task." }), + "heading": Schema.Union([ + Schema.String.annotate({ + "description": "Optional heading for the grouped task. Defaults to null when not provided." + }), + Schema.Null + ]), + "summary": Schema.Union([ + Schema.String.annotate({ + "description": "Optional summary that describes the grouped task. Defaults to null when omitted." + }), + Schema.Null + ]) +}).annotate({ "title": "Task group task", "description": "Task entry that appears within a TaskGroup." }) +export type ActiveStatus = { readonly "type": "active" } +export const ActiveStatus = Schema.Struct({ + "type": Schema.Literal("active").annotate({ "description": "Status discriminator that is always `active`." }) +}).annotate({ "title": "Active thread status", "description": "Indicates that a thread is active." }) +export type LockedStatus = { readonly "type": "locked"; readonly "reason": string | null } +export const LockedStatus = Schema.Struct({ + "type": Schema.Literal("locked").annotate({ "description": "Status discriminator that is always `locked`." }), + "reason": Schema.Union([ + Schema.String.annotate({ + "description": "Reason that the thread was locked. Defaults to null when no reason is recorded." + }), + Schema.Null + ]) +}).annotate({ + "title": "Locked thread status", + "description": "Indicates that a thread is locked and cannot accept new input." +}) +export type ClosedStatus = { readonly "type": "closed"; readonly "reason": string | null } +export const ClosedStatus = Schema.Struct({ + "type": Schema.Literal("closed").annotate({ "description": "Status discriminator that is always `closed`." }), + "reason": Schema.Union([ + Schema.String.annotate({ + "description": "Reason that the thread was closed. Defaults to null when no reason is recorded." + }), + Schema.Null + ]) +}).annotate({ "title": "Closed thread status", "description": "Indicates that a thread has been closed." }) +export type DeletedThreadResource = { + readonly "id": string + readonly "object": "chatkit.thread.deleted" + readonly "deleted": boolean +} +export const DeletedThreadResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier of the deleted thread." }), + "object": Schema.Literal("chatkit.thread.deleted").annotate({ + "description": "Type discriminator that is always `chatkit.thread.deleted`." + }), + "deleted": Schema.Boolean.annotate({ "description": "Indicates that the thread has been deleted." }) +}).annotate({ "title": "Deleted thread", "description": "Confirmation payload returned after deleting a thread." }) +export type ResponseKeepAliveEvent = { readonly "type": "keepalive"; readonly "sequence_number": number } +export const ResponseKeepAliveEvent = Schema.Struct({ + "type": Schema.Literal("keepalive").annotate({ + "description": "The type of the keepalive event. Always `keepalive`." + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this keepalive event." }).check( + Schema.isInt() + ) +}).annotate({ "title": "Keep alive", "description": "A keepalive event emitted during long-running response streams." }) +export type ResponseApplyPatchCallOperationDiffDeltaEvent = { + readonly "type": "response.apply_patch_call_operation_diff.delta" + readonly "sequence_number": number + readonly "output_index": number + readonly "item_id": string + readonly "delta": string +} +export const ResponseApplyPatchCallOperationDiffDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.apply_patch_call_operation_diff.delta").annotate({ + "description": "The event type identifier." + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "output_index": Schema.Number.annotate({ "description": "The index of the output this delta applies to." }).check( + Schema.isInt() + ), + "item_id": Schema.String.annotate({ + "description": "Unique identifier for the API item associated with this event." + }), + "delta": Schema.String.annotate({ "description": "The incremental diff data for the apply_patch tool call." }) +}).annotate({ + "title": "ResponseApplyPatchCallOperationDiffDelta", + "description": "Event representing a delta for an apply_patch tool call operation diff." +}) +export type ResponseApplyPatchCallOperationDiffDoneEvent = { + readonly "type": "response.apply_patch_call_operation_diff.done" + readonly "sequence_number": number + readonly "output_index": number + readonly "item_id": string + readonly "delta"?: string +} +export const ResponseApplyPatchCallOperationDiffDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.apply_patch_call_operation_diff.done").annotate({ + "description": "The event type identifier." + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "output_index": Schema.Number.annotate({ "description": "The index of the output this event applies to." }).check( + Schema.isInt() + ), + "item_id": Schema.String.annotate({ + "description": "Unique identifier for the API item associated with this event." + }), + "delta": Schema.optionalKey( + Schema.String.annotate({ "description": "The final diff data for the apply_patch tool call." }) + ) +}).annotate({ + "title": "ResponseApplyPatchCallOperationDiffDone", + "description": "Event indicating that the operation diff for an apply_patch tool call is complete." +}) +export type ApiKeyList = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "first_id"?: string | null + readonly "last_id"?: string | null +} +export const ApiKeyList = Schema.Struct({ + "object": Schema.Literal("list"), + "data": Schema.Array(AdminApiKey), + "has_more": Schema.Boolean, + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])) +}) +export type RoleListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next": string | null +} +export const RoleListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "Always `list`." }), + "data": Schema.Array(AssignedRoleDetails).annotate({ + "description": "Role assignments returned in the current page." + }), + "has_more": Schema.Boolean.annotate({ + "description": "Whether additional assignments are available when paginating." + }), + "next": Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "Cursor to fetch the next page of results, or `null` when there are no more assignments." + }) +}).annotate({ "description": "Paginated list of roles assigned to a principal." }) +export type AuditLogActorApiKey = { + readonly "id"?: string + readonly "type"?: "user" | "service_account" + readonly "user"?: AuditLogActorUser + readonly "service_account"?: AuditLogActorServiceAccount +} +export const AuditLogActorApiKey = Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The tracking id of the API key." })), + "type": Schema.optionalKey( + Schema.Literals(["user", "service_account"]).annotate({ + "description": "The type of API key. Can be either `user` or `service_account`." + }) + ), + "user": Schema.optionalKey(AuditLogActorUser), + "service_account": Schema.optionalKey(AuditLogActorServiceAccount) +}).annotate({ "description": "The API Key used to perform the audit logged action." }) +export type AuditLogActorSession = { readonly "user"?: AuditLogActorUser; readonly "ip_address"?: string } +export const AuditLogActorSession = Schema.Struct({ + "user": Schema.optionalKey(AuditLogActorUser), + "ip_address": Schema.optionalKey( + Schema.String.annotate({ "description": "The IP address from which the action was performed." }) + ) +}).annotate({ "description": "The session in which the audit logged action was performed." }) +export type ChatCompletionAllowedToolsChoice = { + readonly "type": "allowed_tools" + readonly "allowed_tools": ChatCompletionAllowedTools +} +export const ChatCompletionAllowedToolsChoice = Schema.Struct({ + "type": Schema.Literal("allowed_tools").annotate({ + "description": "Allowed tool configuration type. Always `allowed_tools`." + }), + "allowed_tools": ChatCompletionAllowedTools +}).annotate({ + "title": "Allowed tools", + "description": "Constrains the tools available to the model to a pre-defined set.\n" +}) +export type ChatCompletionMessageToolCalls = ReadonlyArray< + ChatCompletionMessageToolCall | ChatCompletionMessageCustomToolCall +> +export const ChatCompletionMessageToolCalls = Schema.Array( + Schema.Union([ChatCompletionMessageToolCall, ChatCompletionMessageCustomToolCall], { mode: "oneOf" }) +).annotate({ "description": "The tool calls generated by the model, such as function calls." }) +export type ChatCompletionStreamResponseDelta = { + readonly "content"?: string | null + readonly "function_call"?: { readonly "arguments"?: string; readonly "name"?: string } + readonly "tool_calls"?: ReadonlyArray + readonly "role"?: "developer" | "system" | "user" | "assistant" | "tool" + readonly "refusal"?: string | null +} +export const ChatCompletionStreamResponseDelta = Schema.Struct({ + "content": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "The contents of the chunk message." }), Schema.Null]) + ), + "function_call": Schema.optionalKey( + Schema.Struct({ + "arguments": Schema.optionalKey(Schema.String.annotate({ + "description": + "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + })), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the function to call." })) + }).annotate({ + "description": + "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + }) + ), + "tool_calls": Schema.optionalKey(Schema.Array(ChatCompletionMessageToolCallChunk)), + "role": Schema.optionalKey( + Schema.Literals(["developer", "system", "user", "assistant", "tool"]).annotate({ + "description": "The role of the author of this message." + }) + ), + "refusal": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The refusal message generated by the model." }), + Schema.Null + ]) + ) +}).annotate({ "description": "A chat completion delta generated by streamed model responses." }) +export type ChatCompletionRequestAssistantMessageContentPart = + | ChatCompletionRequestMessageContentPartText + | ChatCompletionRequestMessageContentPartRefusal +export const ChatCompletionRequestAssistantMessageContentPart = Schema.Union([ + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartRefusal +], { mode: "oneOf" }) +export type ChatCompletionRequestDeveloperMessage = { + readonly "content": string | ReadonlyArray + readonly "role": "developer" + readonly "name"?: string +} +export const ChatCompletionRequestDeveloperMessage = Schema.Struct({ + "content": Schema.Union([ + Schema.String.annotate({ "title": "Text content", "description": "The contents of the developer message." }), + Schema.Array(ChatCompletionRequestMessageContentPartText).annotate({ + "title": "Array of content parts", + "description": + "An array of content parts with a defined type. For developer messages, only type `text` is supported." + }).check(Schema.isMinLength(1)) + ], { mode: "oneOf" }).annotate({ "description": "The contents of the developer message." }), + "role": Schema.Literal("developer").annotate({ + "description": "The role of the messages author, in this case `developer`." + }), + "name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "An optional name for the participant. Provides the model information to differentiate between participants of the same role." + }) + ) +}).annotate({ + "title": "Developer message", + "description": + "Developer-provided instructions that the model should follow, regardless of\nmessages sent by the user. With o1 models and newer, `developer` messages\nreplace the previous `system` messages.\n" +}) +export type ChatCompletionRequestSystemMessageContentPart = ChatCompletionRequestMessageContentPartText +export const ChatCompletionRequestSystemMessageContentPart = Schema.Union( + [ChatCompletionRequestMessageContentPartText], + { mode: "oneOf" } +) +export type ChatCompletionRequestToolMessageContentPart = ChatCompletionRequestMessageContentPartText +export const ChatCompletionRequestToolMessageContentPart = Schema.Union([ChatCompletionRequestMessageContentPartText], { + mode: "oneOf" +}) +export type ChatCompletionRequestUserMessageContentPart = + | ChatCompletionRequestMessageContentPartText + | ChatCompletionRequestMessageContentPartImage + | ChatCompletionRequestMessageContentPartAudio + | ChatCompletionRequestMessageContentPartFile +export const ChatCompletionRequestUserMessageContentPart = Schema.Union([ + ChatCompletionRequestMessageContentPartText, + ChatCompletionRequestMessageContentPartImage, + ChatCompletionRequestMessageContentPartAudio, + ChatCompletionRequestMessageContentPartFile +], { mode: "oneOf" }) +export type PredictionContent = { + readonly "type": "content" + readonly "content": string | ReadonlyArray +} +export const PredictionContent = Schema.Struct({ + "type": Schema.Literal("content").annotate({ + "description": "The type of the predicted content you want to provide. This type is\ncurrently always `content`.\n" + }), + "content": Schema.Union([ + Schema.String.annotate({ + "title": "Text content", + "description": + "The content used for a Predicted Output. This is often the\ntext of a file you are regenerating with minor changes.\n" + }), + Schema.Array(ChatCompletionRequestMessageContentPartText).annotate({ + "title": "Array of content parts", + "description": + "An array of content parts with a defined type. Supported options differ based on the [model](/docs/models) being used to generate the response. Can contain text inputs." + }).check(Schema.isMinLength(1)) + ], { mode: "oneOf" }).annotate({ + "description": + "The content that should be matched when generating a model response.\nIf generated tokens would match this content, the entire model response\ncan be returned much more quickly.\n" + }) +}).annotate({ + "title": "Static Content", + "description": "Static predicted output content, such as the content of a text file that is\nbeing regenerated.\n" +}) +export type CompoundFilter = { + readonly "type": "and" | "or" + readonly "filters": ReadonlyArray +} +export const CompoundFilter = Schema.Struct({ + "type": Schema.Literals(["and", "or"]).annotate({ "description": "Type of operation: `and` or `or`." }), + "filters": Schema.Array(Schema.Union([ComparisonFilter, Schema.Unknown], { mode: "oneOf" })).annotate({ + "description": "Array of filters to combine. Items can be `ComparisonFilter` or `CompoundFilter`." + }) +}).annotate({ "title": "Compound Filter", "description": "Combine multiple filters using `and` or `or`." }) +export type CreateCompletionResponse = { + readonly "id": string + readonly "choices": ReadonlyArray< + { + readonly "finish_reason": "stop" | "length" | "content_filter" + readonly "index": number + readonly "logprobs": { + readonly "text_offset"?: ReadonlyArray + readonly "token_logprobs"?: ReadonlyArray + readonly "tokens"?: ReadonlyArray + readonly "top_logprobs"?: ReadonlyArray<{}> + } | null + readonly "text": string + } + > + readonly "created": number + readonly "model": string + readonly "system_fingerprint"?: string + readonly "object": "text_completion" + readonly "usage"?: CompletionUsage +} +export const CreateCompletionResponse = Schema.Struct({ + "id": Schema.String.annotate({ "description": "A unique identifier for the completion." }), + "choices": Schema.Array(Schema.Struct({ + "finish_reason": Schema.Literals(["stop", "length", "content_filter"]).annotate({ + "description": + "The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\nor `content_filter` if content was omitted due to a flag from our content filters.\n" + }), + "index": Schema.Number.check(Schema.isInt()), + "logprobs": Schema.Union([ + Schema.Struct({ + "text_offset": Schema.optionalKey(Schema.Array(Schema.Number.check(Schema.isInt()))), + "token_logprobs": Schema.optionalKey(Schema.Array(Schema.Number.check(Schema.isFinite()))), + "tokens": Schema.optionalKey(Schema.Array(Schema.String)), + "top_logprobs": Schema.optionalKey(Schema.Array(Schema.Struct({}))) + }), + Schema.Null + ]), + "text": Schema.String + })).annotate({ "description": "The list of completion choices the model generated for the input prompt." }), + "created": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the completion was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "model": Schema.String.annotate({ "description": "The model used for completion." }), + "system_fingerprint": Schema.optionalKey( + Schema.String.annotate({ + "description": + "This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" + }) + ), + "object": Schema.Literal("text_completion").annotate({ + "description": "The object type, which is always \"text_completion\"" + }), + "usage": Schema.optionalKey(CompletionUsage) +}).annotate({ + "description": + "Represents a completion response from the API. Note: both the streamed and non-streamed response objects share the same shape (unlike the chat endpoint).\n" +}) +export type ContainerFileListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const ContainerFileListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The type of object returned, must be 'list'." }), + "data": Schema.Array(ContainerFileResource).annotate({ "description": "A list of container files." }), + "first_id": Schema.String.annotate({ "description": "The ID of the first file in the list." }), + "last_id": Schema.String.annotate({ "description": "The ID of the last file in the list." }), + "has_more": Schema.Boolean.annotate({ "description": "Whether there are more files available." }) +}) +export type ContainerListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const ContainerListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The type of object returned, must be 'list'." }), + "data": Schema.Array(ContainerResource).annotate({ "description": "A list of containers." }), + "first_id": Schema.String.annotate({ "description": "The ID of the first container in the list." }), + "last_id": Schema.String.annotate({ "description": "The ID of the last container in the list." }), + "has_more": Schema.Boolean.annotate({ "description": "Whether there are more containers available." }) +}) +export type CreateEmbeddingResponse = { + readonly "data": ReadonlyArray + readonly "model": string + readonly "object": "list" + readonly "usage": { readonly "prompt_tokens": number; readonly "total_tokens": number } +} +export const CreateEmbeddingResponse = Schema.Struct({ + "data": Schema.Array(Embedding).annotate({ "description": "The list of embeddings generated by the model." }), + "model": Schema.String.annotate({ "description": "The name of the model used to generate the embedding." }), + "object": Schema.Literal("list").annotate({ "description": "The object type, which is always \"list\"." }), + "usage": Schema.Struct({ + "prompt_tokens": Schema.Number.annotate({ "description": "The number of tokens used by the prompt." }).check( + Schema.isInt() + ), + "total_tokens": Schema.Number.annotate({ "description": "The total number of tokens used by the request." }).check( + Schema.isInt() + ) + }).annotate({ "description": "The usage information for the request." }) +}) +export type ErrorEvent = { readonly "event": "error"; readonly "data": Error } +export const ErrorEvent = Schema.Struct({ "event": Schema.Literal("error"), "data": Error }).annotate({ + "description": + "Occurs when an [error](/docs/guides/error-codes#api-errors) occurs. This can happen due to an internal server error or a timeout." +}) +export type ErrorResponse = { readonly "error": Error } +export const ErrorResponse = Schema.Struct({ "error": Error }) +export type EvalRunOutputItem = { + readonly "object": "eval.run.output_item" + readonly "id": string + readonly "run_id": string + readonly "eval_id": string + readonly "created_at": number + readonly "status": string + readonly "datasource_item_id": number + readonly "datasource_item": {} + readonly "results": ReadonlyArray + readonly "sample": { + readonly "input": ReadonlyArray<{ readonly "role": string; readonly "content": string }> + readonly "output": ReadonlyArray<{ readonly "role"?: string; readonly "content"?: string }> + readonly "finish_reason": string + readonly "model": string + readonly "usage": { + readonly "total_tokens": number + readonly "completion_tokens": number + readonly "prompt_tokens": number + readonly "cached_tokens": number + } + readonly "error": EvalApiError + readonly "temperature": number + readonly "max_completion_tokens": number + readonly "top_p": number + readonly "seed": number + } +} +export const EvalRunOutputItem = Schema.Struct({ + "object": Schema.Literal("eval.run.output_item").annotate({ + "description": "The type of the object. Always \"eval.run.output_item\"." + }), + "id": Schema.String.annotate({ "description": "Unique identifier for the evaluation run output item." }), + "run_id": Schema.String.annotate({ + "description": "The identifier of the evaluation run associated with this output item." + }), + "eval_id": Schema.String.annotate({ "description": "The identifier of the evaluation group." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the evaluation run was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "status": Schema.String.annotate({ "description": "The status of the evaluation run." }), + "datasource_item_id": Schema.Number.annotate({ "description": "The identifier for the data source item." }).check( + Schema.isInt() + ), + "datasource_item": Schema.Struct({}).annotate({ "description": "Details of the input data source item." }), + "results": Schema.Array(EvalRunOutputItemResult).annotate({ + "description": "A list of grader results for this output item." + }), + "sample": Schema.Struct({ + "input": Schema.Array( + Schema.Struct({ + "role": Schema.String.annotate({ + "description": "The role of the message sender (e.g., system, user, developer)." + }), + "content": Schema.String.annotate({ "description": "The content of the message." }) + }).annotate({ "description": "An input message." }) + ).annotate({ "description": "An array of input messages." }), + "output": Schema.Array( + Schema.Struct({ + "role": Schema.optionalKey( + Schema.String.annotate({ + "description": "The role of the message (e.g. \"system\", \"assistant\", \"user\")." + }) + ), + "content": Schema.optionalKey(Schema.String.annotate({ "description": "The content of the message." })) + }) + ).annotate({ "description": "An array of output messages." }), + "finish_reason": Schema.String.annotate({ "description": "The reason why the sample generation was finished." }), + "model": Schema.String.annotate({ "description": "The model used for generating the sample." }), + "usage": Schema.Struct({ + "total_tokens": Schema.Number.annotate({ "description": "The total number of tokens used." }).check( + Schema.isInt() + ), + "completion_tokens": Schema.Number.annotate({ "description": "The number of completion tokens generated." }) + .check(Schema.isInt()), + "prompt_tokens": Schema.Number.annotate({ "description": "The number of prompt tokens used." }).check( + Schema.isInt() + ), + "cached_tokens": Schema.Number.annotate({ "description": "The number of tokens retrieved from cache." }).check( + Schema.isInt() + ) + }).annotate({ "description": "Token usage details for the sample." }), + "error": EvalApiError, + "temperature": Schema.Number.annotate({ "description": "The sampling temperature used." }).check(Schema.isFinite()), + "max_completion_tokens": Schema.Number.annotate({ + "description": "The maximum number of tokens allowed for completion." + }).check(Schema.isInt()), + "top_p": Schema.Number.annotate({ "description": "The top_p value used for sampling." }).check(Schema.isFinite()), + "seed": Schema.Number.annotate({ "description": "The seed used for generating the sample." }).check(Schema.isInt()) + }).annotate({ "description": "A sample containing the input and output of the evaluation run." }) +}).annotate({ "title": "EvalRunOutputItem", "description": "A schema representing an evaluation run output item.\n" }) +export type CreateFileRequest = { + readonly "file": string + readonly "purpose": "assistants" | "batch" | "fine-tune" | "vision" | "user_data" | "evals" + readonly "expires_after"?: FileExpirationAfter +} +export const CreateFileRequest = Schema.Struct({ + "file": Schema.String.annotate({ + "description": "The File object (not file name) to be uploaded.\n", + "format": "binary" + }), + "purpose": Schema.Literals(["assistants", "batch", "fine-tune", "vision", "user_data", "evals"]).annotate({ + "description": + "The intended purpose of the uploaded file. One of:\n- `assistants`: Used in the Assistants API\n- `batch`: Used in the Batch API\n- `fine-tune`: Used for fine-tuning\n- `vision`: Images used for vision fine-tuning\n- `user_data`: Flexible file type for any purpose\n- `evals`: Used for eval data sets\n" + }), + "expires_after": Schema.optionalKey(FileExpirationAfter) +}) +export type CreateUploadRequest = { + readonly "filename": string + readonly "purpose": "assistants" | "batch" | "fine-tune" | "vision" + readonly "bytes": number + readonly "mime_type": string + readonly "expires_after"?: FileExpirationAfter +} +export const CreateUploadRequest = Schema.Struct({ + "filename": Schema.String.annotate({ "description": "The name of the file to upload.\n" }), + "purpose": Schema.Literals(["assistants", "batch", "fine-tune", "vision"]).annotate({ + "description": + "The intended purpose of the uploaded file.\n\nSee the [documentation on File\npurposes](/docs/api-reference/files/create#files-create-purpose).\n" + }), + "bytes": Schema.Number.annotate({ "description": "The number of bytes in the file you are uploading.\n" }).check( + Schema.isInt() + ), + "mime_type": Schema.String.annotate({ + "description": + "The MIME type of the file.\n\n\nThis must fall within the supported MIME types for your file purpose. See\nthe supported MIME types for assistants and vision.\n" + }), + "expires_after": Schema.optionalKey(FileExpirationAfter) +}) +export type FileSearchRankingOptions = { readonly "ranker"?: FileSearchRanker; readonly "score_threshold": number } +export const FileSearchRankingOptions = Schema.Struct({ + "ranker": Schema.optionalKey(FileSearchRanker), + "score_threshold": Schema.Number.annotate({ + "description": + "The score threshold for the file search. All values must be a floating point number between 0 and 1." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) +}).annotate({ + "title": "File search tool call ranking options", + "description": + "The ranking options for the file search. If not specified, the file search tool will use the `auto` ranker and a score_threshold of 0.\n\nSee the [file search tool documentation](/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n" +}) +export type RunStepDetailsToolCallsFileSearchRankingOptionsObject = { + readonly "ranker": FileSearchRanker + readonly "score_threshold": number +} +export const RunStepDetailsToolCallsFileSearchRankingOptionsObject = Schema.Struct({ + "ranker": FileSearchRanker, + "score_threshold": Schema.Number.annotate({ + "description": + "The score threshold for the file search. All values must be a floating point number between 0 and 1." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)) +}).annotate({ + "title": "File search tool call ranking options", + "description": "The ranking options for the file search." +}) +export type FineTuneDPOMethod = { readonly "hyperparameters"?: FineTuneDPOHyperparameters } +export const FineTuneDPOMethod = Schema.Struct({ "hyperparameters": Schema.optionalKey(FineTuneDPOHyperparameters) }) + .annotate({ "description": "Configuration for the DPO fine-tuning method." }) +export type FineTuneSupervisedMethod = { readonly "hyperparameters"?: FineTuneSupervisedHyperparameters } +export const FineTuneSupervisedMethod = Schema.Struct({ + "hyperparameters": Schema.optionalKey(FineTuneSupervisedHyperparameters) +}).annotate({ "description": "Configuration for the supervised fine-tuning method." }) +export type ListFineTuningCheckpointPermissionResponse = { + readonly "data": ReadonlyArray + readonly "object": "list" + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const ListFineTuningCheckpointPermissionResponse = Schema.Struct({ + "data": Schema.Array(FineTuningCheckpointPermission), + "object": Schema.Literal("list"), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type ListFineTuningJobCheckpointsResponse = { + readonly "data": ReadonlyArray + readonly "object": "list" + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const ListFineTuningJobCheckpointsResponse = Schema.Struct({ + "data": Schema.Array(FineTuningJobCheckpoint), + "object": Schema.Literal("list"), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type ListFineTuningJobEventsResponse = { + readonly "data": ReadonlyArray + readonly "object": "list" + readonly "has_more": boolean +} +export const ListFineTuningJobEventsResponse = Schema.Struct({ + "data": Schema.Array(FineTuningJobEvent), + "object": Schema.Literal("list"), + "has_more": Schema.Boolean +}) +export type ChatCompletionFunctions = { + readonly "description"?: string + readonly "name": string + readonly "parameters"?: FunctionParameters +} +export const ChatCompletionFunctions = Schema.Struct({ + "description": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A description of what the function does, used by the model to choose when and how to call the function." + }) + ), + "name": Schema.String.annotate({ + "description": + "The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." + }), + "parameters": Schema.optionalKey(FunctionParameters) +}) +export type FunctionObject = { + readonly "description"?: string + readonly "name": string + readonly "parameters"?: FunctionParameters + readonly "strict"?: boolean | null +} +export const FunctionObject = Schema.Struct({ + "description": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A description of what the function does, used by the model to choose when and how to call the function." + }) + ), + "name": Schema.String.annotate({ + "description": + "The name of the function to be called. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64." + }), + "parameters": Schema.optionalKey(FunctionParameters), + "strict": Schema.optionalKey(Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Whether to enable strict schema adherence when generating the function call. If set to true, the model will follow the exact schema defined in the `parameters` field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn more about Structured Outputs in the [function calling guide](/docs/guides/function-calling)." + }), + Schema.Null + ])) +}) +export type GroupListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next": string | null +} +export const GroupListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "Always `list`." }), + "data": Schema.Array(GroupResponse).annotate({ "description": "Groups returned in the current page." }), + "has_more": Schema.Boolean.annotate({ "description": "Whether additional groups are available when paginating." }), + "next": Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "Cursor to fetch the next page of results, or `null` if there are no more results." + }) +}).annotate({ "description": "Paginated list of organization groups." }) +export type UserListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next": string | null +} +export const UserListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "Always `list`." }), + "data": Schema.Array(GroupUser).annotate({ "description": "Users in the current page." }), + "has_more": Schema.Boolean.annotate({ "description": "Whether more users are available when paginating." }), + "next": Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "Cursor to fetch the next page of results, or `null` when no further users are available." + }) +}).annotate({ "description": "Paginated list of user objects returned when inspecting group membership." }) +export type ProjectHostedToolPermissions = { + readonly "file_search": HostedToolPermission + readonly "web_search": HostedToolPermission + readonly "image_generation": HostedToolPermission + readonly "mcp": HostedToolPermission + readonly "code_interpreter": HostedToolPermission +} +export const ProjectHostedToolPermissions = Schema.Struct({ + "file_search": HostedToolPermission, + "web_search": HostedToolPermission, + "image_generation": HostedToolPermission, + "mcp": HostedToolPermission, + "code_interpreter": HostedToolPermission +}).annotate({ "description": "Represents hosted tool permissions for a project." }) +export type ProjectHostedToolPermissionsUpdateRequest = { + readonly "file_search"?: HostedToolPermissionUpdate | null + readonly "web_search"?: HostedToolPermissionUpdate | null + readonly "image_generation"?: HostedToolPermissionUpdate | null + readonly "mcp"?: HostedToolPermissionUpdate | null + readonly "code_interpreter"?: HostedToolPermissionUpdate | null +} +export const ProjectHostedToolPermissionsUpdateRequest = Schema.Struct({ + "file_search": Schema.optionalKey( + Schema.Union([HostedToolPermissionUpdate, Schema.Null]).annotate({ + "description": "The file search permission update." + }) + ), + "web_search": Schema.optionalKey( + Schema.Union([HostedToolPermissionUpdate, Schema.Null]).annotate({ + "description": "The web search permission update." + }) + ), + "image_generation": Schema.optionalKey( + Schema.Union([HostedToolPermissionUpdate, Schema.Null]).annotate({ + "description": "The image generation permission update." + }) + ), + "mcp": Schema.optionalKey( + Schema.Union([HostedToolPermissionUpdate, Schema.Null]).annotate({ "description": "The MCP permission update." }) + ), + "code_interpreter": Schema.optionalKey( + Schema.Union([HostedToolPermissionUpdate, Schema.Null]).annotate({ + "description": "The code interpreter permission update." + }) + ) +}) +export type ImageEditCompletedEvent = { + readonly "type": "image_edit.completed" + readonly "b64_json": string + readonly "created_at": number + readonly "size": "1024x1024" | "1024x1536" | "1536x1024" | "auto" + readonly "quality": "low" | "medium" | "high" | "auto" + readonly "background": "transparent" | "opaque" | "auto" + readonly "output_format": "png" | "webp" | "jpeg" + readonly "usage": ImagesUsage +} +export const ImageEditCompletedEvent = Schema.Struct({ + "type": Schema.Literal("image_edit.completed").annotate({ + "description": "The type of the event. Always `image_edit.completed`.\n" + }), + "b64_json": Schema.String.annotate({ + "description": "Base64-encoded final edited image data, suitable for rendering as an image.\n" + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp when the event was created.\n", + "format": "unixtime" + }).check(Schema.isInt()), + "size": Schema.Literals(["1024x1024", "1024x1536", "1536x1024", "auto"]).annotate({ + "description": "The size of the edited image.\n" + }), + "quality": Schema.Literals(["low", "medium", "high", "auto"]).annotate({ + "description": "The quality setting for the edited image.\n" + }), + "background": Schema.Literals(["transparent", "opaque", "auto"]).annotate({ + "description": "The background setting for the edited image.\n" + }), + "output_format": Schema.Literals(["png", "webp", "jpeg"]).annotate({ + "description": "The output format for the edited image.\n" + }), + "usage": ImagesUsage +}).annotate({ "description": "Emitted when image editing has completed and the final image is available.\n" }) +export type ImageGenCompletedEvent = { + readonly "type": "image_generation.completed" + readonly "b64_json": string + readonly "created_at": number + readonly "size": "1024x1024" | "1024x1536" | "1536x1024" | "auto" + readonly "quality": "low" | "medium" | "high" | "auto" + readonly "background": "transparent" | "opaque" | "auto" + readonly "output_format": "png" | "webp" | "jpeg" + readonly "usage": ImagesUsage +} +export const ImageGenCompletedEvent = Schema.Struct({ + "type": Schema.Literal("image_generation.completed").annotate({ + "description": "The type of the event. Always `image_generation.completed`.\n" + }), + "b64_json": Schema.String.annotate({ + "description": "Base64-encoded image data, suitable for rendering as an image.\n" + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp when the event was created.\n", + "format": "unixtime" + }).check(Schema.isInt()), + "size": Schema.Literals(["1024x1024", "1024x1536", "1536x1024", "auto"]).annotate({ + "description": "The size of the generated image.\n" + }), + "quality": Schema.Literals(["low", "medium", "high", "auto"]).annotate({ + "description": "The quality setting for the generated image.\n" + }), + "background": Schema.Literals(["transparent", "opaque", "auto"]).annotate({ + "description": "The background setting for the generated image.\n" + }), + "output_format": Schema.Literals(["png", "webp", "jpeg"]).annotate({ + "description": "The output format for the generated image.\n" + }), + "usage": ImagesUsage +}).annotate({ "description": "Emitted when image generation has completed and the final image is available.\n" }) +export type InviteListResponse = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const InviteListResponse = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The object type, which is always `list`" }), + "data": Schema.Array(Invite), + "first_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "The first `invite_id` in the retrieved `list`" + }) + ), + "last_id": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "The last `invite_id` in the retrieved `list`" + }) + ), + "has_more": Schema.Boolean.annotate({ + "description": "The `has_more` property is used for pagination to indicate there are additional results." + }) +}) +export type RealtimeServerEventConversationItemInputAudioTranscriptionCompleted = { + readonly "event_id": string + readonly "type": "conversation.item.input_audio_transcription.completed" + readonly "item_id": string + readonly "content_index": number + readonly "transcript": string + readonly "logprobs"?: ReadonlyArray | null + readonly "usage": { + readonly "type": "tokens" + readonly "input_tokens": number + readonly "input_token_details"?: { readonly "text_tokens"?: number; readonly "audio_tokens"?: number } + readonly "output_tokens": number + readonly "total_tokens": number + } | { readonly "type": "duration"; readonly "seconds": number } +} +export const RealtimeServerEventConversationItemInputAudioTranscriptionCompleted = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.input_audio_transcription.completed").annotate({ + "description": "The event type, must be\n`conversation.item.input_audio_transcription.completed`.\n" + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the item containing the audio that is being transcribed." + }), + "content_index": Schema.Number.annotate({ "description": "The index of the content part containing the audio." }) + .check(Schema.isInt()), + "transcript": Schema.String.annotate({ "description": "The transcribed text." }), + "logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Array(LogProbProperties).annotate({ "description": "The log probabilities of the transcription." }), + Schema.Null + ]) + ), + "usage": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("tokens").annotate({ + "description": "The type of the usage object. Always `tokens` for this variant." + }), + "input_tokens": Schema.Number.annotate({ "description": "Number of input tokens billed for this request." }) + .check(Schema.isInt()), + "input_token_details": Schema.optionalKey( + Schema.Struct({ + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Number of text tokens billed for this request." }).check( + Schema.isInt() + ) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Number of audio tokens billed for this request." }).check( + Schema.isInt() + ) + ) + }).annotate({ "description": "Details about the input tokens billed for this request." }) + ), + "output_tokens": Schema.Number.annotate({ "description": "Number of output tokens generated." }).check( + Schema.isInt() + ), + "total_tokens": Schema.Number.annotate({ "description": "Total number of tokens used (input + output)." }).check( + Schema.isInt() + ) + }).annotate({ + "title": "Token Usage", + "description": + "Usage statistics for the transcription, this is billed according to the ASR model's pricing rather than the realtime model's pricing." + }), + Schema.Struct({ + "type": Schema.Literal("duration").annotate({ + "description": "The type of the usage object. Always `duration` for this variant." + }), + "seconds": Schema.Number.annotate({ + "description": "Duration of the input audio in seconds.", + "format": "double" + }).check(Schema.isFinite()) + }).annotate({ + "title": "Duration Usage", + "description": + "Usage statistics for the transcription, this is billed according to the ASR model's pricing rather than the realtime model's pricing." + }) + ], { mode: "oneOf" }) +}).annotate({ + "description": + "This event is the output of audio transcription for user audio written to the\nuser audio buffer. Transcription begins when the input audio buffer is\ncommitted by the client or server (when VAD is enabled). Transcription runs\nasynchronously with Response creation, so this event may come before or after\nthe Response events.\n\nRealtime API models accept audio natively, and thus input transcription is a\nseparate process run on a separate ASR (Automatic Speech Recognition) model.\nThe transcript may diverge somewhat from the model's interpretation, and\nshould be treated as a rough guide.\n" +}) +export type RealtimeServerEventConversationItemInputAudioTranscriptionDelta = { + readonly "event_id": string + readonly "type": "conversation.item.input_audio_transcription.delta" + readonly "item_id": string + readonly "content_index"?: number + readonly "delta"?: string + readonly "logprobs"?: ReadonlyArray | null +} +export const RealtimeServerEventConversationItemInputAudioTranscriptionDelta = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.input_audio_transcription.delta").annotate({ + "description": "The event type, must be `conversation.item.input_audio_transcription.delta`." + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the item containing the audio that is being transcribed." + }), + "content_index": Schema.optionalKey( + Schema.Number.annotate({ "description": "The index of the content part in the item's content array." }).check( + Schema.isInt() + ) + ), + "delta": Schema.optionalKey(Schema.String.annotate({ "description": "The text delta." })), + "logprobs": Schema.optionalKey(Schema.Union([ + Schema.Array(LogProbProperties).annotate({ + "description": + "The log probabilities of the transcription. These can be enabled by configurating the session with `\"include\": [\"item.input_audio_transcription.logprobs\"]`. Each entry in the array corresponds a log probability of which token would be selected for this chunk of transcription. This can help to identify if it was possible there were multiple valid options for a given chunk of transcription." + }), + Schema.Null + ])) +}).annotate({ + "description": + "Returned when the text value of an input audio transcription content part is updated with incremental transcription results.\n" +}) +export type MCPListTools = { + readonly "type": "mcp_list_tools" + readonly "id": string + readonly "server_label": string + readonly "tools": ReadonlyArray + readonly "error"?: string | null +} +export const MCPListTools = Schema.Struct({ + "type": Schema.Literal("mcp_list_tools").annotate({ + "description": "The type of the item. Always `mcp_list_tools`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the list.\n" }), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server.\n" }), + "tools": Schema.Array(MCPListToolsTool).annotate({ "description": "The tools available on the server.\n" }), + "error": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "Error message if the server could not list tools.\n" }), + Schema.Null + ]) + ) +}).annotate({ "title": "MCP list tools", "description": "A list of tools available on an MCP server.\n" }) +export type RealtimeMCPListTools = { + readonly "type": "mcp_list_tools" + readonly "id"?: string + readonly "server_label": string + readonly "tools": ReadonlyArray +} +export const RealtimeMCPListTools = Schema.Struct({ + "type": Schema.Literal("mcp_list_tools").annotate({ + "description": "The type of the item. Always `mcp_list_tools`." + }), + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The unique ID of the list." })), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server." }), + "tools": Schema.Array(MCPListToolsTool).annotate({ "description": "The tools available on the server." }) +}).annotate({ + "title": "Realtime MCP list tools", + "description": "A Realtime item listing tools available on an MCP server.\n" +}) +export type MCPTool = { + readonly "type": "mcp" + readonly "server_label": string + readonly "server_url"?: string + readonly "connector_id"?: + | "connector_dropbox" + | "connector_gmail" + | "connector_googlecalendar" + | "connector_googledrive" + | "connector_microsoftteams" + | "connector_outlookcalendar" + | "connector_outlookemail" + | "connector_sharepoint" + readonly "authorization"?: string + readonly "server_description"?: string + readonly "headers"?: {} | null + readonly "allowed_tools"?: ReadonlyArray | MCPToolFilter | null + readonly "require_approval"?: + | { readonly "always"?: MCPToolFilter; readonly "never"?: MCPToolFilter } + | "always" + | "never" + | null + readonly "defer_loading"?: boolean +} +export const MCPTool = Schema.Struct({ + "type": Schema.Literal("mcp").annotate({ "description": "The type of the MCP tool. Always `mcp`." }), + "server_label": Schema.String.annotate({ + "description": "A label for this MCP server, used to identify it in tool calls.\n" + }), + "server_url": Schema.optionalKey( + Schema.String.annotate({ + "description": "The URL for the MCP server. One of `server_url` or `connector_id` must be\nprovided.\n", + "format": "uri" + }) + ), + "connector_id": Schema.optionalKey( + Schema.Literals([ + "connector_dropbox", + "connector_gmail", + "connector_googlecalendar", + "connector_googledrive", + "connector_microsoftteams", + "connector_outlookcalendar", + "connector_outlookemail", + "connector_sharepoint" + ]).annotate({ + "description": + "Identifier for service connectors, like those available in ChatGPT. One of\n`server_url` or `connector_id` must be provided. Learn more about service\nconnectors [here](/docs/guides/tools-remote-mcp#connectors).\n\nCurrently supported `connector_id` values are:\n\n- Dropbox: `connector_dropbox`\n- Gmail: `connector_gmail`\n- Google Calendar: `connector_googlecalendar`\n- Google Drive: `connector_googledrive`\n- Microsoft Teams: `connector_microsoftteams`\n- Outlook Calendar: `connector_outlookcalendar`\n- Outlook Email: `connector_outlookemail`\n- SharePoint: `connector_sharepoint`\n" + }) + ), + "authorization": Schema.optionalKey( + Schema.String.annotate({ + "description": + "An OAuth access token that can be used with a remote MCP server, either\nwith a custom MCP server URL or a service connector. Your application\nmust handle the OAuth authorization flow and provide the token here.\n" + }) + ), + "server_description": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional description of the MCP server, used to provide more context.\n" }) + ), + "headers": Schema.optionalKey( + Schema.Union([ + Schema.Struct({}).annotate({ + "description": "Optional HTTP headers to send to the MCP server. Use for authentication\nor other purposes.\n" + }), + Schema.Null + ]) + ), + "allowed_tools": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Array(Schema.String).annotate({ + "title": "MCP allowed tools", + "description": "A string array of allowed tool names" + }), + MCPToolFilter + ], { mode: "oneOf" }).annotate({ "description": "List of allowed tool names or a filter object.\n" }), + Schema.Null + ]) + ), + "require_approval": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Struct({ "always": Schema.optionalKey(MCPToolFilter), "never": Schema.optionalKey(MCPToolFilter) }) + .annotate({ + "title": "MCP tool approval filter", + "description": + "Specify which of the MCP server's tools require approval. Can be\n`always`, `never`, or a filter object associated with tools\nthat require approval.\n" + }), + Schema.Literals(["always", "never"]).annotate({ + "title": "MCP tool approval setting", + "description": + "Specify a single approval policy for all tools. One of `always` or\n`never`. When set to `always`, all tools will require approval. When\nset to `never`, all tools will not require approval.\n" + }) + ], { mode: "oneOf" }).annotate({ "description": "Specify which of the MCP server's tools require approval." }), + Schema.Null + ]) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether this MCP tool is deferred and discovered via tool search.\n" }) + ) +}).annotate({ + "title": "MCP tool", + "description": + "Give the model access to additional tools via remote Model Context Protocol\n(MCP) servers. [Learn more about MCP](/docs/guides/tools-remote-mcp).\n" +}) +export type MessageContentTextObject = { + readonly "type": "text" + readonly "text": { + readonly "value": string + readonly "annotations": ReadonlyArray< + MessageContentTextAnnotationsFileCitationObject | MessageContentTextAnnotationsFilePathObject + > + } +} +export const MessageContentTextObject = Schema.Struct({ + "type": Schema.Literal("text").annotate({ "description": "Always `text`." }), + "text": Schema.Struct({ + "value": Schema.String.annotate({ "description": "The data that makes up the text." }), + "annotations": Schema.Array( + Schema.Union([MessageContentTextAnnotationsFileCitationObject, MessageContentTextAnnotationsFilePathObject], { + mode: "oneOf" + }) + ) + }) +}).annotate({ "title": "Text", "description": "The text content that is part of a message." }) +export type MessageDeltaContentTextObject = { + readonly "index": number + readonly "type": "text" + readonly "text"?: { + readonly "value"?: string + readonly "annotations"?: ReadonlyArray< + MessageDeltaContentTextAnnotationsFileCitationObject | MessageDeltaContentTextAnnotationsFilePathObject + > + } +} +export const MessageDeltaContentTextObject = Schema.Struct({ + "index": Schema.Number.annotate({ "description": "The index of the content part in the message." }).check( + Schema.isInt() + ), + "type": Schema.Literal("text").annotate({ "description": "Always `text`." }), + "text": Schema.optionalKey(Schema.Struct({ + "value": Schema.optionalKey(Schema.String.annotate({ "description": "The data that makes up the text." })), + "annotations": Schema.optionalKey( + Schema.Array( + Schema.Union([ + MessageDeltaContentTextAnnotationsFileCitationObject, + MessageDeltaContentTextAnnotationsFilePathObject + ], { mode: "oneOf" }) + ) + ) + })) +}).annotate({ "title": "Text", "description": "The text content that is part of a message." }) +export type Batch = { + readonly "id": string + readonly "object": "batch" + readonly "endpoint": string + readonly "model"?: string + readonly "errors"?: { + readonly "object"?: string + readonly "data"?: ReadonlyArray< + { + readonly "code"?: string + readonly "message"?: string + readonly "param"?: string | null + readonly "line"?: number | null + } + > + } + readonly "input_file_id": string + readonly "completion_window": string + readonly "status": + | "validating" + | "failed" + | "in_progress" + | "finalizing" + | "completed" + | "expired" + | "cancelling" + | "cancelled" + readonly "output_file_id"?: string + readonly "error_file_id"?: string + readonly "created_at": number + readonly "in_progress_at"?: number + readonly "expires_at"?: number + readonly "finalizing_at"?: number + readonly "completed_at"?: number + readonly "failed_at"?: number + readonly "expired_at"?: number + readonly "cancelling_at"?: number + readonly "cancelled_at"?: number + readonly "request_counts"?: { readonly "total": number; readonly "completed": number; readonly "failed": number } + readonly "usage"?: { + readonly "input_tokens": number + readonly "input_tokens_details": { readonly "cached_tokens": number } + readonly "output_tokens": number + readonly "output_tokens_details": { readonly "reasoning_tokens": number } + readonly "total_tokens": number + } + readonly "metadata"?: Metadata +} +export const Batch = Schema.Struct({ + "id": Schema.String, + "object": Schema.Literal("batch").annotate({ "description": "The object type, which is always `batch`." }), + "endpoint": Schema.String.annotate({ "description": "The OpenAI API endpoint used by the batch." }), + "model": Schema.optionalKey(Schema.String.annotate({ + "description": + "Model ID used to process the batch, like `gpt-5-2025-08-07`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model\nguide](/docs/models) to browse and compare available models.\n" + })), + "errors": Schema.optionalKey(Schema.Struct({ + "object": Schema.optionalKey(Schema.String.annotate({ "description": "The object type, which is always `list`." })), + "data": Schema.optionalKey(Schema.Array(Schema.Struct({ + "code": Schema.optionalKey( + Schema.String.annotate({ "description": "An error code identifying the error type." }) + ), + "message": Schema.optionalKey( + Schema.String.annotate({ "description": "A human-readable message providing more details about the error." }) + ), + "param": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The name of the parameter that caused the error, if applicable." }), + Schema.Null + ]) + ), + "line": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The line number of the input file where the error occurred, if applicable." + }).check(Schema.isInt()), + Schema.Null + ]) + ) + }))) + })), + "input_file_id": Schema.String.annotate({ "description": "The ID of the input file for the batch." }), + "completion_window": Schema.String.annotate({ + "description": "The time frame within which the batch should be processed." + }), + "status": Schema.Literals([ + "validating", + "failed", + "in_progress", + "finalizing", + "completed", + "expired", + "cancelling", + "cancelled" + ]).annotate({ "description": "The current status of the batch." }), + "output_file_id": Schema.optionalKey( + Schema.String.annotate({ + "description": "The ID of the file containing the outputs of successfully executed requests." + }) + ), + "error_file_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the file containing the outputs of requests with errors." }) + ), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the batch was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "in_progress_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the batch started processing.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "expires_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the batch will expire.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "finalizing_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the batch started finalizing.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "completed_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the batch was completed.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "failed_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the batch failed.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "expired_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the batch expired.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "cancelling_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the batch started cancelling.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "cancelled_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the batch was cancelled.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "request_counts": Schema.optionalKey( + Schema.Struct({ + "total": Schema.Number.annotate({ "description": "Total number of requests in the batch." }).check( + Schema.isInt() + ), + "completed": Schema.Number.annotate({ + "description": "Number of requests that have been completed successfully." + }).check(Schema.isInt()), + "failed": Schema.Number.annotate({ "description": "Number of requests that have failed." }).check(Schema.isInt()) + }).annotate({ "description": "The request counts for different statuses within the batch." }) + ), + "usage": Schema.optionalKey( + Schema.Struct({ + "input_tokens": Schema.Number.annotate({ "description": "The number of input tokens." }).check(Schema.isInt()), + "input_tokens_details": Schema.Struct({ + "cached_tokens": Schema.Number.annotate({ + "description": + "The number of tokens that were retrieved from the cache. [More on\nprompt caching](/docs/guides/prompt-caching).\n" + }).check(Schema.isInt()) + }).annotate({ "description": "A detailed breakdown of the input tokens." }), + "output_tokens": Schema.Number.annotate({ "description": "The number of output tokens." }).check(Schema.isInt()), + "output_tokens_details": Schema.Struct({ + "reasoning_tokens": Schema.Number.annotate({ "description": "The number of reasoning tokens." }).check( + Schema.isInt() + ) + }).annotate({ "description": "A detailed breakdown of the output tokens." }), + "total_tokens": Schema.Number.annotate({ "description": "The total number of tokens used." }).check( + Schema.isInt() + ) + }).annotate({ + "description": + "Represents token usage details including input tokens, output tokens, a\nbreakdown of output tokens, and the total tokens used. Only populated on\nbatches created after September 7, 2025.\n" + }) + ), + "metadata": Schema.optionalKey(Metadata) +}) +export type CreateMessageRequest = { + readonly "role": "user" | "assistant" + readonly "content": + | string + | ReadonlyArray + readonly "attachments"?: + | ReadonlyArray< + { + readonly "file_id"?: string + readonly "tools"?: ReadonlyArray + } + > + | null + readonly "metadata"?: Metadata +} +export const CreateMessageRequest = Schema.Struct({ + "role": Schema.Literals(["user", "assistant"]).annotate({ + "description": + "The role of the entity that is creating the message. Allowed values include:\n- `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.\n- `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.\n" + }), + "content": Schema.Union([ + Schema.String.annotate({ "title": "Text content", "description": "The text contents of the message." }), + Schema.Array( + Schema.Union([MessageContentImageFileObject, MessageContentImageUrlObject, MessageRequestContentTextObject], { + mode: "oneOf" + }) + ).annotate({ + "title": "Array of content parts", + "description": + "An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](/docs/models)." + }).check(Schema.isMinLength(1)) + ], { mode: "oneOf" }), + "attachments": Schema.optionalKey(Schema.Union([ + Schema.Array(Schema.Struct({ + "file_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the file to attach to the message." }) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Union([AssistantToolsCode, AssistantToolsFileSearchTypeOnly], { mode: "oneOf" })).annotate({ + "description": "The tools to add this file to." + }) + ) + })).annotate({ "description": "A list of files attached to the message, and the tools they should be added to." }), + Schema.Null + ])), + "metadata": Schema.optionalKey(Metadata) +}) +export type EvalStoredCompletionsSource = { + readonly "type": "stored_completions" + readonly "metadata"?: Metadata + readonly "model"?: string | null + readonly "created_after"?: number | null + readonly "created_before"?: number | null + readonly "limit"?: number | null +} +export const EvalStoredCompletionsSource = Schema.Struct({ + "type": Schema.Literal("stored_completions").annotate({ + "description": "The type of source. Always `stored_completions`." + }), + "metadata": Schema.optionalKey(Metadata), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "An optional model to filter by (e.g., 'gpt-4o')." }), + Schema.Null + ]) + ), + "created_after": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "An optional Unix timestamp to filter items created after this time." }) + .check(Schema.isInt()), + Schema.Null + ]) + ), + "created_before": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "An optional Unix timestamp to filter items created before this time." }) + .check(Schema.isInt()), + Schema.Null + ]) + ), + "limit": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "An optional maximum number of items to return." }).check(Schema.isInt()), + Schema.Null + ]) + ) +}).annotate({ + "title": "StoredCompletionsRunDataSource", + "description": "A StoredCompletionsRunDataSource configuration describing a set of filters\n" +}) +export type ModifyMessageRequest = { readonly "metadata"?: Metadata } +export const ModifyMessageRequest = Schema.Struct({ "metadata": Schema.optionalKey(Metadata) }) +export type ModifyRunRequest = { readonly "metadata"?: Metadata } +export const ModifyRunRequest = Schema.Struct({ "metadata": Schema.optionalKey(Metadata) }) +export type ModifyThreadRequest = { + readonly "tool_resources"?: { + readonly "code_interpreter"?: { readonly "file_ids"?: ReadonlyArray } + readonly "file_search"?: { readonly "vector_store_ids"?: ReadonlyArray } + } | null + readonly "metadata"?: Metadata +} +export const ModifyThreadRequest = Schema.Struct({ + "tool_resources": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "code_interpreter": Schema.optionalKey(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n" + }).check(Schema.isMaxLength(20)) + ) + })), + "file_search": Schema.optionalKey(Schema.Struct({ + "vector_store_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n" + }).check(Schema.isMaxLength(1)) + ) + })) + }).annotate({ + "description": + "A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + }), + Schema.Null + ])), + "metadata": Schema.optionalKey(Metadata) +}) +export type ThreadObject = { + readonly "id": string + readonly "object": "thread" + readonly "created_at": number + readonly "tool_resources": { + readonly "code_interpreter"?: { readonly "file_ids"?: ReadonlyArray } + readonly "file_search"?: { readonly "vector_store_ids"?: ReadonlyArray } + } | null + readonly "metadata": Metadata +} +export const ThreadObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints." }), + "object": Schema.Literal("thread").annotate({ "description": "The object type, which is always `thread`." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the thread was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "tool_resources": Schema.Union([ + Schema.Struct({ + "code_interpreter": Schema.optionalKey(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n" + }).check(Schema.isMaxLength(20)) + ) + })), + "file_search": Schema.optionalKey(Schema.Struct({ + "vector_store_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n" + }).check(Schema.isMaxLength(1)) + ) + })) + }).annotate({ + "description": + "A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + }), + Schema.Null + ]), + "metadata": Metadata +}).annotate({ + "title": "Thread", + "description": "Represents a thread that contains [messages](/docs/api-reference/messages)." +}) +export type UpdateVectorStoreRequest = { + readonly "name"?: string | null + readonly "expires_after"?: { readonly "anchor": "last_active_at"; readonly "days": number } + readonly "metadata"?: Metadata +} +export const UpdateVectorStoreRequest = Schema.Struct({ + "name": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ "description": "The name of the vector store." }) + ), + "expires_after": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "anchor": Schema.Literal("last_active_at").annotate({ + "description": + "Anchor timestamp after which the expiration policy applies. Supported anchors: `last_active_at`." + }), + "days": Schema.Number.annotate({ + "description": "The number of days after the anchor time that the vector store will expire." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(365)) + }).annotate({ + "title": "Vector store expiration policy", + "description": "The expiration policy for a vector store." + }) + ])), + "metadata": Schema.optionalKey(Metadata) +}) +export type ListModelsResponse = { readonly "object": "list"; readonly "data": ReadonlyArray } +export const ListModelsResponse = Schema.Struct({ "object": Schema.Literal("list"), "data": Schema.Array(Model) }) +export type ModelIdsResponses = + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" +export const ModelIdsResponses = Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) +]) +export type RealtimeTranscriptionSessionCreateRequest = { + readonly "turn_detection"?: { + readonly "type"?: "server_vad" + readonly "threshold"?: number + readonly "prefix_padding_ms"?: number + readonly "silence_duration_ms"?: number + } + readonly "input_audio_noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "input_audio_format"?: "pcm16" | "g711_ulaw" | "g711_alaw" + readonly "input_audio_transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + readonly "delay"?: "minimal" | "low" | "medium" | "high" | "xhigh" + } + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> +} +export const RealtimeTranscriptionSessionCreateRequest = Schema.Struct({ + "turn_detection": Schema.optionalKey( + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("server_vad").annotate({ + "description": + "Type of turn detection. Only `server_vad` is currently supported for transcription sessions.\n" + }) + ), + "threshold": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }).check(Schema.isFinite()) + ), + "prefix_padding_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }).check(Schema.isInt()) + ), + "silence_duration_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + }).check(Schema.isInt()) + ) + }).annotate({ + "description": + "Configuration for turn detection. Can be set to `null` to turn off. Server VAD means that the model will detect the start and end of speech based on audio volume and respond at the end of user speech.\n" + }) + ), + "input_audio_noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": + "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n" + }) + ), + "input_audio_format": Schema.optionalKey( + Schema.Literals(["pcm16", "g711_ulaw", "g711_alaw"]).annotate({ + "description": + "The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\nsingle channel (mono), and little-endian byte order.\n" + }) + ), + "input_audio_transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n" + }) + ), + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }) + ), + "prompt": Schema.optionalKey(Schema.String.annotate({ + "description": + "An optional text to guide the model's style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text string, for example \"expect words related to technology\".\nPrompt is not supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + })), + "delay": Schema.optionalKey( + Schema.Literals(["minimal", "low", "medium", "high", "xhigh"]).annotate({ + "description": + "Controls how long the model waits before emitting transcription text.\nHigher values can improve transcription accuracy at the cost of latency.\nOnly supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + }) + ) + }).annotate({ + "description": + "Configuration for input audio transcription. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n" + }) + ), + "include": Schema.optionalKey( + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "The set of items to include in the transcription. Current available items are:\n`item.input_audio_transcription.logprobs`\n" + }) + ) +}).annotate({ + "title": "Realtime transcription session configuration", + "description": "Realtime transcription session object configuration." +}) +export type RealtimeTranslationClientEventSessionUpdate = { + readonly "event_id"?: string + readonly "type": "session.update" + readonly "session": { + readonly "audio"?: { + readonly "input"?: { + readonly "transcription"?: { readonly "model": string } | null + readonly "noise_reduction"?: { readonly "type": NoiseReductionType } | null + } + readonly "output"?: { readonly "language"?: string } + } + } +} +export const RealtimeTranslationClientEventSessionUpdate = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("session.update").annotate({ "description": "The event type, must be `session.update`." }), + "session": Schema.Struct({ + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "transcription": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "model": Schema.String.annotate({ + "description": "The transcription model to use for source transcript deltas." + }) + }).annotate({ + "description": + "Optional source-language transcription. When configured, the server emits\n`session.input_transcript.delta` events. Translation itself still runs from\nthe input audio stream.\n" + }), + Schema.Null + ]) + ), + "noise_reduction": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": NoiseReductionType }).annotate({ + "description": "Optional input noise reduction. Set to `null` to disable it.\n" + }), + Schema.Null + ]) + ) + })), + "output": Schema.optionalKey( + Schema.Struct({ + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": "Target language for translated output audio and transcript deltas.\n" + }) + ) + }) + ) + }).annotate({ "description": "Configuration for translation input and output audio.\n" }) + ) + }).annotate({ + "title": "Realtime translation session update", + "description": + "Translation session fields to update. The session `type` and `model` are set\nat creation and cannot be changed with `session.update`.\n" + }) +}).annotate({ + "description": + "Send this event to update the translation session configuration. Translation\nsessions support updates to `audio.output.language`, `audio.input.transcription`,\nand `audio.input.noise_reduction`.\n" +}) +export type RealtimeTranslationServerEventSessionCreated = { + readonly "event_id": string + readonly "type": "session.created" + readonly "session": { + readonly "id": string + readonly "type": "translation" + readonly "expires_at": number + readonly "model": string + readonly "audio": { + readonly "input"?: { + readonly "transcription"?: { readonly "model": string } | null + readonly "noise_reduction"?: { readonly "type": NoiseReductionType } | null + } + readonly "output"?: { readonly "language"?: string } + } + } +} +export const RealtimeTranslationServerEventSessionCreated = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("session.created").annotate({ "description": "The event type, must be `session.created`." }), + "session": Schema.Struct({ + "id": Schema.String.annotate({ + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }), + "type": Schema.Literal("translation").annotate({ + "description": "The session type. Always `translation` for Realtime translation sessions.\n" + }), + "expires_at": Schema.Number.annotate({ + "description": "Expiration timestamp for the session, in seconds since epoch.", + "format": "unixtime" + }).check(Schema.isInt()), + "model": Schema.String.annotate({ + "description": + "The Realtime translation model used for this session. This field is set at\nsession creation and cannot be changed with `session.update`.\n" + }), + "audio": Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "transcription": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "model": Schema.String.annotate({ + "description": "The transcription model used for source transcript deltas." + }) + }).annotate({ + "description": + "Optional source-language transcription. When configured, the server emits\n`session.input_transcript.delta` events. Translation itself still runs from\nthe input audio stream.\n" + }), + Schema.Null + ]) + ), + "noise_reduction": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": NoiseReductionType }).annotate({ + "description": "Optional input noise reduction.\n" + }), + Schema.Null + ]) + ) + })), + "output": Schema.optionalKey( + Schema.Struct({ + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": "Target language for translated output audio and transcript deltas.\n" + }) + ) + }) + ) + }).annotate({ "description": "Configuration for translation input and output audio.\n" }) + }).annotate({ "title": "Realtime translation session", "description": "The translation session configuration." }) +}).annotate({ + "description": + "Returned when a translation session is created. Emitted automatically when a\nnew connection is established as the first server event. This event contains\nthe default translation session configuration.\n" +}) +export type RealtimeTranslationServerEventSessionUpdated = { + readonly "event_id": string + readonly "type": "session.updated" + readonly "session": { + readonly "id": string + readonly "type": "translation" + readonly "expires_at": number + readonly "model": string + readonly "audio": { + readonly "input"?: { + readonly "transcription"?: { readonly "model": string } | null + readonly "noise_reduction"?: { readonly "type": NoiseReductionType } | null + } + readonly "output"?: { readonly "language"?: string } + } + } +} +export const RealtimeTranslationServerEventSessionUpdated = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("session.updated").annotate({ "description": "The event type, must be `session.updated`." }), + "session": Schema.Struct({ + "id": Schema.String.annotate({ + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }), + "type": Schema.Literal("translation").annotate({ + "description": "The session type. Always `translation` for Realtime translation sessions.\n" + }), + "expires_at": Schema.Number.annotate({ + "description": "Expiration timestamp for the session, in seconds since epoch.", + "format": "unixtime" + }).check(Schema.isInt()), + "model": Schema.String.annotate({ + "description": + "The Realtime translation model used for this session. This field is set at\nsession creation and cannot be changed with `session.update`.\n" + }), + "audio": Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "transcription": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "model": Schema.String.annotate({ + "description": "The transcription model used for source transcript deltas." + }) + }).annotate({ + "description": + "Optional source-language transcription. When configured, the server emits\n`session.input_transcript.delta` events. Translation itself still runs from\nthe input audio stream.\n" + }), + Schema.Null + ]) + ), + "noise_reduction": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": NoiseReductionType }).annotate({ + "description": "Optional input noise reduction.\n" + }), + Schema.Null + ]) + ) + })), + "output": Schema.optionalKey( + Schema.Struct({ + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": "Target language for translated output audio and transcript deltas.\n" + }) + ) + }) + ) + }).annotate({ "description": "Configuration for translation input and output audio.\n" }) + }).annotate({ "title": "Realtime translation session", "description": "The translation session configuration." }) +}).annotate({ + "description": + "Returned when a translation session is updated with a `session.update` event,\nunless there is an error.\n" +}) +export type RealtimeTranslationSession = { + readonly "id": string + readonly "type": "translation" + readonly "expires_at": number + readonly "model": string + readonly "audio": { + readonly "input"?: { + readonly "transcription"?: { readonly "model": string } | null + readonly "noise_reduction"?: { readonly "type": NoiseReductionType } | null + } + readonly "output"?: { readonly "language"?: string } + } +} +export const RealtimeTranslationSession = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }), + "type": Schema.Literal("translation").annotate({ + "description": "The session type. Always `translation` for Realtime translation sessions.\n" + }), + "expires_at": Schema.Number.annotate({ + "description": "Expiration timestamp for the session, in seconds since epoch.", + "format": "unixtime" + }).check(Schema.isInt()), + "model": Schema.String.annotate({ + "description": + "The Realtime translation model used for this session. This field is set at\nsession creation and cannot be changed with `session.update`.\n" + }), + "audio": Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "transcription": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "model": Schema.String.annotate({ + "description": "The transcription model used for source transcript deltas." + }) + }).annotate({ + "description": + "Optional source-language transcription. When configured, the server emits\n`session.input_transcript.delta` events. Translation itself still runs from\nthe input audio stream.\n" + }), + Schema.Null + ]) + ), + "noise_reduction": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": NoiseReductionType }).annotate({ + "description": "Optional input noise reduction.\n" + }), + Schema.Null + ]) + ) + })), + "output": Schema.optionalKey( + Schema.Struct({ + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": "Target language for translated output audio and transcript deltas.\n" + }) + ) + }) + ) + }).annotate({ "description": "Configuration for translation input and output audio.\n" }) +}).annotate({ + "title": "Realtime translation session", + "description": + "A Realtime translation session. Translation sessions continuously translate input\naudio into the configured output language.\n" +}) +export type RealtimeTranslationSessionCreateRequest = { + readonly "model": string + readonly "audio"?: { + readonly "input"?: { + readonly "transcription"?: { readonly "model": string } | null + readonly "noise_reduction"?: { readonly "type": NoiseReductionType } | null + } + readonly "output"?: { readonly "language"?: string } + } +} +export const RealtimeTranslationSessionCreateRequest = Schema.Struct({ + "model": Schema.String.annotate({ "description": "The Realtime translation model used for this session.\n" }), + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "transcription": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "model": Schema.String.annotate({ + "description": "The transcription model to use for source transcript deltas." + }) + }).annotate({ + "description": + "Optional source-language transcription. When configured, the server emits\n`session.input_transcript.delta` events. Translation itself still runs from\nthe input audio stream.\n" + }), + Schema.Null + ]) + ), + "noise_reduction": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": NoiseReductionType }).annotate({ + "description": "Optional input noise reduction. Set to `null` to disable it.\n" + }), + Schema.Null + ]) + ) + })), + "output": Schema.optionalKey( + Schema.Struct({ + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": "Target language for translated output audio and transcript deltas.\n" + }) + ) + }) + ) + }).annotate({ "description": "Configuration for translation input and output audio.\n" }) + ) +}).annotate({ + "title": "Realtime translation session configuration", + "description": + "Realtime translation session configuration. Translation sessions stream source\naudio in and translated audio plus transcript deltas out continuously.\n" +}) +export type ListFilesResponse = { + readonly "object": string + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const ListFilesResponse = Schema.Struct({ + "object": Schema.String, + "data": Schema.Array(OpenAIFile), + "first_id": Schema.String, + "last_id": Schema.String, + "has_more": Schema.Boolean +}) +export type ListCertificatesResponse = { + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "last_id": string | null + readonly "has_more": boolean + readonly "object": "list" +} +export const ListCertificatesResponse = Schema.Struct({ + "data": Schema.Array(OrganizationCertificate), + "first_id": Schema.Union([Schema.String, Schema.Null]), + "last_id": Schema.Union([Schema.String, Schema.Null]), + "has_more": Schema.Boolean, + "object": Schema.Literal("list") +}) +export type OrganizationCertificateActivationResponse = { + readonly "object": "organization.certificate.activation" + readonly "data": ReadonlyArray +} +export const OrganizationCertificateActivationResponse = Schema.Struct({ + "object": Schema.Literal("organization.certificate.activation").annotate({ + "description": "The organization certificate activation result type." + }), + "data": Schema.Array(OrganizationCertificate) +}) +export type OrganizationCertificateDeactivationResponse = { + readonly "object": "organization.certificate.deactivation" + readonly "data": ReadonlyArray +} +export const OrganizationCertificateDeactivationResponse = Schema.Struct({ + "object": Schema.Literal("organization.certificate.deactivation").annotate({ + "description": "The organization certificate deactivation result type." + }), + "data": Schema.Array(OrganizationCertificate) +}) +export type ListProjectCertificatesResponse = { + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "last_id": string | null + readonly "has_more": boolean + readonly "object": "list" +} +export const ListProjectCertificatesResponse = Schema.Struct({ + "data": Schema.Array(OrganizationProjectCertificate), + "first_id": Schema.Union([Schema.String, Schema.Null]), + "last_id": Schema.Union([Schema.String, Schema.Null]), + "has_more": Schema.Boolean, + "object": Schema.Literal("list") +}) +export type OrganizationProjectCertificateActivationResponse = { + readonly "object": "organization.project.certificate.activation" + readonly "data": ReadonlyArray +} +export const OrganizationProjectCertificateActivationResponse = Schema.Struct({ + "object": Schema.Literal("organization.project.certificate.activation").annotate({ + "description": "The project certificate activation result type." + }), + "data": Schema.Array(OrganizationProjectCertificate) +}) +export type OrganizationProjectCertificateDeactivationResponse = { + readonly "object": "organization.project.certificate.deactivation" + readonly "data": ReadonlyArray +} +export const OrganizationProjectCertificateDeactivationResponse = Schema.Struct({ + "object": Schema.Literal("organization.project.certificate.deactivation").annotate({ + "description": "The project certificate deactivation result type." + }), + "data": Schema.Array(OrganizationProjectCertificate) +}) +export type CreateImageRequest = { + readonly "prompt": string + readonly "model"?: string | "gpt-image-1.5" | "dall-e-2" | "dall-e-3" | "gpt-image-1" | "gpt-image-1-mini" | null + readonly "n"?: number + readonly "quality"?: "standard" | "hd" | "low" | "medium" | "high" | "auto" | null + readonly "response_format"?: "url" | "b64_json" | null + readonly "output_format"?: "png" | "jpeg" | "webp" | null + readonly "output_compression"?: number | null + readonly "stream"?: boolean | null + readonly "partial_images"?: PartialImages + readonly "size"?: + | string + | "auto" + | "1024x1024" + | "1536x1024" + | "1024x1536" + | "256x256" + | "512x512" + | "1792x1024" + | "1024x1792" + | null + readonly "moderation"?: "low" | "auto" | null + readonly "background"?: "transparent" | "opaque" | "auto" | null + readonly "style"?: "vivid" | "natural" | null + readonly "user"?: string +} +export const CreateImageRequest = Schema.Struct({ + "prompt": Schema.String.annotate({ + "description": + "A text description of the desired image(s). The maximum length is 32000 characters for the GPT image models, 1000 characters for `dall-e-2` and 4000 characters for `dall-e-3`." + }), + "model": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.String, + Schema.Literals(["gpt-image-1.5", "dall-e-2", "dall-e-3", "gpt-image-1", "gpt-image-1-mini"]) + ]).annotate({ + "description": + "The model to use for image generation. One of `dall-e-2`, `dall-e-3`, or a GPT image model (`gpt-image-1`, `gpt-image-1-mini`, `gpt-image-1.5`). Defaults to `dall-e-2` unless a parameter specific to the GPT image models is used." + }), + Schema.Null + ]) + ), + "n": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(10)], { + "description": + "The number of images to generate. Must be between 1 and 10. For `dall-e-3`, only `n=1` is supported." + }) + ) + ]) + ), + "quality": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["standard", "hd", "low", "medium", "high", "auto"]).annotate({ + "description": + "The quality of the image that will be generated.\n\n- `auto` (default value) will automatically select the best quality for the given model.\n- `high`, `medium` and `low` are supported for the GPT image models.\n- `hd` and `standard` are supported for `dall-e-3`.\n- `standard` is the only option for `dall-e-2`.\n" + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "The quality of the image that will be generated.\n\n- `auto` (default value) will automatically select the best quality for the given model.\n- `high`, `medium` and `low` are supported for the GPT image models.\n- `hd` and `standard` are supported for `dall-e-3`.\n- `standard` is the only option for `dall-e-2`.\n" + }) + ]) + ), + "response_format": Schema.optionalKey(Schema.Union([ + Schema.Literals(["url", "b64_json"]).annotate({ + "description": + "The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for the GPT image models, which always return base64-encoded images." + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "The format in which generated images with `dall-e-2` and `dall-e-3` are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter isn't supported for the GPT image models, which always return base64-encoded images." + }) + ])), + "output_format": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["png", "jpeg", "webp"]).annotate({ + "description": + "The format in which the generated images are returned. This parameter is only supported for the GPT image models. Must be one of `png`, `jpeg`, or `webp`." + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "The format in which the generated images are returned. This parameter is only supported for the GPT image models. Must be one of `png`, `jpeg`, or `webp`." + }) + ]) + ), + "output_compression": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "description": + "The compression level (0-100%) for the generated images. This parameter is only supported for the GPT image models with the `webp` or `jpeg` output formats, and defaults to 100." + }) + ), + "stream": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": + "Generate the image in streaming mode. Defaults to `false`. See the\n[Image generation guide](/docs/guides/image-generation) for more information.\nThis parameter is only supported for the GPT image models.\n" + }) + ), + "partial_images": Schema.optionalKey(PartialImages), + "size": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.String, + Schema.Literals(["auto", "1024x1024", "1536x1024", "1024x1536", "256x256", "512x512", "1792x1024", "1024x1792"]) + ]).annotate({ + "description": + "The size of the generated images. For `gpt-image-2` and `gpt-image-2-2026-04-21`, arbitrary resolutions are supported as `WIDTHxHEIGHT` strings, for example `1536x864`. Width and height must both be divisible by 16 and the requested aspect ratio must be between 1:3 and 3:1. Resolutions above `2560x1440` are experimental, and the maximum supported resolution is `3840x2160`. The requested size must also satisfy the model's current pixel and edge limits. The standard sizes `1024x1024`, `1536x1024`, and `1024x1536` are supported by the GPT image models; `auto` is supported for models that allow automatic sizing. For `dall-e-2`, use one of `256x256`, `512x512`, or `1024x1024`. For `dall-e-3`, use one of `1024x1024`, `1792x1024`, or `1024x1792`." + }), + Schema.Null + ]) + ), + "moderation": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["low", "auto"]).annotate({ + "description": + "Control the content-moderation level for images generated by the GPT image models. Must be either `low` for less restrictive filtering or `auto` (default value)." + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "Control the content-moderation level for images generated by the GPT image models. Must be either `low` for less restrictive filtering or `auto` (default value)." + }) + ]) + ), + "background": Schema.optionalKey(Schema.Union([ + Schema.Literals(["transparent", "opaque", "auto"]).annotate({ + "description": + "Allows to set transparency for the background of the generated image(s).\nThis parameter is only supported for the GPT image models. Must be one of\n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the\nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it\nshould be set to either `png` (default value) or `webp`.\n" + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "Allows to set transparency for the background of the generated image(s).\nThis parameter is only supported for the GPT image models. Must be one of\n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the\nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it\nshould be set to either `png` (default value) or `webp`.\n" + }) + ])), + "style": Schema.optionalKey(Schema.Union([ + Schema.Literals(["vivid", "natural"]).annotate({ + "description": + "The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images." + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "The style of the generated images. This parameter is only supported for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes the model to lean towards generating hyper-real and dramatic images. Natural causes the model to produce more natural, less hyper-real looking images." + }) + ])), + "user": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices#end-user-ids).\n" + }) + ) +}) +export type EditImageBodyJsonParam = { + readonly "model"?: string | "gpt-image-1.5" | "gpt-image-1" | "gpt-image-1-mini" | "chatgpt-image-latest" | null + readonly "images": ReadonlyArray + readonly "mask"?: ImageRefParam + readonly "prompt": string + readonly "n"?: number | null + readonly "quality"?: "low" | "medium" | "high" | "auto" | null + readonly "input_fidelity"?: "high" | "low" | null + readonly "size"?: "auto" | "1024x1024" | "1536x1024" | "1024x1536" | null + readonly "user"?: string + readonly "output_format"?: "png" | "jpeg" | "webp" | null + readonly "output_compression"?: number | null + readonly "moderation"?: "low" | "auto" | null + readonly "background"?: "transparent" | "opaque" | "auto" | null + readonly "stream"?: boolean | null + readonly "partial_images"?: PartialImages +} +export const EditImageBodyJsonParam = Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals(["gpt-image-1.5", "gpt-image-1", "gpt-image-1-mini", "chatgpt-image-latest"]), + Schema.Null + ]).annotate({ "description": "The model to use for image editing." }) + ), + "images": Schema.Array(ImageRefParam).annotate({ + "description": "Input image references to edit.\nFor GPT image models, you can provide up to 16 images.\n" + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(16)), + "mask": Schema.optionalKey(ImageRefParam), + "prompt": Schema.String.annotate({ "description": "A text description of the desired image edit." }).check( + Schema.isMinLength(1) + ).check(Schema.isMaxLength(32000)), + "n": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(10)), + Schema.Null + ]).annotate({ "description": "The number of edited images to generate." }) + ), + "quality": Schema.optionalKey( + Schema.Union([Schema.Literals(["low", "medium", "high", "auto"]), Schema.Null]).annotate({ + "description": "Output quality for GPT image models.\n" + }) + ), + "input_fidelity": Schema.optionalKey( + Schema.Union([Schema.Literals(["high", "low"]), Schema.Null]).annotate({ + "description": "Controls fidelity to the original input image(s)." + }) + ), + "size": Schema.optionalKey( + Schema.Union([Schema.Literals(["auto", "1024x1024", "1536x1024", "1024x1536"]), Schema.Null]).annotate({ + "description": "Requested output image size." + }) + ), + "user": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A unique identifier representing your end-user, which can help OpenAI\nmonitor and detect abuse.\n" + }) + ), + "output_format": Schema.optionalKey( + Schema.Union([Schema.Literals(["png", "jpeg", "webp"]), Schema.Null]).annotate({ + "description": "Output image format. Supported for GPT image models." + }) + ), + "output_compression": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check( + Schema.isLessThanOrEqualTo(100) + ), + Schema.Null + ]).annotate({ "description": "Compression level for `jpeg` or `webp` output." }) + ), + "moderation": Schema.optionalKey( + Schema.Union([Schema.Literals(["low", "auto"]), Schema.Null]).annotate({ + "description": "Moderation level for GPT image models." + }) + ), + "background": Schema.optionalKey( + Schema.Union([Schema.Literals(["transparent", "opaque", "auto"]), Schema.Null]).annotate({ + "description": "Background behavior for generated image output." + }) + ), + "stream": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ "description": "Stream partial image results as events." }) + ), + "partial_images": Schema.optionalKey(PartialImages) +}).annotate({ + "description": + "JSON request body for image edits.\n\nUse `images` (array of `ImageRefParam`) instead of multipart `image` uploads.\nYou can reference images via external URLs, data URLs, or uploaded file IDs.\nJSON edits support GPT image models only; DALL-E edits require multipart (`dall-e-2` only).\n" +}) +export type ProjectListResponse = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const ProjectListResponse = Schema.Struct({ + "object": Schema.Literal("list"), + "data": Schema.Array(Project), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type ProjectApiKey = { + readonly "object": "organization.project.api_key" + readonly "redacted_value": string + readonly "name": string + readonly "created_at": number + readonly "last_used_at": number | null + readonly "id": string + readonly "owner": { + readonly "type"?: "user" | "service_account" + readonly "user"?: ProjectApiKeyOwnerUser + readonly "service_account"?: ProjectApiKeyOwnerServiceAccount + } +} +export const ProjectApiKey = Schema.Struct({ + "object": Schema.Literal("organization.project.api_key").annotate({ + "description": "The object type, which is always `organization.project.api_key`" + }), + "redacted_value": Schema.String.annotate({ "description": "The redacted value of the API key" }), + "name": Schema.String.annotate({ "description": "The name of the API key" }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the API key was created", + "format": "unixtime" + }).check(Schema.isInt()), + "last_used_at": Schema.Union([Schema.Number.annotate({ "format": "unixtime" }).check(Schema.isInt()), Schema.Null]) + .annotate({ "description": "The Unix timestamp (in seconds) of when the API key was last used." }), + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints" }), + "owner": Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literals(["user", "service_account"]).annotate({ "description": "`user` or `service_account`" }) + ), + "user": Schema.optionalKey(ProjectApiKeyOwnerUser), + "service_account": Schema.optionalKey(ProjectApiKeyOwnerServiceAccount) + }) +}).annotate({ "description": "Represents an individual API key in a project." }) +export type ProjectGroupListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next": string | null +} +export const ProjectGroupListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "Always `list`." }), + "data": Schema.Array(ProjectGroup).annotate({ + "description": "Project group memberships returned in the current page." + }), + "has_more": Schema.Boolean.annotate({ "description": "Whether additional project group memberships are available." }), + "next": Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "Cursor to fetch the next page of results, or `null` when there are no more results." + }) +}).annotate({ "description": "Paginated list of groups that have access to a project." }) +export type ProjectRateLimitListResponse = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const ProjectRateLimitListResponse = Schema.Struct({ + "object": Schema.Literal("list"), + "data": Schema.Array(ProjectRateLimit), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type ProjectServiceAccountListResponse = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const ProjectServiceAccountListResponse = Schema.Struct({ + "object": Schema.Literal("list"), + "data": Schema.Array(ProjectServiceAccount), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type ProjectServiceAccountCreateResponse = { + readonly "object": "organization.project.service_account" + readonly "id": string + readonly "name": string + readonly "role": "member" + readonly "created_at": number + readonly "api_key": ProjectServiceAccountApiKey | null +} +export const ProjectServiceAccountCreateResponse = Schema.Struct({ + "object": Schema.Literal("organization.project.service_account"), + "id": Schema.String, + "name": Schema.String, + "role": Schema.Literal("member").annotate({ + "description": "Service accounts can only have one role of type `member`" + }), + "created_at": Schema.Number.annotate({ "format": "unixtime" }).check(Schema.isInt()), + "api_key": Schema.Union([ProjectServiceAccountApiKey, Schema.Null]) +}) +export type ProjectUserListResponse = { + readonly "object": string + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const ProjectUserListResponse = Schema.Struct({ + "object": Schema.String, + "data": Schema.Array(ProjectUser), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type RealtimeTranscriptionSessionCreateResponseGA = { + readonly "type": "transcription" + readonly "id": string + readonly "object": string + readonly "expires_at"?: number + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> + readonly "audio"?: { + readonly "input"?: { + readonly "format"?: RealtimeAudioFormats + readonly "transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + } + readonly "noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "turn_detection"?: { + readonly "type"?: string + readonly "threshold"?: number + readonly "prefix_padding_ms"?: number + readonly "silence_duration_ms"?: number + } | null + } + } +} +export const RealtimeTranscriptionSessionCreateResponseGA = Schema.Struct({ + "type": Schema.Literal("transcription").annotate({ + "description": "The type of session. Always `transcription` for transcription sessions.\n" + }), + "id": Schema.String.annotate({ + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }), + "object": Schema.String.annotate({ "description": "The object type. Always `realtime.transcription_session`." }), + "expires_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Expiration timestamp for the session, in seconds since epoch.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "include": Schema.optionalKey( + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }) + ), + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey(RealtimeAudioFormats), + "transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model used for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`.\n" + }) + ), + "language": Schema.optionalKey( + Schema.String.annotate({ "description": "The language of the input audio.\n" }) + ), + "prompt": Schema.optionalKey( + Schema.String.annotate({ + "description": "The prompt configured for input audio transcription, when present.\n" + }) + ) + }).annotate({ "description": "Configuration of the transcription model.\n" }) + ), + "noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": "Configuration for input audio noise reduction.\n" + }) + ), + "turn_detection": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.String.annotate({ + "description": "Type of turn detection, only `server_vad` is currently supported.\n" + }) + ), + "threshold": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }).check(Schema.isFinite()) + ), + "prefix_padding_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }).check(Schema.isInt()) + ), + "silence_duration_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + }).check(Schema.isInt()) + ) + }).annotate({ + "description": + "Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech. For `gpt-realtime-whisper`, this must be `null`; VAD is not supported.\n" + }), + Schema.Null + ]).annotate({ + "description": + "Configuration for turn detection. For `gpt-realtime-whisper`, this must be `null`; VAD is not supported.\n" + }) + ) + })) + }).annotate({ "description": "Configuration for input audio for the session.\n" }) + ) +}).annotate({ + "title": "Realtime transcription session configuration object", + "description": "A Realtime transcription session configuration object.\n" +}) +export type RealtimeMCPToolCall = { + readonly "type": "mcp_call" + readonly "id": string + readonly "server_label": string + readonly "name": string + readonly "arguments": string + readonly "approval_request_id"?: string | null + readonly "output"?: string | null + readonly "error"?: RealtimeMCPProtocolError | RealtimeMCPToolExecutionError | RealtimeMCPHTTPError | null +} +export const RealtimeMCPToolCall = Schema.Struct({ + "type": Schema.Literal("mcp_call").annotate({ "description": "The type of the item. Always `mcp_call`." }), + "id": Schema.String.annotate({ "description": "The unique ID of the tool call." }), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server running the tool." }), + "name": Schema.String.annotate({ "description": "The name of the tool that was run." }), + "arguments": Schema.String.annotate({ "description": "A JSON string of the arguments passed to the tool." }), + "approval_request_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The ID of an associated approval request, if any." }), + Schema.Null + ]) + ), + "output": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "The output from the tool call." }), Schema.Null]) + ), + "error": Schema.optionalKey( + Schema.Union([ + Schema.Union([RealtimeMCPProtocolError, RealtimeMCPToolExecutionError, RealtimeMCPHTTPError], { mode: "oneOf" }) + .annotate({ "description": "The error from the tool call, if any." }), + Schema.Null + ]) + ) +}).annotate({ + "title": "Realtime MCP tool call", + "description": "A Realtime item representing an invocation of a tool on an MCP server.\n" +}) +export type RealtimeReasoning = { readonly "effort"?: RealtimeReasoningEffort } +export const RealtimeReasoning = Schema.Struct({ "effort": Schema.optionalKey(RealtimeReasoningEffort) }).annotate({ + "title": "Realtime reasoning configuration", + "description": "Configuration for reasoning-capable Realtime models such as `gpt-realtime-2`.\n" +}) +export type RealtimeTranscriptionSessionCreateRequestGA = { + readonly "type": "transcription" + readonly "audio"?: { + readonly "input"?: { + readonly "format"?: RealtimeAudioFormats + readonly "transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + readonly "delay"?: "minimal" | "low" | "medium" | "high" | "xhigh" + } + readonly "noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "turn_detection"?: RealtimeTurnDetection + } + } + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> +} +export const RealtimeTranscriptionSessionCreateRequestGA = Schema.Struct({ + "type": Schema.Literal("transcription").annotate({ + "description": "The type of session to create. Always `transcription` for transcription sessions.\n" + }), + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey(RealtimeAudioFormats), + "transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n" + }) + ), + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }) + ), + "prompt": Schema.optionalKey(Schema.String.annotate({ + "description": + "An optional text to guide the model's style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text string, for example \"expect words related to technology\".\nPrompt is not supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + })), + "delay": Schema.optionalKey( + Schema.Literals(["minimal", "low", "medium", "high", "xhigh"]).annotate({ + "description": + "Controls how long the model waits before emitting transcription text.\nHigher values can improve transcription accuracy at the cost of latency.\nOnly supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + }) + ) + }).annotate({ + "description": + "Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n" + }) + ), + "noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": + "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n" + }) + ), + "turn_detection": Schema.optionalKey(RealtimeTurnDetection) + })) + }).annotate({ "description": "Configuration for input and output audio.\n" }) + ), + "include": Schema.optionalKey( + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }) + ) +}).annotate({ + "title": "Realtime transcription session configuration", + "description": "Realtime transcription session object configuration." +}) +export type Reasoning = { + readonly "effort"?: ReasoningEffort + readonly "summary"?: "auto" | "concise" | "detailed" | null + readonly "generate_summary"?: "auto" | "concise" | "detailed" | null +} +export const Reasoning = Schema.Struct({ + "effort": Schema.optionalKey(ReasoningEffort), + "summary": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "concise", "detailed"]).annotate({ + "description": + "A summary of the reasoning performed by the model. This can be\nuseful for debugging and understanding the model's reasoning process.\nOne of `auto`, `concise`, or `detailed`.\n\n`concise` is supported for `computer-use-preview` models and all reasoning models after `gpt-5`.\n" + }), + Schema.Null + ])), + "generate_summary": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["auto", "concise", "detailed"]).annotate({ + "description": + "**Deprecated:** use `summary` instead.\n\nA summary of the reasoning performed by the model. This can be\nuseful for debugging and understanding the model's reasoning process.\nOne of `auto`, `concise`, or `detailed`.\n" + }), + Schema.Null + ]) + ) +}).annotate({ + "title": "Reasoning", + "description": + "**gpt-5 and o-series models only**\n\nConfiguration options for\n[reasoning models](https://platform.openai.com/docs/guides/reasoning).\n" +}) +export type ResponseError = { readonly "code": ResponseErrorCode; readonly "message": string } | null +export const ResponseError = Schema.Union([ + Schema.Struct({ + "code": ResponseErrorCode, + "message": Schema.String.annotate({ "description": "A human-readable description of the error.\n" }) + }).annotate({ "description": "An error object returned when the model fails to generate a Response.\n" }), + Schema.Null +]) +export type ResponseFormatJsonSchema = { + readonly "type": "json_schema" + readonly "json_schema": { + readonly "description"?: string + readonly "name": string + readonly "schema"?: ResponseFormatJsonSchemaSchema + readonly "strict"?: boolean | null + } +} +export const ResponseFormatJsonSchema = Schema.Struct({ + "type": Schema.Literal("json_schema").annotate({ + "description": "The type of response format being defined. Always `json_schema`." + }), + "json_schema": Schema.Struct({ + "description": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A description of what the response format is for, used by the model to\ndetermine how to respond in the format.\n" + }) + ), + "name": Schema.String.annotate({ + "description": + "The name of the response format. Must be a-z, A-Z, 0-9, or contain\nunderscores and dashes, with a maximum length of 64.\n" + }), + "schema": Schema.optionalKey(ResponseFormatJsonSchemaSchema), + "strict": Schema.optionalKey(Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Whether to enable strict schema adherence when generating the output.\nIf set to true, the model will always follow the exact schema defined\nin the `schema` field. Only a subset of JSON Schema is supported when\n`strict` is `true`. To learn more, read the [Structured Outputs\nguide](/docs/guides/structured-outputs).\n" + }), + Schema.Null + ])) + }).annotate({ + "title": "JSON schema", + "description": "Structured Outputs configuration options, including a JSON Schema.\n" + }) +}).annotate({ + "title": "JSON schema", + "description": + "JSON Schema response format. Used to generate structured JSON responses.\nLearn more about [Structured Outputs](/docs/guides/structured-outputs).\n" +}) +export type TextResponseFormatJsonSchema = { + readonly "type": "json_schema" + readonly "description"?: string + readonly "name": string + readonly "schema": ResponseFormatJsonSchemaSchema + readonly "strict"?: boolean | null +} +export const TextResponseFormatJsonSchema = Schema.Struct({ + "type": Schema.Literal("json_schema").annotate({ + "description": "The type of response format being defined. Always `json_schema`." + }), + "description": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A description of what the response format is for, used by the model to\ndetermine how to respond in the format.\n" + }) + ), + "name": Schema.String.annotate({ + "description": + "The name of the response format. Must be a-z, A-Z, 0-9, or contain\nunderscores and dashes, with a maximum length of 64.\n" + }), + "schema": ResponseFormatJsonSchemaSchema, + "strict": Schema.optionalKey(Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Whether to enable strict schema adherence when generating the output.\nIf set to true, the model will always follow the exact schema defined\nin the `schema` field. Only a subset of JSON Schema is supported when\n`strict` is `true`. To learn more, read the [Structured Outputs\nguide](/docs/guides/structured-outputs).\n" + }), + Schema.Null + ])) +}).annotate({ + "title": "JSON schema", + "description": + "JSON Schema response format. Used to generate structured JSON responses.\nLearn more about [Structured Outputs](/docs/guides/structured-outputs).\n" +}) +export type ResponseTextDeltaEvent = { + readonly "type": "response.output_text.delta" + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "delta": string + readonly "sequence_number": number + readonly "logprobs": ReadonlyArray +} +export const ResponseTextDeltaEvent = Schema.Struct({ + "type": Schema.Literal("response.output_text.delta").annotate({ + "description": "The type of the event. Always `response.output_text.delta`.\n" + }), + "item_id": Schema.String.annotate({ "description": "The ID of the output item that the text delta was added to.\n" }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the text delta was added to.\n" + }).check(Schema.isInt()), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part that the text delta was added to.\n" + }).check(Schema.isInt()), + "delta": Schema.String.annotate({ "description": "The text delta that was added.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number for this event." }).check( + Schema.isInt() + ), + "logprobs": Schema.Array(ResponseLogProb).annotate({ + "description": "The log probabilities of the tokens in the delta.\n" + }) +}).annotate({ "description": "Emitted when there is an additional text delta." }) +export type ResponseTextDoneEvent = { + readonly "type": "response.output_text.done" + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "text": string + readonly "sequence_number": number + readonly "logprobs": ReadonlyArray +} +export const ResponseTextDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.output_text.done").annotate({ + "description": "The type of the event. Always `response.output_text.done`.\n" + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the output item that the text content is finalized.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the text content is finalized.\n" + }).check(Schema.isInt()), + "content_index": Schema.Number.annotate({ + "description": "The index of the content part that the text content is finalized.\n" + }).check(Schema.isInt()), + "text": Schema.String.annotate({ "description": "The text content that is finalized.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number for this event." }).check( + Schema.isInt() + ), + "logprobs": Schema.Array(ResponseLogProb).annotate({ + "description": "The log probabilities of the tokens in the delta.\n" + }) +}).annotate({ "description": "Emitted when text content is finalized." }) +export type Prompt = { + readonly "id": string + readonly "version"?: string | null + readonly "variables"?: ResponsePromptVariables +} | null +export const Prompt = Schema.Union([ + Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique identifier of the prompt template to use." }), + "version": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "Optional version of the prompt template." }), Schema.Null]) + ), + "variables": Schema.optionalKey(ResponsePromptVariables) + }).annotate({ + "description": + "Reference to a prompt template and its variables.\n[Learn more](/docs/guides/text?api-mode=responses#reusable-prompts).\n" + }), + Schema.Null +]) +export type GroupRoleAssignment = { readonly "object": "group.role"; readonly "group": Group; readonly "role": Role } +export const GroupRoleAssignment = Schema.Struct({ + "object": Schema.Literal("group.role").annotate({ "description": "Always `group.role`." }), + "group": Group, + "role": Role +}).annotate({ "description": "Role assignment linking a group to a role." }) +export type PublicRoleListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next": string | null +} +export const PublicRoleListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "Always `list`." }), + "data": Schema.Array(Role).annotate({ "description": "Roles returned in the current page." }), + "has_more": Schema.Boolean.annotate({ "description": "Whether more roles are available when paginating." }), + "next": Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "Cursor to fetch the next page of results, or `null` when there are no additional roles." + }) +}).annotate({ "description": "Paginated list of roles available on an organization or project." }) +export type RunStepDeltaObject = { + readonly "id": string + readonly "object": "thread.run.step.delta" + readonly "delta": { + readonly "step_details"?: { + readonly "type": "message_creation" + readonly "message_creation"?: { readonly "message_id"?: string } + } | { + readonly "type": "tool_calls" + readonly "tool_calls"?: ReadonlyArray< + | RunStepDeltaStepDetailsToolCallsCodeObject + | RunStepDeltaStepDetailsToolCallsFileSearchObject + | RunStepDeltaStepDetailsToolCallsFunctionObject + > + } + } +} +export const RunStepDeltaObject = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The identifier of the run step, which can be referenced in API endpoints." + }), + "object": Schema.Literal("thread.run.step.delta").annotate({ + "description": "The object type, which is always `thread.run.step.delta`." + }), + "delta": Schema.Struct({ + "step_details": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("message_creation").annotate({ "description": "Always `message_creation`." }), + "message_creation": Schema.optionalKey( + Schema.Struct({ + "message_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the message that was created by this run step." }) + ) + }) + ) + }).annotate({ "title": "Message creation", "description": "The details of the run step." }), + Schema.Struct({ + "type": Schema.Literal("tool_calls").annotate({ "description": "Always `tool_calls`." }), + "tool_calls": Schema.optionalKey( + Schema.Array( + Schema.Union([ + RunStepDeltaStepDetailsToolCallsCodeObject, + RunStepDeltaStepDetailsToolCallsFileSearchObject, + RunStepDeltaStepDetailsToolCallsFunctionObject + ], { mode: "oneOf" }) + ).annotate({ + "description": + "An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n" + }) + ) + }).annotate({ "title": "Tool calls", "description": "The details of the run step." }) + ], { mode: "oneOf" })) + }).annotate({ "description": "The delta containing the fields that have changed on the run step." }) +}).annotate({ + "title": "Run step delta object", + "description": "Represents a run step delta i.e. any changed fields on a run step during streaming.\n" +}) +export type CreateSpeechResponseStreamEvent = SpeechAudioDeltaEvent | SpeechAudioDoneEvent +export const CreateSpeechResponseStreamEvent = Schema.Union([SpeechAudioDeltaEvent, SpeechAudioDoneEvent]) +export type ChunkingStrategyRequestParam = { readonly "type": "auto" } | { + readonly "type": "static" + readonly "static": StaticChunkingStrategy +} +export const ChunkingStrategyRequestParam = Schema.Union([ + Schema.Struct({ "type": Schema.Literal("auto").annotate({ "description": "Always `auto`." }) }).annotate({ + "title": "Auto Chunking Strategy", + "description": "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }), + Schema.Struct({ + "type": Schema.Literal("static").annotate({ "description": "Always `static`." }), + "static": StaticChunkingStrategy + }).annotate({ + "title": "Static Chunking Strategy", + "description": "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }) +], { mode: "oneOf" }) +export type CreateCompletionRequest = { + readonly "model": string | "gpt-3.5-turbo-instruct" | "davinci-002" | "babbage-002" + readonly "prompt": + | string + | ReadonlyArray + | ReadonlyArray + | ReadonlyArray> + | null + readonly "best_of"?: number + readonly "echo"?: boolean | null + readonly "frequency_penalty"?: number + readonly "logit_bias"?: {} + readonly "logprobs"?: number + readonly "max_tokens"?: number + readonly "n"?: number + readonly "presence_penalty"?: number + readonly "seed"?: never + readonly "stop"?: StopConfiguration + readonly "stream"?: boolean | null + readonly "stream_options"?: ChatCompletionStreamOptions + readonly "suffix"?: string | null + readonly "temperature"?: number + readonly "top_p"?: number + readonly "user"?: string +} +export const CreateCompletionRequest = Schema.Struct({ + "model": Schema.Union([Schema.String, Schema.Literals(["gpt-3.5-turbo-instruct", "davinci-002", "babbage-002"])]) + .annotate({ + "description": + "ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models) for descriptions of them.\n" + }), + "prompt": Schema.Union([ + Schema.Union([ + Schema.String, + Schema.Array(Schema.String), + Schema.Array(Schema.Number.check(Schema.isInt())).check(Schema.isMinLength(1)), + Schema.Array(Schema.Array(Schema.Number.check(Schema.isInt())).check(Schema.isMinLength(1))).check( + Schema.isMinLength(1) + ) + ], { mode: "oneOf" }).annotate({ + "description": + "The prompt(s) to generate completions for, encoded as a string, array of strings, array of tokens, or array of token arrays.\n\nNote that <|endoftext|> is the document separator that the model sees during training, so if a prompt is not specified the model will generate as if from the beginning of a new document.\n" + }), + Schema.Null + ]), + "best_of": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(20)], { + "description": + "Generates `best_of` completions server-side and returns the \"best\" (the one with the highest log probability per token). Results cannot be streamed.\n\nWhen used with `n`, `best_of` controls the number of candidate completions and `n` specifies how many to return – `best_of` must be greater than `n`.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n" + }) + ) + ]) + ), + "echo": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": "Echo back the prompt in addition to the completion\n" + }) + ), + "frequency_penalty": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(-2), Schema.isLessThanOrEqualTo(2)], { + "description": + "Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation)\n" + }) + ) + ]) + ), + "logit_bias": Schema.optionalKey(Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the GPT tokenizer) to an associated bias value from -100 to 100. You can use this [tokenizer tool](/tokenizer?view=bpe) to convert text to token IDs. Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban or exclusive selection of the relevant token.\n\nAs an example, you can pass `{\"50256\": -100}` to prevent the <|endoftext|> token from being generated.\n" + }) + ])), + "logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(5)], { + "description": + "Include the log probabilities on the `logprobs` most likely output tokens, as well the chosen tokens. For example, if `logprobs` is 5, the API will return a list of the 5 most likely tokens. The API will always return the `logprob` of the sampled token, so there may be up to `logprobs+1` elements in the response.\n\nThe maximum value for `logprobs` is 5.\n" + }) + ) + ]) + ), + "max_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0)], { + "description": + "The maximum number of [tokens](/tokenizer) that can be generated in the completion.\n\nThe token count of your prompt plus `max_tokens` cannot exceed the model's context length. [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) for counting tokens.\n" + }) + ) + ]) + ), + "n": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(128)], { + "description": + "How many completions to generate for each prompt.\n\n**Note:** Because this parameter generates many completions, it can quickly consume your token quota. Use carefully and ensure that you have reasonable settings for `max_tokens` and `stop`.\n" + }) + ) + ]) + ), + "presence_penalty": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(-2), Schema.isLessThanOrEqualTo(2)], { + "description": + "Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.\n\n[See more information about frequency and presence penalties.](/docs/guides/text-generation)\n" + }) + ) + ]) + ), + "seed": Schema.optionalKey(Schema.Never), + "stop": Schema.optionalKey(StopConfiguration), + "stream": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": + "Whether to stream back partial progress. If set, tokens will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available, with the stream terminated by a `data: [DONE]` message. [Example Python code](https://cookbook.openai.com/examples/how_to_stream_completions).\n" + }) + ), + "stream_options": Schema.optionalKey(ChatCompletionStreamOptions), + "suffix": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "The suffix that comes after a completion of inserted text.\n\nThis parameter is only supported for `gpt-3.5-turbo-instruct`.\n" + }) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(2)], { + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n\nWe generally recommend altering this or `top_p` but not both.\n" + }) + ) + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(1)], { + "description": + "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }) + ) + ]) + ), + "user": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices#end-user-ids).\n" + }) + ) +}) +export type TranscriptTextDoneEvent = { + readonly "type": "transcript.text.done" + readonly "text": string + readonly "logprobs"?: ReadonlyArray< + { readonly "token"?: string; readonly "logprob"?: number; readonly "bytes"?: ReadonlyArray } + > + readonly "usage"?: TranscriptTextUsageTokens +} +export const TranscriptTextDoneEvent = Schema.Struct({ + "type": Schema.Literal("transcript.text.done").annotate({ + "description": "The type of the event. Always `transcript.text.done`.\n" + }), + "text": Schema.String.annotate({ "description": "The text that was transcribed.\n" }), + "logprobs": Schema.optionalKey( + Schema.Array(Schema.Struct({ + "token": Schema.optionalKey( + Schema.String.annotate({ "description": "The token that was used to generate the log probability.\n" }) + ), + "logprob": Schema.optionalKey( + Schema.Number.annotate({ "description": "The log probability of the token.\n" }).check(Schema.isFinite()) + ), + "bytes": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": "The bytes that were used to generate the log probability.\n" + }) + ) + })).annotate({ + "description": + "The log probabilities of the individual tokens in the transcription. Only included if you [create a transcription](/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`.\n" + }) + ), + "usage": Schema.optionalKey(TranscriptTextUsageTokens) +}).annotate({ + "description": + "Emitted when the transcription is complete. Contains the complete transcription text. Only emitted when you [create a transcription](/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`." +}) +export type CreateTranscriptionResponseDiarizedJson = { + readonly "task": "transcribe" + readonly "duration": number + readonly "text": string + readonly "segments": ReadonlyArray + readonly "usage"?: { + readonly "type": "tokens" + readonly "input_tokens": number + readonly "input_token_details"?: { readonly "text_tokens"?: number; readonly "audio_tokens"?: number } + readonly "output_tokens": number + readonly "total_tokens": number + } | { readonly "type": "duration"; readonly "seconds": number } +} +export const CreateTranscriptionResponseDiarizedJson = Schema.Struct({ + "task": Schema.Literal("transcribe").annotate({ + "description": "The type of task that was run. Always `transcribe`." + }), + "duration": Schema.Number.annotate({ "description": "Duration of the input audio in seconds.", "format": "double" }) + .check(Schema.isFinite()), + "text": Schema.String.annotate({ "description": "The concatenated transcript text for the entire audio input." }), + "segments": Schema.Array(TranscriptionDiarizedSegment).annotate({ + "description": "Segments of the transcript annotated with timestamps and speaker labels." + }), + "usage": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("tokens").annotate({ + "description": "The type of the usage object. Always `tokens` for this variant." + }), + "input_tokens": Schema.Number.annotate({ "description": "Number of input tokens billed for this request." }) + .check(Schema.isInt()), + "input_token_details": Schema.optionalKey( + Schema.Struct({ + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Number of text tokens billed for this request." }).check( + Schema.isInt() + ) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Number of audio tokens billed for this request." }).check( + Schema.isInt() + ) + ) + }).annotate({ "description": "Details about the input tokens billed for this request." }) + ), + "output_tokens": Schema.Number.annotate({ "description": "Number of output tokens generated." }).check( + Schema.isInt() + ), + "total_tokens": Schema.Number.annotate({ "description": "Total number of tokens used (input + output)." }).check( + Schema.isInt() + ) + }).annotate({ "title": "Token Usage", "description": "Token or duration usage statistics for the request." }), + Schema.Struct({ + "type": Schema.Literal("duration").annotate({ + "description": "The type of the usage object. Always `duration` for this variant." + }), + "seconds": Schema.Number.annotate({ + "description": "Duration of the input audio in seconds.", + "format": "double" + }).check(Schema.isFinite()) + }).annotate({ "title": "Duration Usage", "description": "Token or duration usage statistics for the request." }) + ], { mode: "oneOf" })) +}).annotate({ + "description": + "Represents a diarized transcription response returned by the model, including the combined transcript and speaker-segment annotations.\n" +}) +export type CreateTranslationResponseVerboseJson = { + readonly "language": string + readonly "duration": number + readonly "text": string + readonly "segments"?: ReadonlyArray +} +export const CreateTranslationResponseVerboseJson = Schema.Struct({ + "language": Schema.String.annotate({ "description": "The language of the output translation (always `english`)." }), + "duration": Schema.Number.annotate({ "description": "The duration of the input audio.", "format": "double" }).check( + Schema.isFinite() + ), + "text": Schema.String.annotate({ "description": "The translated text." }), + "segments": Schema.optionalKey( + Schema.Array(TranscriptionSegment).annotate({ + "description": "Segments of the translated text and their corresponding details." + }) + ) +}) +export type CreateTranscriptionResponseVerboseJson = { + readonly "language": string + readonly "duration": number + readonly "text": string + readonly "words"?: ReadonlyArray + readonly "segments"?: ReadonlyArray + readonly "usage"?: TranscriptTextUsageDuration +} +export const CreateTranscriptionResponseVerboseJson = Schema.Struct({ + "language": Schema.String.annotate({ "description": "The language of the input audio." }), + "duration": Schema.Number.annotate({ "description": "The duration of the input audio.", "format": "double" }).check( + Schema.isFinite() + ), + "text": Schema.String.annotate({ "description": "The transcribed text." }), + "words": Schema.optionalKey( + Schema.Array(TranscriptionWord).annotate({ "description": "Extracted words and their corresponding timestamps." }) + ), + "segments": Schema.optionalKey( + Schema.Array(TranscriptionSegment).annotate({ + "description": "Segments of the transcribed text and their corresponding details." + }) + ), + "usage": Schema.optionalKey(TranscriptTextUsageDuration) +}).annotate({ + "description": "Represents a verbose json transcription response returned by model, based on the provided input." +}) +export type UsageTimeBucket = { + readonly "object": "bucket" + readonly "start_time": number + readonly "end_time": number + readonly "results": ReadonlyArray< + | UsageCompletionsResult + | UsageEmbeddingsResult + | UsageModerationsResult + | UsageImagesResult + | UsageAudioSpeechesResult + | UsageAudioTranscriptionsResult + | UsageVectorStoresResult + | UsageCodeInterpreterSessionsResult + | UsageFileSearchCallsResult + | UsageWebSearchCallsResult + | CostsResult + > +} +export const UsageTimeBucket = Schema.Struct({ + "object": Schema.Literal("bucket"), + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.Number.check(Schema.isInt()), + "results": Schema.Array( + Schema.Union([ + UsageCompletionsResult, + UsageEmbeddingsResult, + UsageModerationsResult, + UsageImagesResult, + UsageAudioSpeechesResult, + UsageAudioTranscriptionsResult, + UsageVectorStoresResult, + UsageCodeInterpreterSessionsResult, + UsageFileSearchCallsResult, + UsageWebSearchCallsResult, + CostsResult + ], { mode: "oneOf" }) + ) +}) +export type UserListResponse = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const UserListResponse = Schema.Struct({ + "object": Schema.Literal("list"), + "data": Schema.Array(User), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type UserRoleAssignment = { readonly "object": "user.role"; readonly "user": User; readonly "role": Role } +export const UserRoleAssignment = Schema.Struct({ + "object": Schema.Literal("user.role").annotate({ "description": "Always `user.role`." }), + "user": User, + "role": Role +}).annotate({ "description": "Role assignment linking a user to a role." }) +export type CreateTranscriptionRequest = { + readonly "file": string + readonly "model": + | string + | "whisper-1" + | "gpt-4o-transcribe" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe-diarize" + readonly "language"?: string + readonly "prompt"?: string + readonly "response_format"?: AudioResponseFormat + readonly "temperature"?: number + readonly "include"?: ReadonlyArray + readonly "timestamp_granularities"?: ReadonlyArray<"word" | "segment"> + readonly "stream"?: boolean | null + readonly "chunking_strategy"?: "auto" | VadConfig | null + readonly "known_speaker_names"?: ReadonlyArray + readonly "known_speaker_references"?: ReadonlyArray +} +export const CreateTranscriptionRequest = Schema.Struct({ + "file": Schema.String.annotate({ + "description": + "The audio file object (not file name) to transcribe, in one of these formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm.\n", + "format": "binary" + }), + "model": Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-transcribe", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe-diarize" + ]) + ]).annotate({ + "description": + "ID of the model to use. The options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `whisper-1` (which is powered by our open source Whisper V2 model), and `gpt-4o-transcribe-diarize`.\n" + }), + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format will improve accuracy and latency.\n" + }) + ), + "prompt": Schema.optionalKey( + Schema.String.annotate({ + "description": + "An optional text to guide the model's style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text#prompting) should match the audio language. This field is not supported when using `gpt-4o-transcribe-diarize`.\n" + }) + ), + "response_format": Schema.optionalKey(AudioResponseFormat), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit.\n" + }).check(Schema.isFinite()) + ), + "include": Schema.optionalKey( + Schema.Array(TranscriptionInclude).annotate({ + "description": + "Additional information to include in the transcription response.\n`logprobs` will return the log probabilities of the tokens in the\nresponse to understand the model's confidence in the transcription.\n`logprobs` only works with response_format set to `json` and only with\nthe models `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `gpt-4o-mini-transcribe-2025-12-15`. This field is not supported when using `gpt-4o-transcribe-diarize`.\n" + }) + ), + "timestamp_granularities": Schema.optionalKey( + Schema.Array(Schema.Literals(["word", "segment"])).annotate({ + "description": + "The timestamp granularities to populate for this transcription. `response_format` must be set `verbose_json` to use timestamp granularities. Either or both of these options are supported: `word`, or `segment`. Note: There is no additional latency for segment timestamps, but generating word timestamps incurs additional latency.\nThis option is not available for `gpt-4o-transcribe-diarize`.\n" + }) + ), + "stream": Schema.optionalKey(Schema.Union([ + Schema.Boolean.annotate({ + "description": + "If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section of the Speech-to-Text guide](/docs/guides/speech-to-text?lang=curl#streaming-transcriptions)\nfor more information.\n\nNote: Streaming is not supported for the `whisper-1` model and will be ignored.\n" + }), + Schema.Null + ])), + "chunking_strategy": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Literal("auto").annotate({ + "description": "Automatically set chunking parameters based on the audio. Must be set to `\"auto\"`.\n" + }), + VadConfig + ]).annotate({ + "description": + "Controls how the audio is cut into chunks. When set to `\"auto\"`, the server first normalizes loudness and then uses voice activity detection (VAD) to choose boundaries. `server_vad` object can be provided to tweak VAD detection parameters manually. If unset, the audio is transcribed as a single block. Required when using `gpt-4o-transcribe-diarize` for inputs longer than 30 seconds. " + }), + Schema.Null + ]) + ), + "known_speaker_names": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "Optional list of speaker names that correspond to the audio samples provided in `known_speaker_references[]`. Each entry should be a short identifier (for example `customer` or `agent`). Up to 4 speakers are supported.\n" + }).check(Schema.isMaxLength(4)) + ), + "known_speaker_references": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "Optional list of audio samples (as [data URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs)) that contain known speaker references matching `known_speaker_names[]`. Each sample must be between 2 and 10 seconds, and can use any of the same input audio formats supported by `file`.\n" + }).check(Schema.isMaxLength(4)) + ) +}) +export type CreateVectorStoreRequest = { + readonly "file_ids"?: ReadonlyArray + readonly "name"?: string + readonly "description"?: string + readonly "expires_after"?: VectorStoreExpirationAfter + readonly "chunking_strategy"?: { readonly "type": "auto" } | { + readonly "type": "static" + readonly "static": StaticChunkingStrategy + } + readonly "metadata"?: Metadata +} +export const CreateVectorStoreRequest = Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files." + }).check(Schema.isMaxLength(500)) + ), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the vector store." })), + "description": Schema.optionalKey( + Schema.String.annotate({ + "description": "A description for the vector store. Can be used to describe the vector store's purpose." + }) + ), + "expires_after": Schema.optionalKey(VectorStoreExpirationAfter), + "chunking_strategy": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": Schema.Literal("auto").annotate({ "description": "Always `auto`." }) }).annotate({ + "title": "Auto Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty." + }), + Schema.Struct({ + "type": Schema.Literal("static").annotate({ "description": "Always `static`." }), + "static": StaticChunkingStrategy + }).annotate({ + "title": "Static Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy. Only applicable if `file_ids` is non-empty." + }) + ], { mode: "oneOf" }) + ), + "metadata": Schema.optionalKey(Metadata) +}) +export type VectorStoreObject = { + readonly "id": string + readonly "object": "vector_store" + readonly "created_at": number + readonly "name": string + readonly "usage_bytes": number + readonly "file_counts": { + readonly "in_progress": number + readonly "completed": number + readonly "failed": number + readonly "cancelled": number + readonly "total": number + } + readonly "status": "expired" | "in_progress" | "completed" + readonly "expires_after"?: VectorStoreExpirationAfter + readonly "expires_at"?: number | null + readonly "last_active_at": number | null + readonly "metadata": Metadata +} +export const VectorStoreObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints." }), + "object": Schema.Literal("vector_store").annotate({ + "description": "The object type, which is always `vector_store`." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the vector store was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "name": Schema.String.annotate({ "description": "The name of the vector store." }), + "usage_bytes": Schema.Number.annotate({ + "description": "The total number of bytes used by the files in the vector store." + }).check(Schema.isInt()), + "file_counts": Schema.Struct({ + "in_progress": Schema.Number.annotate({ "description": "The number of files that are currently being processed." }) + .check(Schema.isInt()), + "completed": Schema.Number.annotate({ "description": "The number of files that have been successfully processed." }) + .check(Schema.isInt()), + "failed": Schema.Number.annotate({ "description": "The number of files that have failed to process." }).check( + Schema.isInt() + ), + "cancelled": Schema.Number.annotate({ "description": "The number of files that were cancelled." }).check( + Schema.isInt() + ), + "total": Schema.Number.annotate({ "description": "The total number of files." }).check(Schema.isInt()) + }), + "status": Schema.Literals(["expired", "in_progress", "completed"]).annotate({ + "description": + "The status of the vector store, which can be either `expired`, `in_progress`, or `completed`. A status of `completed` indicates that the vector store is ready for use." + }), + "expires_after": Schema.optionalKey(VectorStoreExpirationAfter), + "expires_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the vector store will expire.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "last_active_at": Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the vector store was last active.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "metadata": Metadata +}).annotate({ + "title": "Vector store", + "description": "A vector store is a collection of processed files can be used by the `file_search` tool." +}) +export type FileSearchToolCall = { + readonly "id": string + readonly "type": "file_search_call" + readonly "status": "in_progress" | "searching" | "completed" | "incomplete" | "failed" + readonly "queries": ReadonlyArray + readonly "results"?: + | ReadonlyArray< + { + readonly "file_id"?: string + readonly "text"?: string + readonly "filename"?: string + readonly "attributes"?: VectorStoreFileAttributes + readonly "score"?: number + } + > + | null +} +export const FileSearchToolCall = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the file search tool call.\n" }), + "type": Schema.Literal("file_search_call").annotate({ + "description": "The type of the file search tool call. Always `file_search_call`.\n" + }), + "status": Schema.Literals(["in_progress", "searching", "completed", "incomplete", "failed"]).annotate({ + "description": + "The status of the file search tool call. One of `in_progress`,\n`searching`, `incomplete` or `failed`,\n" + }), + "queries": Schema.Array(Schema.String).annotate({ "description": "The queries used to search for files.\n" }), + "results": Schema.optionalKey(Schema.Union([ + Schema.Array(Schema.Struct({ + "file_id": Schema.optionalKey(Schema.String.annotate({ "description": "The unique ID of the file.\n" })), + "text": Schema.optionalKey( + Schema.String.annotate({ "description": "The text that was retrieved from the file.\n" }) + ), + "filename": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the file.\n" })), + "attributes": Schema.optionalKey(VectorStoreFileAttributes), + "score": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The relevance score of the file - a value between 0 and 1.\n", + "format": "float" + }).check(Schema.isFinite()) + ) + })).annotate({ "description": "The results of the file search tool call.\n" }), + Schema.Null + ])) +}).annotate({ + "title": "File search tool call", + "description": + "The results of a file search tool call. See the\n[file search guide](/docs/guides/tools-file-search) for more information.\n" +}) +export type UpdateVectorStoreFileAttributesRequest = { readonly "attributes": VectorStoreFileAttributes } +export const UpdateVectorStoreFileAttributesRequest = Schema.Struct({ "attributes": VectorStoreFileAttributes }) +export type VectorStoreFileObject = { + readonly "id": string + readonly "object": "vector_store.file" + readonly "usage_bytes": number + readonly "created_at": number + readonly "vector_store_id": string + readonly "status": "in_progress" | "completed" | "cancelled" | "failed" + readonly "last_error": { + readonly "code": "server_error" | "unsupported_file" | "invalid_file" + readonly "message": string + } | null + readonly "chunking_strategy"?: { readonly "type": "static"; readonly "static": StaticChunkingStrategy } | { + readonly "type": "other" + } + readonly "attributes"?: VectorStoreFileAttributes +} +export const VectorStoreFileObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints." }), + "object": Schema.Literal("vector_store.file").annotate({ + "description": "The object type, which is always `vector_store.file`." + }), + "usage_bytes": Schema.Number.annotate({ + "description": "The total vector store usage in bytes. Note that this may be different from the original file size." + }).check(Schema.isInt()), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the vector store file was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "vector_store_id": Schema.String.annotate({ + "description": + "The ID of the [vector store](/docs/api-reference/vector-stores/object) that the [File](/docs/api-reference/files) is attached to." + }), + "status": Schema.Literals(["in_progress", "completed", "cancelled", "failed"]).annotate({ + "description": + "The status of the vector store file, which can be either `in_progress`, `completed`, `cancelled`, or `failed`. The status `completed` indicates that the vector store file is ready for use." + }), + "last_error": Schema.Union([ + Schema.Struct({ + "code": Schema.Literals(["server_error", "unsupported_file", "invalid_file"]).annotate({ + "description": "One of `server_error`, `unsupported_file`, or `invalid_file`." + }), + "message": Schema.String.annotate({ "description": "A human-readable description of the error." }) + }).annotate({ + "description": "The last error associated with this vector store file. Will be `null` if there are no errors." + }), + Schema.Null + ]), + "chunking_strategy": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("static").annotate({ "description": "Always `static`." }), + "static": StaticChunkingStrategy + }).annotate({ "title": "Static Chunking Strategy", "description": "The strategy used to chunk the file." }), + Schema.Struct({ "type": Schema.Literal("other").annotate({ "description": "Always `other`." }) }).annotate({ + "title": "Other Chunking Strategy", + "description": "The strategy used to chunk the file." + }) + ], { mode: "oneOf" }) + ), + "attributes": Schema.optionalKey(VectorStoreFileAttributes) +}).annotate({ "title": "Vector store files", "description": "A list of files attached to a vector store." }) +export type VectorStoreSearchResultItem = { + readonly "file_id": string + readonly "filename": string + readonly "score": number + readonly "attributes": VectorStoreFileAttributes + readonly "content": ReadonlyArray +} +export const VectorStoreSearchResultItem = Schema.Struct({ + "file_id": Schema.String.annotate({ "description": "The ID of the vector store file." }), + "filename": Schema.String.annotate({ "description": "The name of the vector store file." }), + "score": Schema.Number.annotate({ "description": "The similarity score for the result." }).check(Schema.isFinite()) + .check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + "attributes": VectorStoreFileAttributes, + "content": Schema.Array(VectorStoreSearchResultContentObject).annotate({ + "description": "Content chunks from the file." + }) +}) +export type VoiceConsentListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const VoiceConsentListResource = Schema.Struct({ + "object": Schema.Literal("list"), + "data": Schema.Array(VoiceConsentResource), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type CreateSpeechRequest = { + readonly "model": string | "tts-1" | "tts-1-hd" | "gpt-4o-mini-tts" | "gpt-4o-mini-tts-2025-12-15" + readonly "input": string + readonly "instructions"?: string + readonly "voice": VoiceIdsShared | { readonly "id": string } + readonly "response_format"?: "mp3" | "opus" | "aac" | "flac" | "wav" | "pcm" + readonly "speed"?: number + readonly "stream_format"?: "sse" | "audio" +} +export const CreateSpeechRequest = Schema.Struct({ + "model": Schema.Union([ + Schema.String, + Schema.Literals(["tts-1", "tts-1-hd", "gpt-4o-mini-tts", "gpt-4o-mini-tts-2025-12-15"]) + ]).annotate({ + "description": + "One of the available [TTS models](/docs/models#tts): `tts-1`, `tts-1-hd`, `gpt-4o-mini-tts`, or `gpt-4o-mini-tts-2025-12-15`.\n" + }), + "input": Schema.String.annotate({ + "description": "The text to generate audio for. The maximum length is 4096 characters." + }).check(Schema.isMaxLength(4096)), + "instructions": Schema.optionalKey( + Schema.String.annotate({ + "description": + "Control the voice of your generated audio with additional instructions. Does not work with `tts-1` or `tts-1-hd`." + }).check(Schema.isMaxLength(4096)) + ), + "voice": Schema.Union([ + VoiceIdsShared, + Schema.Struct({ "id": Schema.String.annotate({ "description": "The custom voice ID, e.g. `voice_1234`." }) }) + .annotate({ "description": "Custom voice reference." }) + ]).annotate({ + "title": "Voice", + "description": + "The voice to use when generating the audio. Supported built-in voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `onyx`, `nova`, `sage`, `shimmer`, `verse`, `marin`, and `cedar`. You may also provide a custom voice object with an `id`, for example `{ \"id\": \"voice_1234\" }`. Previews of the voices are available in the [Text to speech guide](/docs/guides/text-to-speech#voice-options)." + }), + "response_format": Schema.optionalKey( + Schema.Literals(["mp3", "opus", "aac", "flac", "wav", "pcm"]).annotate({ + "description": "The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, `wav`, and `pcm`." + }) + ), + "speed": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is the default." + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0.25)).check(Schema.isLessThanOrEqualTo(4)) + ), + "stream_format": Schema.optionalKey( + Schema.Literals(["sse", "audio"]).annotate({ + "description": + "The format to stream the audio in. Supported formats are `sse` and `audio`. `sse` is not supported for `tts-1` or `tts-1-hd`." + }) + ) +}) +export type RealtimeSessionCreateResponse = { + readonly "id"?: string + readonly "object"?: string + readonly "expires_at"?: number + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> + readonly "model"?: string + readonly "output_modalities"?: ReadonlyArray<"text" | "audio"> + readonly "instructions"?: string + readonly "audio"?: { + readonly "input"?: { + readonly "format"?: RealtimeAudioFormats + readonly "transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + } + readonly "noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "turn_detection"?: { + readonly "type"?: string + readonly "threshold"?: number + readonly "prefix_padding_ms"?: number + readonly "silence_duration_ms"?: number + } + } + readonly "output"?: { + readonly "format"?: RealtimeAudioFormats + readonly "voice"?: VoiceIdsShared + readonly "speed"?: number + } + } + readonly "tracing"?: "auto" | { + readonly "workflow_name"?: string + readonly "group_id"?: string + readonly "metadata"?: {} + } + readonly "turn_detection"?: { + readonly "type"?: string + readonly "threshold"?: number + readonly "prefix_padding_ms"?: number + readonly "silence_duration_ms"?: number + } + readonly "tools"?: ReadonlyArray + readonly "tool_choice"?: string + readonly "max_output_tokens"?: number | "inf" +} +export const RealtimeSessionCreateResponse = Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }) + ), + "object": Schema.optionalKey( + Schema.String.annotate({ "description": "The object type. Always `realtime.session`." }) + ), + "expires_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Expiration timestamp for the session, in seconds since epoch.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "include": Schema.optionalKey( + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }) + ), + "model": Schema.optionalKey(Schema.String.annotate({ "description": "The Realtime model used for this session." })), + "output_modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": "The set of modalities the model can respond with. To disable audio,\nset this to [\"text\"].\n" + }) + ), + "instructions": Schema.optionalKey(Schema.String.annotate({ + "description": + "The default system instructions (i.e. system message) prepended to model\ncalls. This field allows the client to guide the model on desired\nresponses. The model can be instructed on response content and format,\n(e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good\nresponses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion\ninto your voice\", \"laugh frequently\"). The instructions are not guaranteed\nto be followed by the model, but they provide guidance to the model on the\ndesired behavior.\n\nNote that the server sets default instructions which will be used if this\nfield is not set and are visible in the `session.created` event at the\nstart of the session.\n" + })), + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey(RealtimeAudioFormats), + "transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model used for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`.\n" + }) + ), + "language": Schema.optionalKey( + Schema.String.annotate({ "description": "The language of the input audio.\n" }) + ), + "prompt": Schema.optionalKey( + Schema.String.annotate({ + "description": "The prompt configured for input audio transcription, when present.\n" + }) + ) + }).annotate({ "description": "Configuration for input audio transcription.\n" }) + ), + "noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": "Configuration for input audio noise reduction.\n" + }) + ), + "turn_detection": Schema.optionalKey( + Schema.Struct({ + "type": Schema.optionalKey( + Schema.String.annotate({ + "description": "Type of turn detection, only `server_vad` is currently supported.\n" + }) + ), + "threshold": Schema.optionalKey(Schema.Number.check(Schema.isFinite())), + "prefix_padding_ms": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "silence_duration_ms": Schema.optionalKey(Schema.Number.check(Schema.isInt())) + }).annotate({ "description": "Configuration for turn detection.\n" }) + ) + })), + "output": Schema.optionalKey( + Schema.Struct({ + "format": Schema.optionalKey(RealtimeAudioFormats), + "voice": Schema.optionalKey(VoiceIdsShared), + "speed": Schema.optionalKey(Schema.Number.check(Schema.isFinite())) + }) + ) + }).annotate({ "description": "Configuration for input and output audio for the session.\n" }) + ), + "tracing": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto").annotate({ "description": "Default tracing mode for the session.\n" }), + Schema.Struct({ + "workflow_name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n" + }) + ), + "group_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n" + }) + ), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": + "The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n" + }) + ) + }).annotate({ "title": "Tracing Configuration", "description": "Granular configuration for tracing.\n" }) + ], { mode: "oneOf" }).annotate({ + "title": "Tracing Configuration", + "description": + "Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n" + }) + ), + "turn_detection": Schema.optionalKey( + Schema.Struct({ + "type": Schema.optionalKey( + Schema.String.annotate({ "description": "Type of turn detection, only `server_vad` is currently supported.\n" }) + ), + "threshold": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }).check(Schema.isFinite()) + ), + "prefix_padding_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }).check(Schema.isInt()) + ), + "silence_duration_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + }).check(Schema.isInt()) + ) + }).annotate({ + "description": + "Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n" + }) + ), + "tools": Schema.optionalKey( + Schema.Array(RealtimeFunctionTool).annotate({ "description": "Tools (functions) available to the model." }) + ), + "tool_choice": Schema.optionalKey( + Schema.String.annotate({ + "description": "How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n" + }) + ), + "max_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n" + }) + ) +}).annotate({ + "title": "Realtime session configuration object", + "description": "A Realtime session configuration object.\n" +}) +export type WebSearchTool = { + readonly "type": "web_search" | "web_search_2025_08_26" + readonly "filters"?: { readonly "allowed_domains"?: ReadonlyArray | null } | null + readonly "user_location"?: WebSearchApproximateLocation + readonly "search_context_size"?: "low" | "medium" | "high" +} +export const WebSearchTool = Schema.Struct({ + "type": Schema.Literals(["web_search", "web_search_2025_08_26"]).annotate({ + "description": "The type of the web search tool. One of `web_search` or `web_search_2025_08_26`." + }), + "filters": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "allowed_domains": Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String.annotate({ "description": "Allowed domain for the search." })).annotate({ + "title": "Allowed domains for the search.", + "description": + "Allowed domains for the search. If not provided, all domains are allowed.\nSubdomains of the provided domains are allowed as well.\n\nExample: `[\"pubmed.ncbi.nlm.nih.gov\"]`\n" + }), + Schema.Null + ]) + ) + }).annotate({ "description": "Filters for the search.\n" }), + Schema.Null + ])), + "user_location": Schema.optionalKey(WebSearchApproximateLocation), + "search_context_size": Schema.optionalKey( + Schema.Literals(["low", "medium", "high"]).annotate({ + "description": + "High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default." + }) + ) +}).annotate({ + "title": "Web search", + "description": + "Search the Internet for sources related to the prompt. Learn more about the\n[web search tool](/docs/guides/tools-web-search).\n" +}) +export type ContainerNetworkPolicyAllowlistParam = { + readonly "type": "allowlist" + readonly "allowed_domains": ReadonlyArray + readonly "domain_secrets"?: ReadonlyArray +} +export const ContainerNetworkPolicyAllowlistParam = Schema.Struct({ + "type": Schema.Literal("allowlist").annotate({ + "description": "Allow outbound network access only to specified domains. Always `allowlist`." + }), + "allowed_domains": Schema.Array(Schema.String).annotate({ + "description": "A list of allowed domains when type is `allowlist`." + }).check(Schema.isMinLength(1)), + "domain_secrets": Schema.optionalKey( + Schema.Array(ContainerNetworkPolicyDomainSecretParam).annotate({ + "description": "Optional domain-scoped secrets for allowlisted domains." + }).check(Schema.isMinLength(1)) + ) +}) +export type EvalItemContentItem = + | EvalItemContentText + | InputTextContent + | EvalItemContentOutputText + | EvalItemInputImage + | InputAudio +export const EvalItemContentItem = Schema.Union([ + EvalItemContentText, + InputTextContent, + EvalItemContentOutputText, + EvalItemInputImage, + InputAudio +], { mode: "oneOf" }).annotate({ + "title": "Eval content item", + "description": "A single content item: input text, output text, input image, or input audio.\n" +}) +export type Annotation = FileCitationBody | UrlCitationBody | ContainerFileCitationBody | FilePath +export const Annotation = Schema.Union([FileCitationBody, UrlCitationBody, ContainerFileCitationBody, FilePath], { + mode: "oneOf" +}).annotate({ "description": "An annotation that applies to a span of output text." }) +export type LogProb = { + readonly "token": string + readonly "logprob": number + readonly "bytes": ReadonlyArray + readonly "top_logprobs": ReadonlyArray +} +export const LogProb = Schema.Struct({ + "token": Schema.String, + "logprob": Schema.Number.check(Schema.isFinite()), + "bytes": Schema.Array(Schema.Number.check(Schema.isInt())), + "top_logprobs": Schema.Array(TopLogProb) +}).annotate({ "title": "Log probability", "description": "The log probability of a token." }) +export type ReasoningItem = { + readonly "type": "reasoning" + readonly "id": string + readonly "encrypted_content"?: string | null + readonly "summary": ReadonlyArray + readonly "content"?: ReadonlyArray + readonly "status"?: "in_progress" | "completed" | "incomplete" +} +export const ReasoningItem = Schema.Struct({ + "type": Schema.Literal("reasoning").annotate({ "description": "The type of the object. Always `reasoning`.\n" }), + "id": Schema.String.annotate({ "description": "The unique identifier of the reasoning content.\n" }), + "encrypted_content": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The encrypted content of the reasoning item - populated when a response is\ngenerated with `reasoning.encrypted_content` in the `include` parameter.\n" + }), + Schema.Null + ]) + ), + "summary": Schema.Array(SummaryTextContent).annotate({ "description": "Reasoning summary content.\n" }), + "content": Schema.optionalKey( + Schema.Array(ReasoningTextContent).annotate({ "description": "Reasoning text content.\n" }) + ), + "status": Schema.optionalKey( + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + ) +}).annotate({ + "title": "Reasoning", + "description": + "A description of the chain of thought used by a reasoning model while generating\na response. Be sure to include these items in your `input` to the Responses API\nfor subsequent turns of a conversation if you are manually\n[managing context](/docs/guides/conversation-state).\n" +}) +export type FunctionAndCustomToolCallOutput = InputTextContent | InputImageContent | InputFileContent +export const FunctionAndCustomToolCallOutput = Schema.Union([InputTextContent, InputImageContent, InputFileContent], { + mode: "oneOf" +}) +export type InputContent = InputTextContent | InputImageContent | InputFileContent +export const InputContent = Schema.Union([InputTextContent, InputImageContent, InputFileContent], { mode: "oneOf" }) +export type DragParam = { + readonly "type": "drag" + readonly "path": ReadonlyArray + readonly "keys"?: ReadonlyArray | null +} +export const DragParam = Schema.Struct({ + "type": Schema.Literal("drag").annotate({ + "description": "Specifies the event type. For a drag action, this property is always set to `drag`." + }), + "path": Schema.Array(CoordParam).annotate({ + "description": + "An array of coordinates representing the path of the drag action. Coordinates will appear as an array of objects, eg\n```\n[\n { x: 100, y: 200 },\n { x: 200, y: 300 }\n]\n```" + }), + "keys": Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.String).annotate({ "description": "The keys being held while dragging the mouse." }), + Schema.Null + ]) + ) +}).annotate({ "title": "Drag", "description": "A drag action." }) +export type ComputerToolCallOutputResource = { + readonly "type": "computer_call_output" + readonly "id": string + readonly "call_id": string + readonly "acknowledged_safety_checks"?: ReadonlyArray + readonly "output": ComputerScreenshotImage + readonly "status": "completed" | "incomplete" + readonly "created_by"?: string +} +export const ComputerToolCallOutputResource = Schema.Struct({ + "type": Schema.Literal("computer_call_output").annotate({ + "description": "The type of the computer tool call output. Always `computer_call_output`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the computer call tool output.\n" }), + "call_id": Schema.String.annotate({ "description": "The ID of the computer tool call that produced the output.\n" }), + "acknowledged_safety_checks": Schema.optionalKey( + Schema.Array(ComputerCallSafetyCheckParam).annotate({ + "description": "The safety checks reported by the API that have been acknowledged by the\ndeveloper.\n" + }) + ), + "output": ComputerScreenshotImage, + "status": Schema.Union([ + Schema.Literal("completed").annotate({ + "description": + "The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n" + }), + Schema.Literal("incomplete").annotate({ + "description": + "The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n" + }) + ]).annotate({ + "description": + "The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n" + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item.\n" }) + ) +}).annotate({ "title": "Computer tool call output", "description": "The output of a computer tool call.\n" }) +export type CreateImageEditRequest = { + readonly "image": string | ReadonlyArray + readonly "prompt": string + readonly "mask"?: string + readonly "background"?: "transparent" | "opaque" | "auto" | null + readonly "model"?: + | string + | "gpt-image-1.5" + | "dall-e-2" + | "gpt-image-1" + | "gpt-image-1-mini" + | "chatgpt-image-latest" + | null + readonly "n"?: number + readonly "size"?: string | "256x256" | "512x512" | "1024x1024" | "1536x1024" | "1024x1536" | "auto" | null + readonly "response_format"?: "url" | "b64_json" | null + readonly "output_format"?: "png" | "jpeg" | "webp" | null + readonly "output_compression"?: number | null + readonly "user"?: string + readonly "input_fidelity"?: InputFidelity | null + readonly "stream"?: boolean | null + readonly "partial_images"?: PartialImages + readonly "quality"?: "standard" | "low" | "medium" | "high" | "auto" | null +} +export const CreateImageEditRequest = Schema.Struct({ + "image": Schema.Union([ + Schema.String.annotate({ "format": "binary" }), + Schema.Array(Schema.String.annotate({ "format": "binary" })).check(Schema.isMaxLength(16)) + ]).annotate({ + "description": + "The image(s) to edit. Must be a supported image file or an array of images.\n\nFor the GPT image models (`gpt-image-1`, `gpt-image-1-mini`, and `gpt-image-1.5`), each image should be a `png`, `webp`, or `jpg`\nfile less than 50MB. You can provide up to 16 images.\n`chatgpt-image-latest` follows the same input constraints as GPT image models.\n\nFor `dall-e-2`, you can only provide one image, and it should be a square\n`png` file less than 4MB.\n" + }), + "prompt": Schema.String.annotate({ + "description": + "A text description of the desired image(s). The maximum length is 1000 characters for `dall-e-2`, and 32000 characters for the GPT image models." + }), + "mask": Schema.optionalKey(Schema.String.annotate({ + "description": + "An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. If there are multiple images provided, the mask will be applied on the first image. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`.", + "format": "binary" + })), + "background": Schema.optionalKey(Schema.Union([ + Schema.Literals(["transparent", "opaque", "auto"]).annotate({ + "description": + "Allows to set transparency for the background of the generated image(s).\nThis parameter is only supported for the GPT image models. Must be one of\n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the\nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it\nshould be set to either `png` (default value) or `webp`.\n" + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "Allows to set transparency for the background of the generated image(s).\nThis parameter is only supported for the GPT image models. Must be one of\n`transparent`, `opaque` or `auto` (default value). When `auto` is used, the\nmodel will automatically determine the best background for the image.\n\nIf `transparent`, the output format needs to support transparency, so it\nshould be set to either `png` (default value) or `webp`.\n" + }) + ])), + "model": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.String, + Schema.Literals(["gpt-image-1.5", "dall-e-2", "gpt-image-1", "gpt-image-1-mini", "chatgpt-image-latest"]) + ]).annotate({ "description": "The model to use for image generation. Defaults to `gpt-image-1.5`." }), + Schema.Null + ]) + ), + "n": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(10)], { + "description": "The number of images to generate. Must be between 1 and 10." + }) + ) + ]) + ), + "size": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.String, + Schema.Literals(["256x256", "512x512", "1024x1024", "1536x1024", "1024x1536", "auto"]) + ]).annotate({ + "description": + "The size of the generated images. For `gpt-image-2` and `gpt-image-2-2026-04-21`, arbitrary resolutions are supported as `WIDTHxHEIGHT` strings, for example `1536x864`. Width and height must both be divisible by 16 and the requested aspect ratio must be between 1:3 and 3:1. Resolutions above `2560x1440` are experimental, and the maximum supported resolution is `3840x2160`. The requested size must also satisfy the model's current pixel and edge limits. The standard sizes `1024x1024`, `1536x1024`, and `1024x1536` are supported by the GPT image models; `auto` is supported for models that allow automatic sizing. For `dall-e-2`, use one of `256x256`, `512x512`, or `1024x1024`. For `dall-e-3`, use one of `1024x1024`, `1792x1024`, or `1024x1792`." + }), + Schema.Null + ]) + ), + "response_format": Schema.optionalKey(Schema.Union([ + Schema.Literals(["url", "b64_json"]).annotate({ + "description": + "The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2` (default is `url` for `dall-e-2`), as GPT image models always return base64-encoded images." + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "The format in which the generated images are returned. Must be one of `url` or `b64_json`. URLs are only valid for 60 minutes after the image has been generated. This parameter is only supported for `dall-e-2` (default is `url` for `dall-e-2`), as GPT image models always return base64-encoded images." + }) + ])), + "output_format": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["png", "jpeg", "webp"]).annotate({ + "description": + "The format in which the generated images are returned. This parameter is\nonly supported for the GPT image models. Must be one of `png`, `jpeg`, or `webp`.\nThe default value is `png`.\n" + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "The format in which the generated images are returned. This parameter is\nonly supported for the GPT image models. Must be one of `png`, `jpeg`, or `webp`.\nThe default value is `png`.\n" + }) + ]) + ), + "output_compression": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "description": + "The compression level (0-100%) for the generated images. This parameter\nis only supported for the GPT image models with the `webp` or `jpeg` output\nformats, and defaults to 100.\n" + }) + ), + "user": Schema.optionalKey( + Schema.String.annotate({ + "description": + "A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices#end-user-ids).\n" + }) + ), + "input_fidelity": Schema.optionalKey(Schema.Union([InputFidelity, Schema.Null])), + "stream": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": + "Edit the image in streaming mode. Defaults to `false`. See the\n[Image generation guide](/docs/guides/image-generation) for more information.\n" + }) + ), + "partial_images": Schema.optionalKey(PartialImages), + "quality": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["standard", "low", "medium", "high", "auto"]).annotate({ + "description": "The quality of the image that will be generated for GPT image models. Defaults to `auto`.\n" + }), + Schema.Union([Schema.Null]).annotate({ + "description": "The quality of the image that will be generated for GPT image models. Defaults to `auto`.\n" + }) + ]) + ) +}) +export type ImageGenTool = { + readonly "type": "image_generation" + readonly "model"?: string | "gpt-image-1" | "gpt-image-1-mini" | "gpt-image-1.5" + readonly "quality"?: "low" | "medium" | "high" | "auto" + readonly "size"?: string | "1024x1024" | "1024x1536" | "1536x1024" | "auto" + readonly "output_format"?: "png" | "webp" | "jpeg" + readonly "output_compression"?: number + readonly "moderation"?: "auto" | "low" + readonly "background"?: "transparent" | "opaque" | "auto" + readonly "input_fidelity"?: InputFidelity | null + readonly "input_image_mask"?: { readonly "image_url"?: string; readonly "file_id"?: string } + readonly "partial_images"?: number + readonly "action"?: "generate" | "edit" | "auto" +} +export const ImageGenTool = Schema.Struct({ + "type": Schema.Literal("image_generation").annotate({ + "description": "The type of the image generation tool. Always `image_generation`.\n" + }), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals(["gpt-image-1", "gpt-image-1-mini", "gpt-image-1.5"]).annotate({ + "description": "The image generation model to use. Default: `gpt-image-1`.\n" + }) + ]) + ), + "quality": Schema.optionalKey( + Schema.Literals(["low", "medium", "high", "auto"]).annotate({ + "description": + "The quality of the generated image. One of `low`, `medium`, `high`,\nor `auto`. Default: `auto`.\n" + }) + ), + "size": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Literals(["1024x1024", "1024x1536", "1536x1024", "auto"])]).annotate({ + "description": + "The size of the generated images. For `gpt-image-2` and `gpt-image-2-2026-04-21`, arbitrary resolutions are supported as `WIDTHxHEIGHT` strings, for example `1536x864`. Width and height must both be divisible by 16 and the requested aspect ratio must be between 1:3 and 3:1. Resolutions above `2560x1440` are experimental, and the maximum supported resolution is `3840x2160`. The requested size must also satisfy the model's current pixel and edge limits. The standard sizes `1024x1024`, `1536x1024`, and `1024x1536` are supported by the GPT image models; `auto` is supported for models that allow automatic sizing. For `dall-e-2`, use one of `256x256`, `512x512`, or `1024x1024`. For `dall-e-3`, use one of `1024x1024`, `1792x1024`, or `1024x1792`." + }) + ), + "output_format": Schema.optionalKey( + Schema.Literals(["png", "webp", "jpeg"]).annotate({ + "description": "The output format of the generated image. One of `png`, `webp`, or\n`jpeg`. Default: `png`.\n" + }) + ), + "output_compression": Schema.optionalKey( + Schema.Number.annotate({ "description": "Compression level for the output image. Default: 100.\n" }).check( + Schema.isInt() + ).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(100)) + ), + "moderation": Schema.optionalKey( + Schema.Literals(["auto", "low"]).annotate({ + "description": "Moderation level for the generated image. Default: `auto`.\n" + }) + ), + "background": Schema.optionalKey( + Schema.Literals(["transparent", "opaque", "auto"]).annotate({ + "description": + "Background type for the generated image. One of `transparent`,\n`opaque`, or `auto`. Default: `auto`.\n" + }) + ), + "input_fidelity": Schema.optionalKey(Schema.Union([InputFidelity, Schema.Null])), + "input_image_mask": Schema.optionalKey( + Schema.Struct({ + "image_url": Schema.optionalKey(Schema.String.annotate({ "description": "Base64-encoded mask image.\n" })), + "file_id": Schema.optionalKey(Schema.String.annotate({ "description": "File ID for the mask image.\n" })) + }).annotate({ + "description": + "Optional mask for inpainting. Contains `image_url`\n(string, optional) and `file_id` (string, optional).\n" + }) + ), + "partial_images": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Number of partial images to generate in streaming mode, from 0 (default value) to 3.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(3)) + ), + "action": Schema.optionalKey( + Schema.Literals(["generate", "edit", "auto"]).annotate({ + "description": "Whether to generate a new image or edit an existing image. Default: `auto`.\n" + }) + ) +}).annotate({ + "title": "Image generation tool", + "description": "A tool that generates images using the GPT image models.\n" +}) +export type LocalEnvironmentParam = { readonly "type": "local"; readonly "skills"?: ReadonlyArray } +export const LocalEnvironmentParam = Schema.Struct({ + "type": Schema.Literal("local").annotate({ "description": "Use a local computer environment." }), + "skills": Schema.optionalKey( + Schema.Array(LocalSkillParam).annotate({ "description": "An optional list of skills." }).check( + Schema.isMaxLength(200) + ) + ) +}) +export type CustomToolParam = { + readonly "type": "custom" + readonly "name": string + readonly "description"?: string + readonly "format"?: CustomTextFormatParam | CustomGrammarFormatParam + readonly "defer_loading"?: boolean +} +export const CustomToolParam = Schema.Struct({ + "type": Schema.Literal("custom").annotate({ "description": "The type of the custom tool. Always `custom`." }), + "name": Schema.String.annotate({ "description": "The name of the custom tool, used to identify it in tool calls." }), + "description": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional description of the custom tool, used to provide more context." }) + ), + "format": Schema.optionalKey( + Schema.Union([CustomTextFormatParam, CustomGrammarFormatParam], { mode: "oneOf" }).annotate({ + "description": "The input format for the custom tool. Default is unconstrained text." + }) + ), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether this tool should be deferred and discovered via tool search." }) + ) +}).annotate({ + "title": "Custom tool", + "description": + "A custom tool that processes input using a specified format. Learn more about [custom tools](/docs/guides/function-calling#custom-tools)" +}) +export type FunctionToolParam = { + readonly "name": string + readonly "description"?: string | null + readonly "parameters"?: EmptyModelParam | null + readonly "strict"?: boolean | null + readonly "type": "function" + readonly "defer_loading"?: boolean +} +export const FunctionToolParam = Schema.Struct({ + "name": Schema.String.check(Schema.isMinLength(1)).check(Schema.isMaxLength(128)).check( + Schema.isPattern(new RegExp("^[a-zA-Z0-9_-]+$")) + ), + "description": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "parameters": Schema.optionalKey(Schema.Union([EmptyModelParam, Schema.Null])), + "strict": Schema.optionalKey(Schema.Union([Schema.Boolean, Schema.Null])), + "type": Schema.Literal("function"), + "defer_loading": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": "Whether this function should be deferred and discovered via tool search." + }) + ) +}) +export type WebSearchPreviewTool = { + readonly "type": "web_search_preview" | "web_search_preview_2025_03_11" + readonly "user_location"?: { + readonly "type": "approximate" + readonly "country"?: string | null + readonly "region"?: string | null + readonly "city"?: string | null + readonly "timezone"?: string | null + } | null + readonly "search_context_size"?: "low" | "medium" | "high" + readonly "search_content_types"?: ReadonlyArray +} +export const WebSearchPreviewTool = Schema.Struct({ + "type": Schema.Literals(["web_search_preview", "web_search_preview_2025_03_11"]).annotate({ + "description": "The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`." + }), + "user_location": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("approximate").annotate({ + "description": "The type of location approximation. Always `approximate`." + }), + "country": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`." + }), + Schema.Null + ]) + ), + "region": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "Free text input for the region of the user, e.g. `California`." }), + Schema.Null + ]) + ), + "city": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "Free text input for the city of the user, e.g. `San Francisco`." }), + Schema.Null + ]) + ), + "timezone": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`." + }), + Schema.Null + ]) + ) + }).annotate({ "description": "The user's location." }), + Schema.Null + ])), + "search_context_size": Schema.optionalKey( + Schema.Literals(["low", "medium", "high"]).annotate({ + "description": + "High level guidance for the amount of context window space to use for the search. One of `low`, `medium`, or `high`. `medium` is the default." + }) + ), + "search_content_types": Schema.optionalKey(Schema.Array(SearchContentType)) +}).annotate({ + "title": "Web search preview", + "description": + "This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search)." +}) +export type CodeInterpreterToolCall = { + readonly "type": "code_interpreter_call" + readonly "id": string + readonly "status": "in_progress" | "completed" | "incomplete" | "interpreting" | "failed" + readonly "container_id": string + readonly "code": string | null + readonly "outputs": ReadonlyArray | null +} +export const CodeInterpreterToolCall = Schema.Struct({ + "type": Schema.Literal("code_interpreter_call").annotate({ + "description": "The type of the code interpreter tool call. Always `code_interpreter_call`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the code interpreter tool call.\n" }), + "status": Schema.Literals(["in_progress", "completed", "incomplete", "interpreting", "failed"]).annotate({ + "description": + "The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`.\n" + }), + "container_id": Schema.String.annotate({ "description": "The ID of the container used to run the code.\n" }), + "code": Schema.Union([ + Schema.String.annotate({ "description": "The code to run, or null if not available.\n" }), + Schema.Null + ]), + "outputs": Schema.Union([ + Schema.Array(Schema.Union([CodeInterpreterOutputLogs, CodeInterpreterOutputImage], { mode: "oneOf" })).annotate({ + "description": + "The outputs generated by the code interpreter, such as logs or images.\nCan be null if no outputs are available.\n" + }), + Schema.Null + ]) +}).annotate({ "title": "Code interpreter tool call", "description": "A tool call to run code.\n" }) +export type LocalShellToolCall = { + readonly "type": "local_shell_call" + readonly "id": string + readonly "call_id": string + readonly "action": LocalShellExecAction + readonly "status": "in_progress" | "completed" | "incomplete" +} +export const LocalShellToolCall = Schema.Struct({ + "type": Schema.Literal("local_shell_call").annotate({ + "description": "The type of the local shell call. Always `local_shell_call`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the local shell call.\n" }), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the local shell tool call generated by the model.\n" + }), + "action": LocalShellExecAction, + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the local shell call.\n" + }) +}).annotate({ "title": "Local shell call", "description": "A tool call to run a command on the local shell.\n" }) +export type FunctionShellCall = { + readonly "type": "shell_call" + readonly "id": string + readonly "call_id": string + readonly "action": { + readonly "commands": ReadonlyArray + readonly "timeout_ms": number | null + readonly "max_output_length": number | null + } + readonly "status": "in_progress" | "completed" | "incomplete" + readonly "environment": LocalEnvironmentResource | ContainerReferenceResource | null + readonly "created_by"?: string +} +export const FunctionShellCall = Schema.Struct({ + "type": Schema.Literal("shell_call").annotate({ "description": "The type of the item. Always `shell_call`." }), + "id": Schema.String.annotate({ + "description": "The unique ID of the shell tool call. Populated when this item is returned via API." + }), + "call_id": Schema.String.annotate({ "description": "The unique ID of the shell tool call generated by the model." }), + "action": Schema.Struct({ + "commands": Schema.Array(Schema.String.annotate({ "description": "A list of commands to run." })), + "timeout_ms": Schema.Union([ + Schema.Number.annotate({ "description": "Optional timeout in milliseconds for the commands." }).check( + Schema.isInt() + ), + Schema.Null + ]), + "max_output_length": Schema.Union([ + Schema.Number.annotate({ "description": "Optional maximum number of characters to return from each command." }) + .check(Schema.isInt()), + Schema.Null + ]) + }).annotate({ + "title": "Shell exec action", + "description": "The shell commands and limits that describe how to run the tool call." + }), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the shell call. One of `in_progress`, `completed`, or `incomplete`." + }), + "environment": Schema.Union([ + Schema.Union([LocalEnvironmentResource, ContainerReferenceResource], { mode: "oneOf" }), + Schema.Null + ]), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the entity that created this tool call." }) + ) +}).annotate({ + "title": "Shell tool call", + "description": "A tool call that executes one or more shell commands in a managed environment." +}) +export type FunctionShellCallOutputContent = { + readonly "stdout": string + readonly "stderr": string + readonly "outcome": FunctionShellCallOutputTimeoutOutcome | FunctionShellCallOutputExitOutcome + readonly "created_by"?: string +} +export const FunctionShellCallOutputContent = Schema.Struct({ + "stdout": Schema.String.annotate({ "description": "The standard output that was captured." }), + "stderr": Schema.String.annotate({ "description": "The standard error output that was captured." }), + "outcome": Schema.Union([FunctionShellCallOutputTimeoutOutcome, FunctionShellCallOutputExitOutcome], { + mode: "oneOf" + }).annotate({ + "title": "Shell call outcome", + "description": + "Represents either an exit outcome (with an exit code) or a timeout outcome for a shell call output chunk." + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item." }) + ) +}).annotate({ + "title": "Shell call output content", + "description": "The content of a shell tool call output that was emitted." +}) +export type ApplyPatchToolCall = { + readonly "type": "apply_patch_call" + readonly "id": string + readonly "call_id": string + readonly "status": "in_progress" | "completed" + readonly "operation": ApplyPatchCreateFileOperation | ApplyPatchDeleteFileOperation | ApplyPatchUpdateFileOperation + readonly "created_by"?: string +} +export const ApplyPatchToolCall = Schema.Struct({ + "type": Schema.Literal("apply_patch_call").annotate({ + "description": "The type of the item. Always `apply_patch_call`." + }), + "id": Schema.String.annotate({ + "description": "The unique ID of the apply patch tool call. Populated when this item is returned via API." + }), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the apply patch tool call generated by the model." + }), + "status": Schema.Literals(["in_progress", "completed"]).annotate({ + "description": "The status of the apply patch tool call. One of `in_progress` or `completed`." + }), + "operation": Schema.Union([ + ApplyPatchCreateFileOperation, + ApplyPatchDeleteFileOperation, + ApplyPatchUpdateFileOperation + ], { mode: "oneOf" }).annotate({ + "title": "Apply patch operation", + "description": "One of the create_file, delete_file, or update_file operations applied via apply_patch." + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the entity that created this tool call." }) + ) +}).annotate({ + "title": "Apply patch tool call", + "description": "A tool call that applies file diffs by creating, deleting, or updating files." +}) +export type FunctionShellCallOutputContentParam = { + readonly "stdout": string + readonly "stderr": string + readonly "outcome": FunctionShellCallOutputTimeoutOutcomeParam | FunctionShellCallOutputExitOutcomeParam +} +export const FunctionShellCallOutputContentParam = Schema.Struct({ + "stdout": Schema.String.annotate({ "description": "Captured stdout output for the shell call." }).check( + Schema.isMaxLength(10485760) + ), + "stderr": Schema.String.annotate({ "description": "Captured stderr output for the shell call." }).check( + Schema.isMaxLength(10485760) + ), + "outcome": Schema.Union([FunctionShellCallOutputTimeoutOutcomeParam, FunctionShellCallOutputExitOutcomeParam], { + mode: "oneOf" + }).annotate({ + "title": "Shell call outcome", + "description": "The exit or timeout outcome associated with this shell call." + }) +}).annotate({ + "title": "Shell output content", + "description": "Captured stdout and stderr for a portion of a shell tool call output." +}) +export type ImageGenUsage = { + readonly "input_tokens": number + readonly "total_tokens": number + readonly "output_tokens": number + readonly "output_tokens_details"?: ImageGenOutputTokensDetails + readonly "input_tokens_details": ImageGenInputUsageDetails +} +export const ImageGenUsage = Schema.Struct({ + "input_tokens": Schema.Number.annotate({ + "description": "The number of tokens (images and text) in the input prompt." + }).check(Schema.isInt()), + "total_tokens": Schema.Number.annotate({ + "description": "The total number of tokens (images and text) used for the image generation." + }).check(Schema.isInt()), + "output_tokens": Schema.Number.annotate({ "description": "The number of output tokens generated by the model." }) + .check(Schema.isInt()), + "output_tokens_details": Schema.optionalKey(ImageGenOutputTokensDetails), + "input_tokens_details": ImageGenInputUsageDetails +}).annotate({ + "title": "Image generation usage", + "description": "For `gpt-image-1` only, the token usage information for the image generation." +}) +export type ToolChoiceParam = + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMCP + | ToolChoiceCustom + | SpecificApplyPatchParam + | SpecificFunctionShellParam +export const ToolChoiceParam = Schema.Union([ + ToolChoiceOptions, + ToolChoiceAllowed, + ToolChoiceTypes, + ToolChoiceFunction, + ToolChoiceMCP, + ToolChoiceCustom, + SpecificApplyPatchParam, + SpecificFunctionShellParam +], { mode: "oneOf" }).annotate({ + "description": + "How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n" +}) +export type ConversationParam = string | ConversationParam_2 +export const ConversationParam = Schema.Union([ + Schema.String.annotate({ "title": "Conversation ID", "description": "The unique ID of the conversation.\n" }), + ConversationParam_2 +], { mode: "oneOf" }).annotate({ + "description": + "The conversation that this response belongs to. Items from this conversation are prepended to `input_items` for this response request.\nInput items and output items from this response are automatically added to this conversation after this response completes.\n" +}) +export type VideoListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "last_id": string | null + readonly "has_more": boolean +} +export const VideoListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The type of object returned, must be `list`." }), + "data": Schema.Array(VideoResource).annotate({ "description": "A list of items" }), + "first_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the first item in the list." }), + Schema.Null + ]), + "last_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the last item in the list." }), + Schema.Null + ]), + "has_more": Schema.Boolean.annotate({ "description": "Whether there are more items available." }) +}) +export type CreateVideoMultipartBody = { + readonly "model"?: + | string + | "sora-2" + | "sora-2-pro" + | "sora-2-2025-10-06" + | "sora-2-pro-2025-10-06" + | "sora-2-2025-12-08" + readonly "prompt": string + readonly "input_reference"?: string | ImageRefParam_2 + readonly "seconds"?: "4" | "8" | "12" + readonly "size"?: "720x1280" | "1280x720" | "1024x1792" | "1792x1024" +} +export const CreateVideoMultipartBody = Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals(["sora-2", "sora-2-pro", "sora-2-2025-10-06", "sora-2-pro-2025-10-06", "sora-2-2025-12-08"]) + ]).annotate({ + "description": "The video generation model to use (allowed values: sora-2, sora-2-pro). Defaults to `sora-2`." + }) + ), + "prompt": Schema.String.annotate({ "description": "Text prompt that describes the video to generate." }).check( + Schema.isMinLength(1) + ).check(Schema.isMaxLength(32000)), + "input_reference": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "Optional reference asset upload or reference object that guides generation.", + "format": "binary" + }), + ImageRefParam_2 + ], { mode: "oneOf" }) + ), + "seconds": Schema.optionalKey( + Schema.Literals(["4", "8", "12"]).annotate({ + "description": "Clip duration in seconds (allowed values: 4, 8, 12). Defaults to 4 seconds." + }) + ), + "size": Schema.optionalKey( + Schema.Literals(["720x1280", "1280x720", "1024x1792", "1792x1024"]).annotate({ + "description": + "Output resolution formatted as width x height (allowed values: 720x1280, 1280x720, 1024x1792, 1792x1024). Defaults to 720x1280." + }) + ) +}).annotate({ + "title": "Create video multipart request", + "description": "Multipart parameters for creating a new video generation job." +}) +export type CreateVideoEditMultipartBody = { + readonly "video": string | VideoReferenceInputParam + readonly "prompt": string +} +export const CreateVideoEditMultipartBody = Schema.Struct({ + "video": Schema.Union([ + Schema.String.annotate({ "description": "Reference to the completed video to edit.", "format": "binary" }), + VideoReferenceInputParam + ], { mode: "oneOf" }), + "prompt": Schema.String.annotate({ "description": "Text prompt that describes how to edit the source video." }).check( + Schema.isMinLength(1) + ).check(Schema.isMaxLength(32000)) +}).annotate({ + "title": "Create video edit multipart request", + "description": "Parameters for editing an existing generated video." +}) +export type CreateVideoExtendMultipartBody = { + readonly "video": VideoReferenceInputParam | string + readonly "prompt": string + readonly "seconds": "4" | "8" | "12" +} +export const CreateVideoExtendMultipartBody = Schema.Struct({ + "video": Schema.Union([ + VideoReferenceInputParam, + Schema.String.annotate({ "description": "Reference to the completed video to extend.", "format": "binary" }) + ], { mode: "oneOf" }), + "prompt": Schema.String.annotate({ "description": "Updated text prompt that directs the extension generation." }) + .check(Schema.isMinLength(1)).check(Schema.isMaxLength(32000)), + "seconds": Schema.Literals(["4", "8", "12"]).annotate({ + "description": "Length of the newly generated extension segment in seconds (allowed values: 4, 8, 12, 16, 20)." + }) +}).annotate({ + "title": "Create video extension multipart request", + "description": "Multipart parameters for extending an existing generated video." +}) +export type SkillListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "last_id": string | null + readonly "has_more": boolean +} +export const SkillListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The type of object returned, must be `list`." }), + "data": Schema.Array(SkillResource).annotate({ "description": "A list of items" }), + "first_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the first item in the list." }), + Schema.Null + ]), + "last_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the last item in the list." }), + Schema.Null + ]), + "has_more": Schema.Boolean.annotate({ "description": "Whether there are more items available." }) +}) +export type SkillVersionListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "last_id": string | null + readonly "has_more": boolean +} +export const SkillVersionListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The type of object returned, must be `list`." }), + "data": Schema.Array(SkillVersionResource).annotate({ "description": "A list of items" }), + "first_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the first item in the list." }), + Schema.Null + ]), + "last_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the last item in the list." }), + Schema.Null + ]), + "has_more": Schema.Boolean.annotate({ "description": "Whether there are more items available." }) +}) +export type UserMessageItem = { + readonly "id": string + readonly "object": "chatkit.thread_item" + readonly "created_at": number + readonly "thread_id": string + readonly "type": "chatkit.user_message" + readonly "content": ReadonlyArray + readonly "attachments": ReadonlyArray + readonly "inference_options": { + readonly "tool_choice": { readonly "id": string } | null + readonly "model": string | null + } | null +} +export const UserMessageItem = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier of the thread item." }), + "object": Schema.Literal("chatkit.thread_item").annotate({ + "description": "Type discriminator that is always `chatkit.thread_item`." + }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) for when the item was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "thread_id": Schema.String.annotate({ "description": "Identifier of the parent thread." }), + "type": Schema.Literal("chatkit.user_message"), + "content": Schema.Array( + Schema.Union([UserMessageInputText, UserMessageQuotedText], { mode: "oneOf" }).annotate({ + "description": "Content blocks that comprise a user message." + }) + ).annotate({ "description": "Ordered content elements supplied by the user." }), + "attachments": Schema.Array(Attachment).annotate({ + "description": "Attachments associated with the user message. Defaults to an empty list." + }), + "inference_options": Schema.Union([ + Schema.Struct({ + "tool_choice": Schema.Union([ + Schema.Struct({ "id": Schema.String.annotate({ "description": "Identifier of the requested tool." }) }) + .annotate({ + "title": "Tool choice", + "description": "Preferred tool to invoke. Defaults to null when ChatKit should auto-select." + }), + Schema.Null + ]), + "model": Schema.Union([ + Schema.String.annotate({ + "description": "Model name that generated the response. Defaults to null when using the session default." + }), + Schema.Null + ]) + }).annotate({ + "title": "Inference options", + "description": "Inference overrides applied to the message. Defaults to null when unset." + }), + Schema.Null + ]) +}).annotate({ "title": "User Message Item", "description": "User-authored messages within a thread." }) +export type ResponseOutputText = { + readonly "type": "output_text" + readonly "text": string + readonly "annotations": ReadonlyArray +} +export const ResponseOutputText = Schema.Struct({ + "type": Schema.Literal("output_text").annotate({ "description": "Type discriminator that is always `output_text`." }), + "text": Schema.String.annotate({ "description": "Assistant generated text." }), + "annotations": Schema.Array( + Schema.Union([FileAnnotation, UrlAnnotation], { mode: "oneOf" }).annotate({ + "description": "Annotation object describing a cited source." + }) + ).annotate({ "description": "Ordered list of annotations attached to the response text." }) +}).annotate({ + "title": "Assistant message content", + "description": "Assistant response text accompanied by optional annotations." +}) +export type TaskGroupItem = { + readonly "id": string + readonly "object": "chatkit.thread_item" + readonly "created_at": number + readonly "thread_id": string + readonly "type": "chatkit.task_group" + readonly "tasks": ReadonlyArray +} +export const TaskGroupItem = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier of the thread item." }), + "object": Schema.Literal("chatkit.thread_item").annotate({ + "description": "Type discriminator that is always `chatkit.thread_item`." + }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) for when the item was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "thread_id": Schema.String.annotate({ "description": "Identifier of the parent thread." }), + "type": Schema.Literal("chatkit.task_group").annotate({ + "description": "Type discriminator that is always `chatkit.task_group`." + }), + "tasks": Schema.Array(TaskGroupTask).annotate({ "description": "Tasks included in the group." }) +}).annotate({ "title": "Task group", "description": "Collection of workflow tasks grouped together in the thread." }) +export type ThreadResource = { + readonly "id": string + readonly "object": "chatkit.thread" + readonly "created_at": number + readonly "title": string | null + readonly "status": ActiveStatus | LockedStatus | ClosedStatus + readonly "user": string +} +export const ThreadResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier of the thread." }), + "object": Schema.Literal("chatkit.thread").annotate({ + "description": "Type discriminator that is always `chatkit.thread`." + }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) for when the thread was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "title": Schema.Union([ + Schema.String.annotate({ + "description": "Optional human-readable title for the thread. Defaults to null when no title has been generated." + }), + Schema.Null + ]), + "status": Schema.Union([ActiveStatus, LockedStatus, ClosedStatus], { mode: "oneOf" }).annotate({ + "description": "Current status for the thread. Defaults to `active` for newly created threads." + }), + "user": Schema.String.annotate({ + "description": "Free-form string that identifies your end user who owns the thread." + }) +}).annotate({ "title": "The thread object", "description": "Represents a ChatKit thread and its current status." }) +export type AuditLogActor = { + readonly "type"?: "session" | "api_key" + readonly "session"?: AuditLogActorSession + readonly "api_key"?: AuditLogActorApiKey +} +export const AuditLogActor = Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literals(["session", "api_key"]).annotate({ + "description": "The type of actor. Is either `session` or `api_key`." + }) + ), + "session": Schema.optionalKey(AuditLogActorSession), + "api_key": Schema.optionalKey(AuditLogActorApiKey) +}).annotate({ "description": "The actor who performed the audit logged action." }) +export type ChatCompletionToolChoiceOption = + | "none" + | "auto" + | "required" + | ChatCompletionAllowedToolsChoice + | ChatCompletionNamedToolChoice + | ChatCompletionNamedToolChoiceCustom +export const ChatCompletionToolChoiceOption = Schema.Union([ + Schema.Literals(["none", "auto", "required"]).annotate({ + "title": "Tool choice mode", + "description": + "`none` means the model will not call any tool and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools.\n" + }), + ChatCompletionAllowedToolsChoice, + ChatCompletionNamedToolChoice, + ChatCompletionNamedToolChoiceCustom +], { mode: "oneOf" }).annotate({ + "description": + "Controls which (if any) tool is called by the model.\n`none` means the model will not call any tool and instead generates a message.\n`auto` means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools.\nSpecifying a particular tool via `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n\n`none` is the default when no tools are present. `auto` is the default if tools are present.\n" +}) +export type ChatCompletionMessageList = { + readonly "object": "list" + readonly "data": ReadonlyArray< + { + readonly "content": string | null + readonly "refusal": string | null + readonly "tool_calls"?: ChatCompletionMessageToolCalls + readonly "annotations"?: ReadonlyArray< + { + readonly "type": "url_citation" + readonly "url_citation": { + readonly "end_index": number + readonly "start_index": number + readonly "url": string + readonly "title": string + } + } + > + readonly "role": "assistant" + readonly "function_call"?: { readonly "arguments": string; readonly "name": string } + readonly "audio"?: { + readonly "id": string + readonly "expires_at": number + readonly "data": string + readonly "transcript": string + } | null + readonly "id": string + readonly "content_parts"?: + | ReadonlyArray + | null + } + > + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const ChatCompletionMessageList = Schema.Struct({ + "object": Schema.Literal("list").annotate({ + "description": "The type of this object. It is always set to \"list\".\n" + }), + "data": Schema.Array( + Schema.Struct({ + "content": Schema.Union([Schema.String.annotate({ "description": "The contents of the message." }), Schema.Null]), + "refusal": Schema.Union([ + Schema.String.annotate({ "description": "The refusal message generated by the model." }), + Schema.Null + ]), + "tool_calls": Schema.optionalKey(ChatCompletionMessageToolCalls), + "annotations": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "type": Schema.Literal("url_citation").annotate({ + "description": "The type of the URL citation. Always `url_citation`." + }), + "url_citation": Schema.Struct({ + "end_index": Schema.Number.annotate({ + "description": "The index of the last character of the URL citation in the message." + }).check(Schema.isInt()), + "start_index": Schema.Number.annotate({ + "description": "The index of the first character of the URL citation in the message." + }).check(Schema.isInt()), + "url": Schema.String.annotate({ "description": "The URL of the web resource.", "format": "uri" }), + "title": Schema.String.annotate({ "description": "The title of the web resource." }) + }).annotate({ "description": "A URL citation when using web search." }) + }).annotate({ "description": "A URL citation when using web search.\n" }) + ).annotate({ + "description": + "Annotations for the message, when applicable, as when using the\n[web search tool](/docs/guides/tools-web-search?api-mode=chat).\n" + }) + ), + "role": Schema.Literal("assistant").annotate({ "description": "The role of the author of this message." }), + "function_call": Schema.optionalKey( + Schema.Struct({ + "arguments": Schema.String.annotate({ + "description": + "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + }), + "name": Schema.String.annotate({ "description": "The name of the function to call." }) + }).annotate({ + "description": + "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + }) + ), + "audio": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "id": Schema.String.annotate({ "description": "Unique identifier for this audio response." }), + "expires_at": Schema.Number.annotate({ + "description": + "The Unix timestamp (in seconds) for when this audio response will\nno longer be accessible on the server for use in multi-turn\nconversations.\n", + "format": "unixtime" + }).check(Schema.isInt()), + "data": Schema.String.annotate({ + "description": + "Base64 encoded audio bytes generated by the model, in the format\nspecified in the request.\n" + }), + "transcript": Schema.String.annotate({ "description": "Transcript of the audio generated by the model." }) + }).annotate({ + "description": + "If the audio output modality is requested, this object contains data\nabout the audio response from the model. [Learn more](/docs/guides/audio).\n" + }), + Schema.Null + ])), + "id": Schema.String.annotate({ "description": "The identifier of the chat message." }), + "content_parts": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([ChatCompletionRequestMessageContentPartText, ChatCompletionRequestMessageContentPartImage], { + mode: "oneOf" + }) + ).annotate({ + "description": + "If a content parts array was provided, this is an array of `text` and `image_url` parts.\nOtherwise, null.\n" + }), + Schema.Null + ]) + ) + }).annotate({ "description": "A chat completion message generated by the model." }) + ).annotate({ "description": "An array of chat completion message objects.\n" }), + "first_id": Schema.String.annotate({ "description": "The identifier of the first chat message in the data array." }), + "last_id": Schema.String.annotate({ "description": "The identifier of the last chat message in the data array." }), + "has_more": Schema.Boolean.annotate({ "description": "Indicates whether there are more chat messages available." }) +}).annotate({ + "title": "ChatCompletionMessageList", + "description": "An object representing a list of chat completion messages.\n" +}) +export type ChatCompletionResponseMessage = { + readonly "content": string | null + readonly "refusal": string | null + readonly "tool_calls"?: ChatCompletionMessageToolCalls + readonly "annotations"?: ReadonlyArray< + { + readonly "type": "url_citation" + readonly "url_citation": { + readonly "end_index": number + readonly "start_index": number + readonly "url": string + readonly "title": string + } + } + > + readonly "role": "assistant" + readonly "function_call"?: { readonly "arguments": string; readonly "name": string } + readonly "audio"?: { + readonly "id": string + readonly "expires_at": number + readonly "data": string + readonly "transcript": string + } | null +} +export const ChatCompletionResponseMessage = Schema.Struct({ + "content": Schema.Union([Schema.String.annotate({ "description": "The contents of the message." }), Schema.Null]), + "refusal": Schema.Union([ + Schema.String.annotate({ "description": "The refusal message generated by the model." }), + Schema.Null + ]), + "tool_calls": Schema.optionalKey(ChatCompletionMessageToolCalls), + "annotations": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "type": Schema.Literal("url_citation").annotate({ + "description": "The type of the URL citation. Always `url_citation`." + }), + "url_citation": Schema.Struct({ + "end_index": Schema.Number.annotate({ + "description": "The index of the last character of the URL citation in the message." + }).check(Schema.isInt()), + "start_index": Schema.Number.annotate({ + "description": "The index of the first character of the URL citation in the message." + }).check(Schema.isInt()), + "url": Schema.String.annotate({ "description": "The URL of the web resource.", "format": "uri" }), + "title": Schema.String.annotate({ "description": "The title of the web resource." }) + }).annotate({ "description": "A URL citation when using web search." }) + }).annotate({ "description": "A URL citation when using web search.\n" }) + ).annotate({ + "description": + "Annotations for the message, when applicable, as when using the\n[web search tool](/docs/guides/tools-web-search?api-mode=chat).\n" + }) + ), + "role": Schema.Literal("assistant").annotate({ "description": "The role of the author of this message." }), + "function_call": Schema.optionalKey( + Schema.Struct({ + "arguments": Schema.String.annotate({ + "description": + "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + }), + "name": Schema.String.annotate({ "description": "The name of the function to call." }) + }).annotate({ + "description": + "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + }) + ), + "audio": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "id": Schema.String.annotate({ "description": "Unique identifier for this audio response." }), + "expires_at": Schema.Number.annotate({ + "description": + "The Unix timestamp (in seconds) for when this audio response will\nno longer be accessible on the server for use in multi-turn\nconversations.\n", + "format": "unixtime" + }).check(Schema.isInt()), + "data": Schema.String.annotate({ + "description": "Base64 encoded audio bytes generated by the model, in the format\nspecified in the request.\n" + }), + "transcript": Schema.String.annotate({ "description": "Transcript of the audio generated by the model." }) + }).annotate({ + "description": + "If the audio output modality is requested, this object contains data\nabout the audio response from the model. [Learn more](/docs/guides/audio).\n" + }), + Schema.Null + ])) +}).annotate({ "description": "A chat completion message generated by the model." }) +export type CreateChatCompletionStreamResponse = { + readonly "id": string + readonly "choices": ReadonlyArray< + { + readonly "delta": ChatCompletionStreamResponseDelta + readonly "logprobs"?: { + readonly "content": ReadonlyArray< + { + readonly "token": string + readonly "logprob": number + readonly "bytes": ReadonlyArray | null + readonly "top_logprobs": ReadonlyArray< + { readonly "token": string; readonly "logprob": number; readonly "bytes": ReadonlyArray | null } + > + } + > + readonly "refusal": ReadonlyArray< + { + readonly "token": string + readonly "logprob": number + readonly "bytes": ReadonlyArray | null + readonly "top_logprobs": ReadonlyArray< + { readonly "token": string; readonly "logprob": number; readonly "bytes": ReadonlyArray | null } + > + } + > + } + readonly "finish_reason": "stop" | "length" | "tool_calls" | "content_filter" | "function_call" | null + readonly "index": number + } + > + readonly "created": number + readonly "model": string + readonly "service_tier"?: ServiceTier + readonly "system_fingerprint"?: string + readonly "object": "chat.completion.chunk" + readonly "usage"?: { + readonly "completion_tokens": number + readonly "prompt_tokens": number + readonly "total_tokens": number + readonly "completion_tokens_details"?: { + readonly "accepted_prediction_tokens"?: number + readonly "audio_tokens"?: number + readonly "reasoning_tokens"?: number + readonly "rejected_prediction_tokens"?: number + } + readonly "prompt_tokens_details"?: { readonly "audio_tokens"?: number; readonly "cached_tokens"?: number } + } | null +} +export const CreateChatCompletionStreamResponse = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "A unique identifier for the chat completion. Each chunk has the same ID." + }), + "choices": Schema.Array(Schema.Struct({ + "delta": ChatCompletionStreamResponseDelta, + "logprobs": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "content": Schema.Union([ + Schema.Array(Schema.Struct({ + "token": Schema.String.annotate({ "description": "The token." }), + "logprob": Schema.Number.annotate({ + "description": + "The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." + }).check(Schema.isFinite()), + "bytes": Schema.Union([ + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": + "A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." + }), + Schema.Null + ]), + "top_logprobs": Schema.Array(Schema.Struct({ + "token": Schema.String.annotate({ "description": "The token." }), + "logprob": Schema.Number.annotate({ + "description": + "The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." + }).check(Schema.isFinite()), + "bytes": Schema.Union([ + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": + "A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." + }), + Schema.Null + ]) + })).annotate({ + "description": + "List of the most likely tokens and their log probability, at this token position. The number of entries may be fewer than the requested `top_logprobs`." + }) + })).annotate({ "description": "A list of message content tokens with log probability information." }) + ]), + "refusal": Schema.Union([ + Schema.Array(Schema.Struct({ + "token": Schema.String.annotate({ "description": "The token." }), + "logprob": Schema.Number.annotate({ + "description": + "The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." + }).check(Schema.isFinite()), + "bytes": Schema.Union([ + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": + "A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." + }), + Schema.Null + ]), + "top_logprobs": Schema.Array(Schema.Struct({ + "token": Schema.String.annotate({ "description": "The token." }), + "logprob": Schema.Number.annotate({ + "description": + "The log probability of this token, if it is within the top 20 most likely tokens. Otherwise, the value `-9999.0` is used to signify that the token is very unlikely." + }).check(Schema.isFinite()), + "bytes": Schema.Union([ + Schema.Array(Schema.Number.check(Schema.isInt())).annotate({ + "description": + "A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and their byte representations must be combined to generate the correct text representation. Can be `null` if there is no bytes representation for the token." + }), + Schema.Null + ]) + })).annotate({ + "description": + "List of the most likely tokens and their log probability, at this token position. The number of entries may be fewer than the requested `top_logprobs`." + }) + })).annotate({ "description": "A list of message refusal tokens with log probability information." }) + ]) + }).annotate({ "description": "Log probability information for the choice." }) + ])), + "finish_reason": Schema.Union([ + Schema.Literals(["stop", "length", "tool_calls", "content_filter", "function_call"]).annotate({ + "description": + "The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n" + }), + Schema.Union([Schema.Null]).annotate({ + "description": + "The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n" + }) + ]), + "index": Schema.Number.annotate({ "description": "The index of the choice in the list of choices." }).check( + Schema.isInt() + ) + })).annotate({ + "description": + "A list of chat completion choices. Can contain more than one elements if `n` is greater than 1. Can also be empty for the\nlast chunk if you set `stream_options: {\"include_usage\": true}`.\n" + }), + "created": Schema.Number.annotate({ + "description": + "The Unix timestamp (in seconds) of when the chat completion was created. Each chunk has the same timestamp.", + "format": "unixtime" + }).check(Schema.isInt()), + "model": Schema.String.annotate({ "description": "The model to generate the completion." }), + "service_tier": Schema.optionalKey(ServiceTier), + "system_fingerprint": Schema.optionalKey( + Schema.String.annotate({ + "description": + "This fingerprint represents the backend configuration that the model runs with.\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" + }) + ), + "object": Schema.Literal("chat.completion.chunk").annotate({ + "description": "The object type, which is always `chat.completion.chunk`." + }), + "usage": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "completion_tokens": Schema.Number.annotate({ "description": "Number of tokens in the generated completion." }) + .check(Schema.isInt()), + "prompt_tokens": Schema.Number.annotate({ "description": "Number of tokens in the prompt." }).check( + Schema.isInt() + ), + "total_tokens": Schema.Number.annotate({ + "description": "Total number of tokens used in the request (prompt + completion)." + }).check(Schema.isInt()), + "completion_tokens_details": Schema.optionalKey( + Schema.Struct({ + "accepted_prediction_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "When using Predicted Outputs, the number of tokens in the\nprediction that appeared in the completion.\n" + }).check(Schema.isInt()) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Audio input tokens generated by the model." }).check( + Schema.isInt() + ) + ), + "reasoning_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Tokens generated by the model for reasoning." }).check( + Schema.isInt() + ) + ), + "rejected_prediction_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "When using Predicted Outputs, the number of tokens in the\nprediction that did not appear in the completion. However, like\nreasoning tokens, these tokens are still counted in the total\ncompletion tokens for purposes of billing, output, and context window\nlimits.\n" + }).check(Schema.isInt()) + ) + }).annotate({ "description": "Breakdown of tokens used in a completion." }) + ), + "prompt_tokens_details": Schema.optionalKey( + Schema.Struct({ + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Audio input tokens present in the prompt." }).check(Schema.isInt()) + ), + "cached_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "Cached tokens present in the prompt." }).check(Schema.isInt()) + ) + }).annotate({ "description": "Breakdown of tokens used in the prompt." }) + ) + }).annotate({ + "description": + "An optional field that will only be present when you set\n`stream_options: {\"include_usage\": true}` in your request. When present, it\ncontains a null value **except for the last chunk** which contains the\ntoken usage statistics for the entire request.\n\n**NOTE:** If the stream is interrupted or cancelled, you may not\nreceive the final usage chunk which contains the total token usage for\nthe request.\n" + }), + Schema.Null + ])) +}).annotate({ + "description": + "Represents a streamed chunk of a chat completion response returned\nby the model, based on the provided input. \n[Learn more](/docs/guides/streaming-responses).\n" +}) +export type ChatCompletionRequestAssistantMessage = { + readonly "content"?: string | ReadonlyArray | null + readonly "refusal"?: string | null + readonly "role": "assistant" + readonly "name"?: string + readonly "audio"?: { readonly "id": string } | null + readonly "tool_calls"?: ChatCompletionMessageToolCalls + readonly "function_call"?: { readonly "arguments": string; readonly "name": string } | null +} +export const ChatCompletionRequestAssistantMessage = Schema.Struct({ + "content": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.String.annotate({ "title": "Text content", "description": "The contents of the assistant message." }), + Schema.Array(ChatCompletionRequestAssistantMessageContentPart).annotate({ + "title": "Array of content parts", + "description": + "An array of content parts with a defined type. Can be one or more of type `text`, or exactly one of type `refusal`." + }).check(Schema.isMinLength(1)) + ], { mode: "oneOf" }).annotate({ + "description": + "The contents of the assistant message. Required unless `tool_calls` or `function_call` is specified.\n" + }), + Schema.Null + ]) + ), + "refusal": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "The refusal message by the assistant." }), Schema.Null]) + ), + "role": Schema.Literal("assistant").annotate({ + "description": "The role of the messages author, in this case `assistant`." + }), + "name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "An optional name for the participant. Provides the model information to differentiate between participants of the same role." + }) + ), + "audio": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "id": Schema.String.annotate({ + "description": "Unique identifier for a previous audio response from the model.\n" + }) + }).annotate({ + "description": "Data about a previous audio response from the model.\n[Learn more](/docs/guides/audio).\n" + }), + Schema.Null + ]) + ), + "tool_calls": Schema.optionalKey(ChatCompletionMessageToolCalls), + "function_call": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "arguments": Schema.String.annotate({ + "description": + "The arguments to call the function with, as generated by the model in JSON format. Note that the model does not always generate valid JSON, and may hallucinate parameters not defined by your function schema. Validate the arguments in your code before calling your function." + }), + "name": Schema.String.annotate({ "description": "The name of the function to call." }) + }).annotate({ + "description": + "Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be called, as generated by the model." + }), + Schema.Null + ])) +}).annotate({ + "title": "Assistant message", + "description": "Messages sent by the model in response to user messages.\n" +}) +export type ChatCompletionRequestSystemMessage = { + readonly "content": string | ReadonlyArray + readonly "role": "system" + readonly "name"?: string +} +export const ChatCompletionRequestSystemMessage = Schema.Struct({ + "content": Schema.Union([ + Schema.String.annotate({ "title": "Text content", "description": "The contents of the system message." }), + Schema.Array(ChatCompletionRequestSystemMessageContentPart).annotate({ + "title": "Array of content parts", + "description": + "An array of content parts with a defined type. For system messages, only type `text` is supported." + }).check(Schema.isMinLength(1)) + ], { mode: "oneOf" }).annotate({ "description": "The contents of the system message." }), + "role": Schema.Literal("system").annotate({ + "description": "The role of the messages author, in this case `system`." + }), + "name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "An optional name for the participant. Provides the model information to differentiate between participants of the same role." + }) + ) +}).annotate({ + "title": "System message", + "description": + "Developer-provided instructions that the model should follow, regardless of\nmessages sent by the user. With o1 models and newer, use `developer` messages\nfor this purpose instead.\n" +}) +export type ChatCompletionRequestToolMessage = { + readonly "role": "tool" + readonly "content": string | ReadonlyArray + readonly "tool_call_id": string +} +export const ChatCompletionRequestToolMessage = Schema.Struct({ + "role": Schema.Literal("tool").annotate({ "description": "The role of the messages author, in this case `tool`." }), + "content": Schema.Union([ + Schema.String.annotate({ "title": "Text content", "description": "The contents of the tool message." }), + Schema.Array(ChatCompletionRequestToolMessageContentPart).annotate({ + "title": "Array of content parts", + "description": "An array of content parts with a defined type. For tool messages, only type `text` is supported." + }).check(Schema.isMinLength(1)) + ], { mode: "oneOf" }).annotate({ "description": "The contents of the tool message." }), + "tool_call_id": Schema.String.annotate({ "description": "Tool call that this message is responding to." }) +}).annotate({ "title": "Tool message" }) +export type ChatCompletionRequestUserMessage = { + readonly "content": string | ReadonlyArray + readonly "role": "user" + readonly "name"?: string +} +export const ChatCompletionRequestUserMessage = Schema.Struct({ + "content": Schema.Union([ + Schema.String.annotate({ "title": "Text content", "description": "The text contents of the message." }), + Schema.Array(ChatCompletionRequestUserMessageContentPart).annotate({ + "title": "Array of content parts", + "description": + "An array of content parts with a defined type. Supported options differ based on the [model](/docs/models) being used to generate the response. Can contain text, image, or audio inputs." + }).check(Schema.isMinLength(1)) + ], { mode: "oneOf" }).annotate({ "description": "The contents of the user message.\n" }), + "role": Schema.Literal("user").annotate({ "description": "The role of the messages author, in this case `user`." }), + "name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "An optional name for the participant. Provides the model information to differentiate between participants of the same role." + }) + ) +}).annotate({ + "title": "User message", + "description": "Messages sent by an end user, containing prompts or additional context\ninformation.\n" +}) +export type VectorStoreSearchRequest = { + readonly "query": string | ReadonlyArray + readonly "rewrite_query"?: boolean + readonly "max_num_results"?: number + readonly "filters"?: ComparisonFilter | CompoundFilter + readonly "ranking_options"?: { + readonly "ranker"?: "none" | "auto" | "default-2024-11-15" + readonly "score_threshold"?: number + } +} +export const VectorStoreSearchRequest = Schema.Struct({ + "query": Schema.Union([ + Schema.String, + Schema.Array(Schema.String.annotate({ "description": "A list of queries to search for." })) + ], { mode: "oneOf" }).annotate({ "description": "A query string for a search" }), + "rewrite_query": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether to rewrite the natural language query for vector search." }) + ), + "max_num_results": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The maximum number of results to return. This number should be between 1 and 50 inclusive." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(50)) + ), + "filters": Schema.optionalKey( + Schema.Union([ComparisonFilter, CompoundFilter], { mode: "oneOf" }).annotate({ + "description": "A filter to apply based on file attributes." + }) + ), + "ranking_options": Schema.optionalKey( + Schema.Struct({ + "ranker": Schema.optionalKey( + Schema.Literals(["none", "auto", "default-2024-11-15"]).annotate({ + "description": "Enable re-ranking; set to `none` to disable, which can help reduce latency." + }) + ), + "score_threshold": Schema.optionalKey( + Schema.Number.check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check( + Schema.isLessThanOrEqualTo(1) + ) + ) + }).annotate({ "description": "Ranking options for search." }) + ) +}) +export type FileSearchTool = { + readonly "type": "file_search" + readonly "vector_store_ids": ReadonlyArray + readonly "max_num_results"?: number + readonly "ranking_options"?: { + readonly "ranker"?: "auto" | "default-2024-11-15" + readonly "score_threshold"?: number + readonly "hybrid_search"?: { readonly "embedding_weight": number; readonly "text_weight": number } + } + readonly "filters"?: ComparisonFilter | CompoundFilter | null +} +export const FileSearchTool = Schema.Struct({ + "type": Schema.Literal("file_search").annotate({ + "description": "The type of the file search tool. Always `file_search`." + }), + "vector_store_ids": Schema.Array(Schema.String).annotate({ + "description": "The IDs of the vector stores to search." + }), + "max_num_results": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The maximum number of results to return. This number should be between 1 and 50 inclusive." + }).check(Schema.isInt()) + ), + "ranking_options": Schema.optionalKey( + Schema.Struct({ + "ranker": Schema.optionalKey( + Schema.Literals(["auto", "default-2024-11-15"]).annotate({ + "description": "The ranker to use for the file search." + }) + ), + "score_threshold": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results." + }).check(Schema.isFinite()) + ), + "hybrid_search": Schema.optionalKey( + Schema.Struct({ + "embedding_weight": Schema.Number.annotate({ + "description": "The weight of the embedding in the reciprocal ranking fusion." + }).check(Schema.isFinite()), + "text_weight": Schema.Number.annotate({ + "description": "The weight of the text in the reciprocal ranking fusion." + }).check(Schema.isFinite()) + }).annotate({ + "description": + "Weights that control how reciprocal rank fusion balances semantic embedding matches versus sparse keyword matches when hybrid search is enabled." + }) + ) + }).annotate({ "description": "Ranking options for search." }) + ), + "filters": Schema.optionalKey( + Schema.Union([ + Schema.Union([ComparisonFilter, CompoundFilter]).annotate({ "description": "A filter to apply." }), + Schema.Null + ]) + ) +}).annotate({ + "title": "File search", + "description": + "A tool that searches for relevant content from uploaded files. Learn more about the [file search tool](https://platform.openai.com/docs/guides/tools-file-search)." +}) +export type EvalRunOutputItemList = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const EvalRunOutputItemList = Schema.Struct({ + "object": Schema.Literal("list").annotate({ + "description": "The type of this object. It is always set to \"list\".\n" + }), + "data": Schema.Array(EvalRunOutputItem).annotate({ "description": "An array of eval run output item objects.\n" }), + "first_id": Schema.String.annotate({ + "description": "The identifier of the first eval run output item in the data array." + }), + "last_id": Schema.String.annotate({ + "description": "The identifier of the last eval run output item in the data array." + }), + "has_more": Schema.Boolean.annotate({ + "description": "Indicates whether there are more eval run output items available." + }) +}).annotate({ + "title": "EvalRunOutputItemList", + "description": "An object representing a list of output items for an evaluation run.\n" +}) +export type AssistantToolsFileSearch = { + readonly "type": "file_search" + readonly "file_search"?: { + readonly "max_num_results"?: number + readonly "ranking_options"?: FileSearchRankingOptions + } +} +export const AssistantToolsFileSearch = Schema.Struct({ + "type": Schema.Literal("file_search").annotate({ "description": "The type of tool being defined: `file_search`" }), + "file_search": Schema.optionalKey( + Schema.Struct({ + "max_num_results": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The maximum number of results the file search tool should output. The default is 20 for `gpt-4*` models and 5 for `gpt-3.5-turbo`. This number should be between 1 and 50 inclusive.\n\nNote that the file search tool may output fewer than `max_num_results` results. See the [file search tool documentation](/docs/assistants/tools/file-search#customizing-file-search-settings) for more information.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check(Schema.isLessThanOrEqualTo(50)) + ), + "ranking_options": Schema.optionalKey(FileSearchRankingOptions) + }).annotate({ "description": "Overrides for the file search tool." }) + ) +}).annotate({ "title": "FileSearch tool" }) +export type RunStepDetailsToolCallsFileSearchObject = { + readonly "id": string + readonly "type": "file_search" + readonly "file_search": { + readonly "ranking_options"?: RunStepDetailsToolCallsFileSearchRankingOptionsObject + readonly "results"?: ReadonlyArray + } +} +export const RunStepDetailsToolCallsFileSearchObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The ID of the tool call object." }), + "type": Schema.Literal("file_search").annotate({ + "description": "The type of tool call. This is always going to be `file_search` for this type of tool call." + }), + "file_search": Schema.Struct({ + "ranking_options": Schema.optionalKey(RunStepDetailsToolCallsFileSearchRankingOptionsObject), + "results": Schema.optionalKey( + Schema.Array(RunStepDetailsToolCallsFileSearchResultObject).annotate({ + "description": "The results of the file search." + }) + ) + }).annotate({ "description": "For now, this is always going to be an empty object." }) +}).annotate({ "title": "File search tool call" }) +export type AssistantToolsFunction = { readonly "type": "function"; readonly "function": FunctionObject } +export const AssistantToolsFunction = Schema.Struct({ + "type": Schema.Literal("function").annotate({ "description": "The type of tool being defined: `function`" }), + "function": FunctionObject +}).annotate({ "title": "Function tool" }) +export type ChatCompletionTool = { readonly "type": "function"; readonly "function": FunctionObject } +export const ChatCompletionTool = Schema.Struct({ + "type": Schema.Literal("function").annotate({ + "description": "The type of the tool. Currently, only `function` is supported." + }), + "function": FunctionObject +}).annotate({ "title": "Function tool", "description": "A function tool that can be used to generate a response.\n" }) +export type ImageEditStreamEvent = ImageEditPartialImageEvent | ImageEditCompletedEvent +export const ImageEditStreamEvent = Schema.Union([ImageEditPartialImageEvent, ImageEditCompletedEvent]) +export type ImageGenStreamEvent = ImageGenPartialImageEvent | ImageGenCompletedEvent +export const ImageGenStreamEvent = Schema.Union([ImageGenPartialImageEvent, ImageGenCompletedEvent]) +export type MessageObject = { + readonly "id": string + readonly "object": "thread.message" + readonly "created_at": number + readonly "thread_id": string + readonly "status": "in_progress" | "incomplete" | "completed" + readonly "incomplete_details": { + readonly "reason": "content_filter" | "max_tokens" | "run_cancelled" | "run_expired" | "run_failed" + } | null + readonly "completed_at": number | null + readonly "incomplete_at": number | null + readonly "role": "user" | "assistant" + readonly "content": ReadonlyArray< + | MessageContentImageFileObject + | MessageContentImageUrlObject + | MessageContentTextObject + | MessageContentRefusalObject + > + readonly "assistant_id": string | null + readonly "run_id": string | null + readonly "attachments": + | ReadonlyArray< + { + readonly "file_id"?: string + readonly "tools"?: ReadonlyArray + } + > + | null + readonly "metadata": Metadata +} +export const MessageObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints." }), + "object": Schema.Literal("thread.message").annotate({ + "description": "The object type, which is always `thread.message`." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the message was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "thread_id": Schema.String.annotate({ + "description": "The [thread](/docs/api-reference/threads) ID that this message belongs to." + }), + "status": Schema.Literals(["in_progress", "incomplete", "completed"]).annotate({ + "description": "The status of the message, which can be either `in_progress`, `incomplete`, or `completed`." + }), + "incomplete_details": Schema.Union([ + Schema.Struct({ + "reason": Schema.Literals(["content_filter", "max_tokens", "run_cancelled", "run_expired", "run_failed"]) + .annotate({ "description": "The reason the message is incomplete." }) + }).annotate({ "description": "On an incomplete message, details about why the message is incomplete." }), + Schema.Null + ]), + "completed_at": Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the message was completed.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "incomplete_at": Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the message was marked as incomplete.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "role": Schema.Literals(["user", "assistant"]).annotate({ + "description": "The entity that produced the message. One of `user` or `assistant`." + }), + "content": Schema.Array( + Schema.Union([ + MessageContentImageFileObject, + MessageContentImageUrlObject, + MessageContentTextObject, + MessageContentRefusalObject + ], { mode: "oneOf" }) + ).annotate({ "description": "The content of the message in array of text and/or images." }), + "assistant_id": Schema.Union([ + Schema.String.annotate({ + "description": + "If applicable, the ID of the [assistant](/docs/api-reference/assistants) that authored this message." + }), + Schema.Null + ]), + "run_id": Schema.Union([ + Schema.String.annotate({ + "description": + "The ID of the [run](/docs/api-reference/runs) associated with the creation of this message. Value is `null` when messages are created manually using the create message or create thread endpoints." + }), + Schema.Null + ]), + "attachments": Schema.Union([ + Schema.Array(Schema.Struct({ + "file_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the file to attach to the message." }) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Union([AssistantToolsCode, AssistantToolsFileSearchTypeOnly], { mode: "oneOf" })).annotate({ + "description": "The tools to add this file to." + }) + ) + })).annotate({ "description": "A list of files attached to the message, and the tools they were added to." }), + Schema.Null + ]), + "metadata": Metadata +}).annotate({ + "title": "The message object", + "description": "Represents a message within a [thread](/docs/api-reference/threads)." +}) +export type MessageDeltaObject = { + readonly "id": string + readonly "object": "thread.message.delta" + readonly "delta": { + readonly "role"?: "user" | "assistant" + readonly "content"?: ReadonlyArray< + | MessageDeltaContentImageFileObject + | MessageDeltaContentTextObject + | MessageDeltaContentRefusalObject + | MessageDeltaContentImageUrlObject + > + } +} +export const MessageDeltaObject = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The identifier of the message, which can be referenced in API endpoints." + }), + "object": Schema.Literal("thread.message.delta").annotate({ + "description": "The object type, which is always `thread.message.delta`." + }), + "delta": Schema.Struct({ + "role": Schema.optionalKey( + Schema.Literals(["user", "assistant"]).annotate({ + "description": "The entity that produced the message. One of `user` or `assistant`." + }) + ), + "content": Schema.optionalKey( + Schema.Array( + Schema.Union([ + MessageDeltaContentImageFileObject, + MessageDeltaContentTextObject, + MessageDeltaContentRefusalObject, + MessageDeltaContentImageUrlObject + ], { mode: "oneOf" }) + ).annotate({ "description": "The content of the message in array of text and/or images." }) + ) + }).annotate({ "description": "The delta containing the fields that have changed on the Message." }) +}).annotate({ + "title": "Message delta object", + "description": "Represents a message delta i.e. any changed fields on a message during streaming.\n" +}) +export type ListBatchesResponse = { + readonly "data": ReadonlyArray + readonly "first_id"?: string + readonly "last_id"?: string + readonly "has_more": boolean + readonly "object": "list" +} +export const ListBatchesResponse = Schema.Struct({ + "data": Schema.Array(Batch), + "first_id": Schema.optionalKey(Schema.String), + "last_id": Schema.optionalKey(Schema.String), + "has_more": Schema.Boolean, + "object": Schema.Literal("list") +}) +export type CreateThreadRequest = { + readonly "messages"?: ReadonlyArray + readonly "tool_resources"?: { + readonly "code_interpreter"?: { readonly "file_ids"?: ReadonlyArray } + readonly "file_search"?: { + readonly "vector_store_ids": ReadonlyArray + readonly "vector_stores"?: ReadonlyArray< + { + readonly "file_ids"?: ReadonlyArray + readonly "chunking_strategy"?: { readonly "type": "auto" } | { + readonly "type": "static" + readonly "static": { readonly "max_chunk_size_tokens": number; readonly "chunk_overlap_tokens": number } + } + readonly "metadata"?: Metadata + } + > + } | { + readonly "vector_stores": ReadonlyArray< + { + readonly "file_ids"?: ReadonlyArray + readonly "chunking_strategy"?: { readonly "type": "auto" } | { + readonly "type": "static" + readonly "static": { readonly "max_chunk_size_tokens": number; readonly "chunk_overlap_tokens": number } + } + readonly "metadata"?: Metadata + } + > + readonly "vector_store_ids"?: ReadonlyArray + } + } | null + readonly "metadata"?: Metadata +} +export const CreateThreadRequest = Schema.Struct({ + "messages": Schema.optionalKey( + Schema.Array(CreateMessageRequest).annotate({ + "description": "A list of [messages](/docs/api-reference/messages) to start the thread with." + }) + ), + "tool_resources": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "code_interpreter": Schema.optionalKey(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n" + }).check(Schema.isMaxLength(20)) + ) + })), + "file_search": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "vector_store_ids": Schema.Array(Schema.String).annotate({ + "description": + "The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n" + }).check(Schema.isMaxLength(1)), + "vector_stores": Schema.optionalKey( + Schema.Array(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs to add to the vector store. For vector stores created before Nov 2025, there can be a maximum of 10,000 files in a vector store. For vector stores created starting in Nov 2025, the limit is 100,000,000 files.\n" + }).check(Schema.isMaxLength(100000000)) + ), + "chunking_strategy": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": Schema.Literal("auto").annotate({ "description": "Always `auto`." }) }) + .annotate({ + "title": "Auto Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }), + Schema.Struct({ + "type": Schema.Literal("static").annotate({ "description": "Always `static`." }), + "static": Schema.Struct({ + "max_chunk_size_tokens": Schema.Number.annotate({ + "description": + "The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(100)).check( + Schema.isLessThanOrEqualTo(4096) + ), + "chunk_overlap_tokens": Schema.Number.annotate({ + "description": + "The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" + }).check(Schema.isInt()) + }) + }).annotate({ + "title": "Static Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }) + ], { mode: "oneOf" }) + ), + "metadata": Schema.optionalKey(Metadata) + })).annotate({ + "description": + "A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n" + }).check(Schema.isMaxLength(1)) + ) + }), + Schema.Struct({ + "vector_stores": Schema.Array(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs to add to the vector store. For vector stores created before Nov 2025, there can be a maximum of 10,000 files in a vector store. For vector stores created starting in Nov 2025, the limit is 100,000,000 files.\n" + }).check(Schema.isMaxLength(100000000)) + ), + "chunking_strategy": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": Schema.Literal("auto").annotate({ "description": "Always `auto`." }) }) + .annotate({ + "title": "Auto Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }), + Schema.Struct({ + "type": Schema.Literal("static").annotate({ "description": "Always `static`." }), + "static": Schema.Struct({ + "max_chunk_size_tokens": Schema.Number.annotate({ + "description": + "The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(100)).check( + Schema.isLessThanOrEqualTo(4096) + ), + "chunk_overlap_tokens": Schema.Number.annotate({ + "description": + "The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" + }).check(Schema.isInt()) + }) + }).annotate({ + "title": "Static Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }) + ], { mode: "oneOf" }) + ), + "metadata": Schema.optionalKey(Metadata) + })).annotate({ + "description": + "A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this thread. There can be a maximum of 1 vector store attached to the thread.\n" + }).check(Schema.isMaxLength(1)), + "vector_store_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "The [vector store](/docs/api-reference/vector-stores/object) attached to this thread. There can be a maximum of 1 vector store attached to the thread.\n" + }).check(Schema.isMaxLength(1)) + ) + }) + ], { mode: "oneOf" })) + }).annotate({ + "description": + "A set of resources that are made available to the assistant's tools in this thread. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + }), + Schema.Null + ])), + "metadata": Schema.optionalKey(Metadata) +}).annotate({ + "description": + "Options to create a new thread. If no thread is provided when running a\nrequest, an empty thread will be created.\n" +}) +export type ThreadStreamEvent = { + readonly "enabled"?: boolean + readonly "event": "thread.created" + readonly "data": ThreadObject +} +export const ThreadStreamEvent = Schema.Union([ + Schema.Struct({ + "enabled": Schema.optionalKey( + Schema.Boolean.annotate({ "description": "Whether to enable input audio transcription." }) + ), + "event": Schema.Literal("thread.created"), + "data": ThreadObject + }).annotate({ "description": "Occurs when a new [thread](/docs/api-reference/threads/object) is created." }) +], { mode: "oneOf" }) +export type ModelIdsCompaction = ModelIdsResponses | string | null +export const ModelIdsCompaction = Schema.Union([ModelIdsResponses, Schema.String, Schema.Null]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-5` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](/docs/models) to browse and compare available models." +}) +export type RealtimeTranslationClientSecretCreateResponse = { + readonly "value": string + readonly "expires_at": number + readonly "session": RealtimeTranslationSession +} +export const RealtimeTranslationClientSecretCreateResponse = Schema.Struct({ + "value": Schema.String.annotate({ "description": "The generated client secret value." }), + "expires_at": Schema.Number.annotate({ + "description": "Expiration timestamp for the client secret, in seconds since epoch.", + "format": "unixtime" + }).check(Schema.isInt()), + "session": RealtimeTranslationSession +}).annotate({ + "title": "Realtime translation session and client secret", + "description": "Response from creating a translation session and client secret for the Realtime API.\n" +}) +export type RealtimeTranslationClientSecretCreateRequest = { + readonly "expires_after"?: { readonly "anchor"?: "created_at"; readonly "seconds"?: number } + readonly "session": RealtimeTranslationSessionCreateRequest +} +export const RealtimeTranslationClientSecretCreateRequest = Schema.Struct({ + "expires_after": Schema.optionalKey( + Schema.Struct({ + "anchor": Schema.optionalKey( + Schema.Literal("created_at").annotate({ + "description": + "The anchor point for the client secret expiration, meaning that `seconds` will be added to the `created_at` time of the client secret to produce an expiration timestamp. Only `created_at` is currently supported.\n" + }) + ), + "seconds": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200` (2 hours). This default to 600 seconds (10 minutes) if not specified.\n", + "format": "int64" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(10)).check(Schema.isLessThanOrEqualTo(7200)) + ) + }).annotate({ + "title": "Client secret expiration", + "description": + "Configuration for the client secret expiration. Expiration refers to the time after which\na client secret will no longer be valid for creating sessions. The session itself may\ncontinue after that time once started. A secret can be used to create multiple sessions\nuntil it expires.\n" + }) + ), + "session": RealtimeTranslationSessionCreateRequest +}).annotate({ + "title": "Realtime translation client secret creation request", + "description": "Create a translation session and client secret for the Realtime API.\n" +}) +export type ProjectApiKeyListResponse = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const ProjectApiKeyListResponse = Schema.Struct({ + "object": Schema.Literal("list"), + "data": Schema.Array(ProjectApiKey), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type RealtimeConversationItem = + | RealtimeConversationItemMessageSystem + | RealtimeConversationItemMessageUser + | RealtimeConversationItemMessageAssistant + | RealtimeConversationItemFunctionCall + | RealtimeConversationItemFunctionCallOutput + | RealtimeMCPApprovalResponse + | RealtimeMCPListTools + | RealtimeMCPToolCall + | RealtimeMCPApprovalRequest +export const RealtimeConversationItem = Schema.Union([ + RealtimeConversationItemMessageSystem, + RealtimeConversationItemMessageUser, + RealtimeConversationItemMessageAssistant, + RealtimeConversationItemFunctionCall, + RealtimeConversationItemFunctionCallOutput, + RealtimeMCPApprovalResponse, + RealtimeMCPListTools, + RealtimeMCPToolCall, + RealtimeMCPApprovalRequest +]).annotate({ "description": "A single item within a Realtime conversation." }) +export type AssistantsApiResponseFormatOption = + | "auto" + | ResponseFormatText + | ResponseFormatJsonObject + | ResponseFormatJsonSchema +export const AssistantsApiResponseFormatOption = Schema.Union([ + Schema.Literal("auto").annotate({ "description": "`auto` is the default value\n" }), + ResponseFormatText, + ResponseFormatJsonObject, + ResponseFormatJsonSchema +], { mode: "oneOf" }).annotate({ + "description": + "Specifies the format that the model must output. Compatible with [GPT-4o](/docs/models#gpt-4o), [GPT-4 Turbo](/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models since `gpt-3.5-turbo-1106`.\n\nSetting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables Structured Outputs which ensures the model will match your supplied JSON schema. Learn more in the [Structured Outputs guide](/docs/guides/structured-outputs).\n\nSetting to `{ \"type\": \"json_object\" }` enables JSON mode, which ensures the message the model generates is valid JSON.\n\n**Important:** when using JSON mode, you **must** also instruct the model to produce JSON yourself via a system or user message. Without this, the model may generate an unending stream of whitespace until the generation reaches the token limit, resulting in a long-running and seemingly \"stuck\" request. Also note that the message content may be partially cut off if `finish_reason=\"length\"`, which indicates the generation exceeded `max_tokens` or the conversation exceeded the max context length.\n" +}) +export type TextResponseFormatConfiguration = + | ResponseFormatText + | TextResponseFormatJsonSchema + | ResponseFormatJsonObject +export const TextResponseFormatConfiguration = Schema.Union([ + ResponseFormatText, + TextResponseFormatJsonSchema, + ResponseFormatJsonObject +], { mode: "oneOf" }).annotate({ + "description": + "An object specifying the format that the model must output.\n\nConfiguring `{ \"type\": \"json_schema\" }` enables Structured Outputs, \nwhich ensures the model will match your supplied JSON schema. Learn more in the \n[Structured Outputs guide](/docs/guides/structured-outputs).\n\nThe default format is `{ \"type\": \"text\" }` with no additional options.\n\n**Not recommended for gpt-4o and newer models:**\n\nSetting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n" +}) +export type RealtimeCallCreateRequest = { + readonly "sdp": string + readonly "session"?: { + readonly "type": "realtime" + readonly "output_modalities"?: ReadonlyArray<"text" | "audio"> + readonly "model"?: + | string + | "gpt-realtime" + | "gpt-realtime-1.5" + | "gpt-realtime-2" + | "gpt-realtime-2025-08-28" + | "gpt-4o-realtime-preview" + | "gpt-4o-realtime-preview-2024-10-01" + | "gpt-4o-realtime-preview-2024-12-17" + | "gpt-4o-realtime-preview-2025-06-03" + | "gpt-4o-mini-realtime-preview" + | "gpt-4o-mini-realtime-preview-2024-12-17" + | "gpt-realtime-mini" + | "gpt-realtime-mini-2025-10-06" + | "gpt-realtime-mini-2025-12-15" + | "gpt-audio-1.5" + | "gpt-audio-mini" + | "gpt-audio-mini-2025-10-06" + | "gpt-audio-mini-2025-12-15" + readonly "instructions"?: string + readonly "audio"?: { + readonly "input"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + readonly "delay"?: "minimal" | "low" | "medium" | "high" | "xhigh" + } + readonly "noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "turn_detection"?: RealtimeTurnDetection + } + readonly "output"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "voice"?: VoiceIdsShared | { readonly "id": string } + readonly "speed"?: number + } + } + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> + readonly "tracing"?: "auto" | { + readonly "workflow_name"?: string + readonly "group_id"?: string + readonly "metadata"?: {} + } | null + readonly "tools"?: ReadonlyArray + readonly "tool_choice"?: ToolChoiceOptions | ToolChoiceFunction | ToolChoiceMCP + readonly "parallel_tool_calls"?: boolean + readonly "reasoning"?: RealtimeReasoning + readonly "max_output_tokens"?: number | "inf" + readonly "truncation"?: RealtimeTruncation + readonly "prompt"?: Prompt + } +} +export const RealtimeCallCreateRequest = Schema.Struct({ + "sdp": Schema.String.annotate({ + "description": "WebRTC Session Description Protocol (SDP) offer generated by the caller." + }), + "session": Schema.optionalKey( + Schema.Struct({ + "type": Schema.Literal("realtime").annotate({ + "description": "The type of session to create. Always `realtime` for the Realtime API.\n" + }), + "output_modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": + "The set of modalities the model can respond with. It defaults to `[\"audio\"]`, indicating\nthat the model will respond with audio plus a transcript. `[\"text\"]` can be used to make\nthe model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n" + }) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "gpt-realtime", + "gpt-realtime-1.5", + "gpt-realtime-2", + "gpt-realtime-2025-08-28", + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-realtime-preview-2025-06-03", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + "gpt-realtime-mini", + "gpt-realtime-mini-2025-10-06", + "gpt-realtime-mini-2025-12-15", + "gpt-audio-1.5", + "gpt-audio-mini", + "gpt-audio-mini-2025-10-06", + "gpt-audio-mini-2025-12-15" + ]) + ]).annotate({ "description": "The Realtime model used for this session.\n" }) + ), + "instructions": Schema.optionalKey(Schema.String.annotate({ + "description": + "The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\n\nNote that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n" + })), + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the input audio." }) + ), + "transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n" + }) + ), + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }) + ), + "prompt": Schema.optionalKey(Schema.String.annotate({ + "description": + "An optional text to guide the model's style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text string, for example \"expect words related to technology\".\nPrompt is not supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + })), + "delay": Schema.optionalKey( + Schema.Literals(["minimal", "low", "medium", "high", "xhigh"]).annotate({ + "description": + "Controls how long the model waits before emitting transcription text.\nHigher values can improve transcription accuracy at the cost of latency.\nOnly supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + }) + ) + }).annotate({ + "description": + "Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n" + }) + ), + "noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": + "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n" + }) + ), + "turn_detection": Schema.optionalKey(RealtimeTurnDetection) + })), + "output": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the output audio." }) + ), + "voice": Schema.optionalKey( + Schema.Union([ + VoiceIdsShared, + Schema.Struct({ + "id": Schema.String.annotate({ "description": "The custom voice ID, e.g. `voice_1234`." }) + }).annotate({ "description": "Custom voice reference." }) + ]).annotate({ + "title": "Voice", + "description": + "The voice the model uses to respond. Supported built-in voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, `verse`,\n`marin`, and `cedar`. You may also provide a custom voice object with\nan `id`, for example `{ \"id\": \"voice_1234\" }`. Voice cannot be changed\nduring the session once the model has responded with audio at least once.\nWe recommend `marin` and `cedar` for best quality.\n" + }) + ), + "speed": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The speed of the model's spoken response as a multiple of the original speed.\n1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed. This value can only be changed in between model turns, not while a response is in progress.\n\nThis parameter is a post-processing adjustment to the audio after it is generated, it's\nalso possible to prompt the model to speak faster or slower.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0.25)).check( + Schema.isLessThanOrEqualTo(1.5) + ) + ) + })) + }).annotate({ "description": "Configuration for input and output audio.\n" }) + ), + "include": Schema.optionalKey( + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }) + ), + "tracing": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Literal("auto").annotate({ + "title": "auto", + "description": + "Enables tracing and sets default values for tracing configuration options. Always `auto`.\n" + }), + Schema.Struct({ + "workflow_name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The name of the workflow to attach to this trace. This is used to\nname the trace in the Traces Dashboard.\n" + }) + ), + "group_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The group id to attach to this trace to enable filtering and\ngrouping in the Traces Dashboard.\n" + }) + ), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": + "The arbitrary metadata to attach to this trace to enable\nfiltering in the Traces Dashboard.\n" + }) + ) + }).annotate({ "title": "Tracing Configuration", "description": "Granular configuration for tracing.\n" }) + ], { mode: "oneOf" }).annotate({ + "title": "Tracing Configuration", + "description": + "Realtime API can write session traces to the [Traces Dashboard](https://platform.openai.com/logs?api=traces). Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n" + }), + Schema.Null + ]) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Union([RealtimeFunctionTool, MCPTool], { mode: "oneOf" })).annotate({ + "description": "Tools available to the model." + }) + ), + "tool_choice": Schema.optionalKey( + Schema.Union([ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], { mode: "oneOf" }).annotate({ + "description": + "How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n" + }) + ), + "parallel_tool_calls": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": + "Whether the model may call multiple tools in parallel. Only supported by\nreasoning Realtime models such as `gpt-realtime-2`.\n" + }) + ), + "reasoning": Schema.optionalKey(RealtimeReasoning), + "max_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n" + }) + ), + "truncation": Schema.optionalKey(RealtimeTruncation), + "prompt": Schema.optionalKey(Prompt) + }).annotate({ "title": "Realtime session configuration", "description": "Realtime session object configuration." }) + ) +}).annotate({ + "title": "Realtime call creation request", + "description": + "Parameters required to initiate a realtime call and receive the SDP answer\nneeded to complete a WebRTC peer connection. Provide an SDP offer generated\nby your client and optionally configure the session that will answer the call." +}) +export type RealtimeClientEventSessionUpdate = { + readonly "event_id"?: string + readonly "type": "session.update" + readonly "session": { + readonly "type": "realtime" + readonly "output_modalities"?: ReadonlyArray<"text" | "audio"> + readonly "model"?: + | string + | "gpt-realtime" + | "gpt-realtime-1.5" + | "gpt-realtime-2" + | "gpt-realtime-2025-08-28" + | "gpt-4o-realtime-preview" + | "gpt-4o-realtime-preview-2024-10-01" + | "gpt-4o-realtime-preview-2024-12-17" + | "gpt-4o-realtime-preview-2025-06-03" + | "gpt-4o-mini-realtime-preview" + | "gpt-4o-mini-realtime-preview-2024-12-17" + | "gpt-realtime-mini" + | "gpt-realtime-mini-2025-10-06" + | "gpt-realtime-mini-2025-12-15" + | "gpt-audio-1.5" + | "gpt-audio-mini" + | "gpt-audio-mini-2025-10-06" + | "gpt-audio-mini-2025-12-15" + readonly "instructions"?: string + readonly "audio"?: { + readonly "input"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + readonly "delay"?: "minimal" | "low" | "medium" | "high" | "xhigh" + } + readonly "noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "turn_detection"?: RealtimeTurnDetection + } + readonly "output"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "voice"?: VoiceIdsShared | { readonly "id": string } + readonly "speed"?: number + } + } + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> + readonly "tracing"?: "auto" | { + readonly "workflow_name"?: string + readonly "group_id"?: string + readonly "metadata"?: {} + } | null + readonly "tools"?: ReadonlyArray + readonly "tool_choice"?: ToolChoiceOptions | ToolChoiceFunction | ToolChoiceMCP + readonly "parallel_tool_calls"?: boolean + readonly "reasoning"?: RealtimeReasoning + readonly "max_output_tokens"?: number | "inf" + readonly "truncation"?: RealtimeTruncation + readonly "prompt"?: Prompt + } | { + readonly "type": "transcription" + readonly "audio"?: { + readonly "input"?: { + readonly "format"?: RealtimeAudioFormats + readonly "transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + readonly "delay"?: "minimal" | "low" | "medium" | "high" | "xhigh" + } + readonly "noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "turn_detection"?: RealtimeTurnDetection + } + } + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> + } +} +export const RealtimeClientEventSessionUpdate = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "Optional client-generated ID used to identify this event. This is an arbitrary string that a client may assign. It will be passed back if there is an error with the event, but the corresponding `session.updated` event will not include it." + }).check(Schema.isMaxLength(512)) + ), + "type": Schema.Literal("session.update").annotate({ "description": "The event type, must be `session.update`." }), + "session": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("realtime").annotate({ + "description": "The type of session to create. Always `realtime` for the Realtime API.\n" + }), + "output_modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": + "The set of modalities the model can respond with. It defaults to `[\"audio\"]`, indicating\nthat the model will respond with audio plus a transcript. `[\"text\"]` can be used to make\nthe model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n" + }) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "gpt-realtime", + "gpt-realtime-1.5", + "gpt-realtime-2", + "gpt-realtime-2025-08-28", + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-realtime-preview-2025-06-03", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + "gpt-realtime-mini", + "gpt-realtime-mini-2025-10-06", + "gpt-realtime-mini-2025-12-15", + "gpt-audio-1.5", + "gpt-audio-mini", + "gpt-audio-mini-2025-10-06", + "gpt-audio-mini-2025-12-15" + ]) + ]).annotate({ "description": "The Realtime model used for this session.\n" }) + ), + "instructions": Schema.optionalKey(Schema.String.annotate({ + "description": + "The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\n\nNote that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n" + })), + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the input audio." }) + ), + "transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n" + }) + ), + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }) + ), + "prompt": Schema.optionalKey(Schema.String.annotate({ + "description": + "An optional text to guide the model's style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text string, for example \"expect words related to technology\".\nPrompt is not supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + })), + "delay": Schema.optionalKey( + Schema.Literals(["minimal", "low", "medium", "high", "xhigh"]).annotate({ + "description": + "Controls how long the model waits before emitting transcription text.\nHigher values can improve transcription accuracy at the cost of latency.\nOnly supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + }) + ) + }).annotate({ + "description": + "Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n" + }) + ), + "noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": + "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n" + }) + ), + "turn_detection": Schema.optionalKey(RealtimeTurnDetection) + })), + "output": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the output audio." }) + ), + "voice": Schema.optionalKey( + Schema.Union([ + VoiceIdsShared, + Schema.Struct({ + "id": Schema.String.annotate({ "description": "The custom voice ID, e.g. `voice_1234`." }) + }).annotate({ "description": "Custom voice reference." }) + ]).annotate({ + "title": "Voice", + "description": + "The voice the model uses to respond. Supported built-in voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, `verse`,\n`marin`, and `cedar`. You may also provide a custom voice object with\nan `id`, for example `{ \"id\": \"voice_1234\" }`. Voice cannot be changed\nduring the session once the model has responded with audio at least once.\nWe recommend `marin` and `cedar` for best quality.\n" + }) + ), + "speed": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The speed of the model's spoken response as a multiple of the original speed.\n1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed. This value can only be changed in between model turns, not while a response is in progress.\n\nThis parameter is a post-processing adjustment to the audio after it is generated, it's\nalso possible to prompt the model to speak faster or slower.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0.25)).check( + Schema.isLessThanOrEqualTo(1.5) + ) + ) + })) + }).annotate({ "description": "Configuration for input and output audio.\n" }) + ), + "include": Schema.optionalKey( + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }) + ), + "tracing": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Literal("auto").annotate({ + "title": "auto", + "description": + "Enables tracing and sets default values for tracing configuration options. Always `auto`.\n" + }), + Schema.Struct({ + "workflow_name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The name of the workflow to attach to this trace. This is used to\nname the trace in the Traces Dashboard.\n" + }) + ), + "group_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The group id to attach to this trace to enable filtering and\ngrouping in the Traces Dashboard.\n" + }) + ), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": + "The arbitrary metadata to attach to this trace to enable\nfiltering in the Traces Dashboard.\n" + }) + ) + }).annotate({ "title": "Tracing Configuration", "description": "Granular configuration for tracing.\n" }) + ], { mode: "oneOf" }).annotate({ + "title": "Tracing Configuration", + "description": + "Realtime API can write session traces to the [Traces Dashboard](https://platform.openai.com/logs?api=traces). Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n" + }), + Schema.Null + ]) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Union([RealtimeFunctionTool, MCPTool], { mode: "oneOf" })).annotate({ + "description": "Tools available to the model." + }) + ), + "tool_choice": Schema.optionalKey( + Schema.Union([ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], { mode: "oneOf" }).annotate({ + "description": + "How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n" + }) + ), + "parallel_tool_calls": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": + "Whether the model may call multiple tools in parallel. Only supported by\nreasoning Realtime models such as `gpt-realtime-2`.\n" + }) + ), + "reasoning": Schema.optionalKey(RealtimeReasoning), + "max_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n" + }) + ), + "truncation": Schema.optionalKey(RealtimeTruncation), + "prompt": Schema.optionalKey(Prompt) + }).annotate({ + "title": "Realtime session configuration", + "description": "Update the Realtime session. Choose either a realtime\nsession or a transcription session.\n" + }), + Schema.Struct({ + "type": Schema.Literal("transcription").annotate({ + "description": "The type of session to create. Always `transcription` for transcription sessions.\n" + }), + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey(RealtimeAudioFormats), + "transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n" + }) + ), + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }) + ), + "prompt": Schema.optionalKey(Schema.String.annotate({ + "description": + "An optional text to guide the model's style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text string, for example \"expect words related to technology\".\nPrompt is not supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + })), + "delay": Schema.optionalKey( + Schema.Literals(["minimal", "low", "medium", "high", "xhigh"]).annotate({ + "description": + "Controls how long the model waits before emitting transcription text.\nHigher values can improve transcription accuracy at the cost of latency.\nOnly supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + }) + ) + }).annotate({ + "description": + "Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n" + }) + ), + "noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": + "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n" + }) + ), + "turn_detection": Schema.optionalKey(RealtimeTurnDetection) + })) + }).annotate({ "description": "Configuration for input and output audio.\n" }) + ), + "include": Schema.optionalKey( + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }) + ) + }).annotate({ + "title": "Realtime transcription session configuration", + "description": "Update the Realtime session. Choose either a realtime\nsession or a transcription session.\n" + }) + ], { mode: "oneOf" }) +}).annotate({ + "description": + "Send this event to update the session’s configuration.\nThe client may send this event at any time to update any field\nexcept for `voice` and `model`. `voice` can be updated only if there have been no other audio outputs yet.\n\nWhen the server receives a `session.update`, it will respond\nwith a `session.updated` event showing the full, effective configuration.\nOnly the fields that are present in the `session.update` are updated. To clear a field like\n`instructions`, pass an empty string. To clear a field like `tools`, pass an empty array.\nTo clear a field like `turn_detection`, pass `null`.\n" +}) +export type RealtimeSession = { + readonly "id"?: string + readonly "object"?: "realtime.session" + readonly "modalities"?: ReadonlyArray<"text" | "audio"> + readonly "model"?: + | string + | "gpt-realtime" + | "gpt-realtime-1.5" + | "gpt-realtime-2025-08-28" + | "gpt-4o-realtime-preview" + | "gpt-4o-realtime-preview-2024-10-01" + | "gpt-4o-realtime-preview-2024-12-17" + | "gpt-4o-realtime-preview-2025-06-03" + | "gpt-4o-mini-realtime-preview" + | "gpt-4o-mini-realtime-preview-2024-12-17" + | "gpt-realtime-mini" + | "gpt-realtime-mini-2025-10-06" + | "gpt-realtime-mini-2025-12-15" + | "gpt-audio-1.5" + | "gpt-audio-mini" + | "gpt-audio-mini-2025-10-06" + | "gpt-audio-mini-2025-12-15" + readonly "instructions"?: string + readonly "voice"?: + | string + | "alloy" + | "ash" + | "ballad" + | "coral" + | "echo" + | "sage" + | "shimmer" + | "verse" + | "marin" + | "cedar" + readonly "input_audio_format"?: "pcm16" | "g711_ulaw" | "g711_alaw" + readonly "output_audio_format"?: "pcm16" | "g711_ulaw" | "g711_alaw" + readonly "input_audio_transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + } | null + readonly "turn_detection"?: RealtimeTurnDetection + readonly "input_audio_noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "speed"?: number + readonly "tracing"?: "auto" | { + readonly "workflow_name"?: string + readonly "group_id"?: string + readonly "metadata"?: {} + } | null + readonly "tools"?: ReadonlyArray + readonly "tool_choice"?: string + readonly "temperature"?: number + readonly "max_response_output_tokens"?: number | "inf" + readonly "expires_at"?: number + readonly "prompt"?: Prompt | null + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> | null +} +export const RealtimeSession = Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }) + ), + "object": Schema.optionalKey( + Schema.Literal("realtime.session").annotate({ "description": "The object type. Always `realtime.session`." }) + ), + "modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": "The set of modalities the model can respond with. To disable audio,\nset this to [\"text\"].\n" + }) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "gpt-realtime", + "gpt-realtime-1.5", + "gpt-realtime-2025-08-28", + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-realtime-preview-2025-06-03", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + "gpt-realtime-mini", + "gpt-realtime-mini-2025-10-06", + "gpt-realtime-mini-2025-12-15", + "gpt-audio-1.5", + "gpt-audio-mini", + "gpt-audio-mini-2025-10-06", + "gpt-audio-mini-2025-12-15" + ]) + ]).annotate({ "description": "The Realtime model used for this session.\n" }) + ), + "instructions": Schema.optionalKey(Schema.String.annotate({ + "description": + "The default system instructions (i.e. system message) prepended to model\ncalls. This field allows the client to guide the model on desired\nresponses. The model can be instructed on response content and format,\n(e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good\nresponses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion\ninto your voice\", \"laugh frequently\"). The instructions are not\nguaranteed to be followed by the model, but they provide guidance to the\nmodel on the desired behavior.\n\n\nNote that the server sets default instructions which will be used if this\nfield is not set and are visible in the `session.created` event at the\nstart of the session.\n" + })), + "voice": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals(["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse", "marin", "cedar"]) + ]).annotate({ + "description": + "The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n" + }) + ), + "input_audio_format": Schema.optionalKey( + Schema.Literals(["pcm16", "g711_ulaw", "g711_alaw"]).annotate({ + "description": + "The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate,\nsingle channel (mono), and little-endian byte order.\n" + }) + ), + "output_audio_format": Schema.optionalKey( + Schema.Literals(["pcm16", "g711_ulaw", "g711_alaw"]).annotate({ + "description": + "The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\nFor `pcm16`, output audio is sampled at a rate of 24kHz.\n" + }) + ), + "input_audio_transcription": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model used for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`.\n" + }) + ), + "language": Schema.optionalKey(Schema.String.annotate({ "description": "The language of the input audio.\n" })), + "prompt": Schema.optionalKey( + Schema.String.annotate({ + "description": "The prompt configured for input audio transcription, when present.\n" + }) + ) + }).annotate({ + "description": + "Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n" + }), + Schema.Null + ])), + "turn_detection": Schema.optionalKey(RealtimeTurnDetection), + "input_audio_noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": + "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n" + }) + ), + "speed": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The speed of the model's spoken response. 1.0 is the default speed. 0.25 is\nthe minimum speed. 1.5 is the maximum speed. This value can only be changed\nin between model turns, not while a response is in progress.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0.25)).check(Schema.isLessThanOrEqualTo(1.5)) + ), + "tracing": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Literal("auto").annotate({ "description": "Default tracing mode for the session.\n" }), + Schema.Struct({ + "workflow_name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n" + }) + ), + "group_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n" + }) + ), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": + "The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n" + }) + ) + }).annotate({ "title": "Tracing Configuration", "description": "Granular configuration for tracing.\n" }) + ], { mode: "oneOf" }).annotate({ + "title": "Tracing Configuration", + "description": + "Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n" + }), + Schema.Null + ]) + ), + "tools": Schema.optionalKey( + Schema.Array(RealtimeFunctionTool).annotate({ "description": "Tools (functions) available to the model." }) + ), + "tool_choice": Schema.optionalKey( + Schema.String.annotate({ + "description": "How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n" + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Sampling temperature for the model, limited to [0.6, 1.2]. For audio models a temperature of 0.8 is highly recommended for best performance.\n" + }).check(Schema.isFinite()) + ), + "max_response_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n" + }) + ), + "expires_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Expiration timestamp for the session, in seconds since epoch.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "prompt": Schema.optionalKey(Schema.Union([Prompt, Schema.Null])), + "include": Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "Additional fields to include in server outputs.\n- `item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }), + Schema.Null + ]) + ) +}).annotate({ "description": "Realtime session object for the beta interface." }) +export type RealtimeSessionCreateRequest = { + readonly "client_secret": { readonly "value": string; readonly "expires_at": number } + readonly "modalities"?: ReadonlyArray<"text" | "audio"> + readonly "instructions"?: string + readonly "voice"?: VoiceIdsShared | { readonly "id": string } + readonly "input_audio_format"?: string + readonly "output_audio_format"?: string + readonly "input_audio_transcription"?: { readonly "model"?: string } + readonly "speed"?: number + readonly "tracing"?: "auto" | { + readonly "workflow_name"?: string + readonly "group_id"?: string + readonly "metadata"?: {} + } + readonly "turn_detection"?: { + readonly "type"?: string + readonly "threshold"?: number + readonly "prefix_padding_ms"?: number + readonly "silence_duration_ms"?: number + } + readonly "tools"?: ReadonlyArray< + { + readonly "type"?: "function" + readonly "name"?: string + readonly "description"?: string + readonly "parameters"?: {} + } + > + readonly "tool_choice"?: string + readonly "temperature"?: number + readonly "max_response_output_tokens"?: number | "inf" + readonly "truncation"?: RealtimeTruncation + readonly "prompt"?: Prompt +} +export const RealtimeSessionCreateRequest = Schema.Struct({ + "client_secret": Schema.Struct({ + "value": Schema.String.annotate({ + "description": + "Ephemeral key usable in client environments to authenticate connections\nto the Realtime API. Use this in client-side environments rather than\na standard API token, which should only be used server-side.\n" + }), + "expires_at": Schema.Number.annotate({ + "description": "Timestamp for when the token expires. Currently, all tokens expire\nafter one minute.\n", + "format": "unixtime" + }).check(Schema.isInt()) + }).annotate({ "description": "Ephemeral key returned by the API." }), + "modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": "The set of modalities the model can respond with. To disable audio,\nset this to [\"text\"].\n" + }) + ), + "instructions": Schema.optionalKey(Schema.String.annotate({ + "description": + "The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\nNote that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n" + })), + "voice": Schema.optionalKey( + Schema.Union([ + VoiceIdsShared, + Schema.Struct({ "id": Schema.String.annotate({ "description": "The custom voice ID, e.g. `voice_1234`." }) }) + .annotate({ "description": "Custom voice reference." }) + ]).annotate({ + "title": "Voice", + "description": + "The voice the model uses to respond. Supported built-in voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, `verse`,\n`marin`, and `cedar`. You may also provide a custom voice object with an\n`id`, for example `{ \"id\": \"voice_1234\" }`. Voice cannot be changed during\nthe session once the model has responded with audio at least once.\n" + }) + ), + "input_audio_format": Schema.optionalKey( + Schema.String.annotate({ + "description": "The format of input audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }) + ), + "output_audio_format": Schema.optionalKey( + Schema.String.annotate({ + "description": "The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }) + ), + "input_audio_transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey(Schema.String.annotate({ "description": "The model to use for transcription.\n" })) + }).annotate({ + "description": + "Configuration for input audio transcription, defaults to off and can be\nset to `null` to turn off once on. Input audio transcription is not native\nto the model, since the model consumes audio directly. Transcription runs\nasynchronously and should be treated as rough guidance\nrather than the representation understood by the model.\n" + }) + ), + "speed": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The speed of the model's spoken response. 1.0 is the default speed. 0.25 is\nthe minimum speed. 1.5 is the maximum speed. This value can only be changed\nin between model turns, not while a response is in progress.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0.25)).check(Schema.isLessThanOrEqualTo(1.5)) + ), + "tracing": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto").annotate({ "description": "Default tracing mode for the session.\n" }), + Schema.Struct({ + "workflow_name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The name of the workflow to attach to this trace. This is used to\nname the trace in the traces dashboard.\n" + }) + ), + "group_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The group id to attach to this trace to enable filtering and\ngrouping in the traces dashboard.\n" + }) + ), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": + "The arbitrary metadata to attach to this trace to enable\nfiltering in the traces dashboard.\n" + }) + ) + }).annotate({ "title": "Tracing Configuration", "description": "Granular configuration for tracing.\n" }) + ], { mode: "oneOf" }).annotate({ + "title": "Tracing Configuration", + "description": + "Configuration options for tracing. Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n" + }) + ), + "turn_detection": Schema.optionalKey( + Schema.Struct({ + "type": Schema.optionalKey( + Schema.String.annotate({ "description": "Type of turn detection, only `server_vad` is currently supported.\n" }) + ), + "threshold": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. A\nhigher threshold will require louder audio to activate the model, and\nthus might perform better in noisy environments.\n" + }).check(Schema.isFinite()) + ), + "prefix_padding_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Amount of audio to include before the VAD detected speech (in\nmilliseconds). Defaults to 300ms.\n" + }).check(Schema.isInt()) + ), + "silence_duration_ms": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "Duration of silence to detect speech stop (in milliseconds). Defaults\nto 500ms. With shorter values the model will respond more quickly,\nbut may jump in on short pauses from the user.\n" + }).check(Schema.isInt()) + ) + }).annotate({ + "description": + "Configuration for turn detection. Can be set to `null` to turn off. Server\nVAD means that the model will detect the start and end of speech based on\naudio volume and respond at the end of user speech.\n" + }) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("function").annotate({ "description": "The type of the tool, i.e. `function`." }) + ), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the function." })), + "description": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The description of the function, including guidance on when and how\nto call it, and guidance about what to tell the user when calling\n(if anything).\n" + }) + ), + "parameters": Schema.optionalKey( + Schema.Struct({}).annotate({ "description": "Parameters of the function in JSON Schema." }) + ) + })).annotate({ "description": "Tools (functions) available to the model." }) + ), + "tool_choice": Schema.optionalKey( + Schema.String.annotate({ + "description": "How the model chooses tools. Options are `auto`, `none`, `required`, or\nspecify a function.\n" + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n" + }).check(Schema.isFinite()) + ), + "max_response_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n" + }) + ), + "truncation": Schema.optionalKey(RealtimeTruncation), + "prompt": Schema.optionalKey(Prompt) +}).annotate({ + "description": "A new Realtime session configuration, with an ephemeral key. Default TTL\nfor keys is one minute.\n" +}) +export type RealtimeSessionCreateRequestGA = { + readonly "type": "realtime" + readonly "output_modalities"?: ReadonlyArray<"text" | "audio"> + readonly "model"?: + | string + | "gpt-realtime" + | "gpt-realtime-1.5" + | "gpt-realtime-2" + | "gpt-realtime-2025-08-28" + | "gpt-4o-realtime-preview" + | "gpt-4o-realtime-preview-2024-10-01" + | "gpt-4o-realtime-preview-2024-12-17" + | "gpt-4o-realtime-preview-2025-06-03" + | "gpt-4o-mini-realtime-preview" + | "gpt-4o-mini-realtime-preview-2024-12-17" + | "gpt-realtime-mini" + | "gpt-realtime-mini-2025-10-06" + | "gpt-realtime-mini-2025-12-15" + | "gpt-audio-1.5" + | "gpt-audio-mini" + | "gpt-audio-mini-2025-10-06" + | "gpt-audio-mini-2025-12-15" + readonly "instructions"?: string + readonly "audio"?: { + readonly "input"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + readonly "delay"?: "minimal" | "low" | "medium" | "high" | "xhigh" + } + readonly "noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "turn_detection"?: RealtimeTurnDetection + } + readonly "output"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "voice"?: VoiceIdsShared | { readonly "id": string } + readonly "speed"?: number + } + } + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> + readonly "tracing"?: "auto" | { + readonly "workflow_name"?: string + readonly "group_id"?: string + readonly "metadata"?: {} + } | null + readonly "tools"?: ReadonlyArray + readonly "tool_choice"?: ToolChoiceOptions | ToolChoiceFunction | ToolChoiceMCP + readonly "parallel_tool_calls"?: boolean + readonly "reasoning"?: RealtimeReasoning + readonly "max_output_tokens"?: number | "inf" + readonly "truncation"?: RealtimeTruncation + readonly "prompt"?: Prompt +} +export const RealtimeSessionCreateRequestGA = Schema.Struct({ + "type": Schema.Literal("realtime").annotate({ + "description": "The type of session to create. Always `realtime` for the Realtime API.\n" + }), + "output_modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": + "The set of modalities the model can respond with. It defaults to `[\"audio\"]`, indicating\nthat the model will respond with audio plus a transcript. `[\"text\"]` can be used to make\nthe model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n" + }) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "gpt-realtime", + "gpt-realtime-1.5", + "gpt-realtime-2", + "gpt-realtime-2025-08-28", + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-realtime-preview-2025-06-03", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + "gpt-realtime-mini", + "gpt-realtime-mini-2025-10-06", + "gpt-realtime-mini-2025-12-15", + "gpt-audio-1.5", + "gpt-audio-mini", + "gpt-audio-mini-2025-10-06", + "gpt-audio-mini-2025-12-15" + ]) + ]).annotate({ "description": "The Realtime model used for this session.\n" }) + ), + "instructions": Schema.optionalKey(Schema.String.annotate({ + "description": + "The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\n\nNote that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n" + })), + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the input audio." }) + ), + "transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model to use for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`. Use `gpt-4o-transcribe-diarize` when you need diarization with speaker labels.\n" + }) + ), + "language": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The language of the input audio. Supplying the input language in\n[ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) (e.g. `en`) format\nwill improve accuracy and latency.\n" + }) + ), + "prompt": Schema.optionalKey(Schema.String.annotate({ + "description": + "An optional text to guide the model's style or continue a previous audio\nsegment.\nFor `whisper-1`, the [prompt is a list of keywords](/docs/guides/speech-to-text#prompting).\nFor `gpt-4o-transcribe` models (excluding `gpt-4o-transcribe-diarize`), the prompt is a free text string, for example \"expect words related to technology\".\nPrompt is not supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + })), + "delay": Schema.optionalKey( + Schema.Literals(["minimal", "low", "medium", "high", "xhigh"]).annotate({ + "description": + "Controls how long the model waits before emitting transcription text.\nHigher values can improve transcription accuracy at the cost of latency.\nOnly supported with `gpt-realtime-whisper` in GA Realtime sessions.\n" + }) + ) + }).annotate({ + "description": + "Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n" + }) + ), + "noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": + "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n" + }) + ), + "turn_detection": Schema.optionalKey(RealtimeTurnDetection) + })), + "output": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the output audio." }) + ), + "voice": Schema.optionalKey( + Schema.Union([ + VoiceIdsShared, + Schema.Struct({ + "id": Schema.String.annotate({ "description": "The custom voice ID, e.g. `voice_1234`." }) + }).annotate({ "description": "Custom voice reference." }) + ]).annotate({ + "title": "Voice", + "description": + "The voice the model uses to respond. Supported built-in voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, `verse`,\n`marin`, and `cedar`. You may also provide a custom voice object with\nan `id`, for example `{ \"id\": \"voice_1234\" }`. Voice cannot be changed\nduring the session once the model has responded with audio at least once.\nWe recommend `marin` and `cedar` for best quality.\n" + }) + ), + "speed": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The speed of the model's spoken response as a multiple of the original speed.\n1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed. This value can only be changed in between model turns, not while a response is in progress.\n\nThis parameter is a post-processing adjustment to the audio after it is generated, it's\nalso possible to prompt the model to speak faster or slower.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0.25)).check(Schema.isLessThanOrEqualTo(1.5)) + ) + })) + }).annotate({ "description": "Configuration for input and output audio.\n" }) + ), + "include": Schema.optionalKey( + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }) + ), + "tracing": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Literal("auto").annotate({ + "title": "auto", + "description": "Enables tracing and sets default values for tracing configuration options. Always `auto`.\n" + }), + Schema.Struct({ + "workflow_name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The name of the workflow to attach to this trace. This is used to\nname the trace in the Traces Dashboard.\n" + }) + ), + "group_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The group id to attach to this trace to enable filtering and\ngrouping in the Traces Dashboard.\n" + }) + ), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": + "The arbitrary metadata to attach to this trace to enable\nfiltering in the Traces Dashboard.\n" + }) + ) + }).annotate({ "title": "Tracing Configuration", "description": "Granular configuration for tracing.\n" }) + ], { mode: "oneOf" }).annotate({ + "title": "Tracing Configuration", + "description": + "Realtime API can write session traces to the [Traces Dashboard](https://platform.openai.com/logs?api=traces). Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n" + }), + Schema.Null + ]) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Union([RealtimeFunctionTool, MCPTool], { mode: "oneOf" })).annotate({ + "description": "Tools available to the model." + }) + ), + "tool_choice": Schema.optionalKey( + Schema.Union([ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], { mode: "oneOf" }).annotate({ + "description": + "How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n" + }) + ), + "parallel_tool_calls": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": + "Whether the model may call multiple tools in parallel. Only supported by\nreasoning Realtime models such as `gpt-realtime-2`.\n" + }) + ), + "reasoning": Schema.optionalKey(RealtimeReasoning), + "max_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n" + }) + ), + "truncation": Schema.optionalKey(RealtimeTruncation), + "prompt": Schema.optionalKey(Prompt) +}).annotate({ "title": "Realtime session configuration", "description": "Realtime session object configuration." }) +export type RealtimeSessionCreateResponseGA = { + readonly "type": "realtime" + readonly "id": string + readonly "object": "realtime.session" + readonly "expires_at"?: number + readonly "output_modalities"?: ReadonlyArray<"text" | "audio"> + readonly "model"?: + | string + | "gpt-realtime" + | "gpt-realtime-1.5" + | "gpt-realtime-2" + | "gpt-realtime-2025-08-28" + | "gpt-4o-realtime-preview" + | "gpt-4o-realtime-preview-2024-10-01" + | "gpt-4o-realtime-preview-2024-12-17" + | "gpt-4o-realtime-preview-2025-06-03" + | "gpt-4o-mini-realtime-preview" + | "gpt-4o-mini-realtime-preview-2024-12-17" + | "gpt-realtime-mini" + | "gpt-realtime-mini-2025-10-06" + | "gpt-realtime-mini-2025-12-15" + | "gpt-audio-1.5" + | "gpt-audio-mini" + | "gpt-audio-mini-2025-10-06" + | "gpt-audio-mini-2025-12-15" + readonly "instructions"?: string + readonly "audio"?: { + readonly "input"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "transcription"?: { + readonly "model"?: + | string + | "whisper-1" + | "gpt-4o-mini-transcribe" + | "gpt-4o-mini-transcribe-2025-12-15" + | "gpt-4o-transcribe" + | "gpt-4o-transcribe-diarize" + | "gpt-realtime-whisper" + readonly "language"?: string + readonly "prompt"?: string + } + readonly "noise_reduction"?: { readonly "type"?: NoiseReductionType } + readonly "turn_detection"?: RealtimeTurnDetection + } + readonly "output"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "voice"?: + | string + | "alloy" + | "ash" + | "ballad" + | "coral" + | "echo" + | "sage" + | "shimmer" + | "verse" + | "marin" + | "cedar" + readonly "speed"?: number + } + } + readonly "include"?: ReadonlyArray<"item.input_audio_transcription.logprobs"> + readonly "tracing"?: "auto" | { + readonly "workflow_name"?: string + readonly "group_id"?: string + readonly "metadata"?: {} + } | null + readonly "tools"?: ReadonlyArray + readonly "tool_choice"?: ToolChoiceOptions | ToolChoiceFunction | ToolChoiceMCP + readonly "reasoning"?: RealtimeReasoning + readonly "max_output_tokens"?: number | "inf" + readonly "truncation"?: RealtimeTruncation + readonly "prompt"?: Prompt +} +export const RealtimeSessionCreateResponseGA = Schema.Struct({ + "type": Schema.Literal("realtime").annotate({ + "description": "The type of session to create. Always `realtime` for the Realtime API.\n" + }), + "id": Schema.String.annotate({ + "description": "Unique identifier for the session that looks like `sess_1234567890abcdef`.\n" + }), + "object": Schema.Literal("realtime.session").annotate({ + "description": "The object type. Always `realtime.session`." + }), + "expires_at": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Expiration timestamp for the session, in seconds since epoch.", + "format": "unixtime" + }).check(Schema.isInt()) + ), + "output_modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": + "The set of modalities the model can respond with. It defaults to `[\"audio\"]`, indicating\nthat the model will respond with audio plus a transcript. `[\"text\"]` can be used to make\nthe model respond with text only. It is not possible to request both `text` and `audio` at the same time.\n" + }) + ), + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "gpt-realtime", + "gpt-realtime-1.5", + "gpt-realtime-2", + "gpt-realtime-2025-08-28", + "gpt-4o-realtime-preview", + "gpt-4o-realtime-preview-2024-10-01", + "gpt-4o-realtime-preview-2024-12-17", + "gpt-4o-realtime-preview-2025-06-03", + "gpt-4o-mini-realtime-preview", + "gpt-4o-mini-realtime-preview-2024-12-17", + "gpt-realtime-mini", + "gpt-realtime-mini-2025-10-06", + "gpt-realtime-mini-2025-12-15", + "gpt-audio-1.5", + "gpt-audio-mini", + "gpt-audio-mini-2025-10-06", + "gpt-audio-mini-2025-12-15" + ]) + ]).annotate({ "description": "The Realtime model used for this session.\n" }) + ), + "instructions": Schema.optionalKey(Schema.String.annotate({ + "description": + "The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\n\nNote that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n" + })), + "audio": Schema.optionalKey( + Schema.Struct({ + "input": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the input audio." }) + ), + "transcription": Schema.optionalKey( + Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals([ + "whisper-1", + "gpt-4o-mini-transcribe", + "gpt-4o-mini-transcribe-2025-12-15", + "gpt-4o-transcribe", + "gpt-4o-transcribe-diarize", + "gpt-realtime-whisper" + ]) + ]).annotate({ + "description": + "The model used for transcription. Current options are `whisper-1`, `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, `gpt-4o-transcribe`, `gpt-4o-transcribe-diarize`, and `gpt-realtime-whisper`.\n" + }) + ), + "language": Schema.optionalKey( + Schema.String.annotate({ "description": "The language of the input audio.\n" }) + ), + "prompt": Schema.optionalKey( + Schema.String.annotate({ + "description": "The prompt configured for input audio transcription, when present.\n" + }) + ) + }).annotate({ + "description": + "Configuration for input audio transcription, defaults to off and can be set to `null` to turn off once on. Input audio transcription is not native to the model, since the model consumes audio directly. Transcription runs asynchronously through [the /audio/transcriptions endpoint](/docs/api-reference/audio/createTranscription) and should be treated as guidance of input audio content rather than precisely what the model heard. The client can optionally set the language and prompt for transcription, these offer additional guidance to the transcription service.\n" + }) + ), + "noise_reduction": Schema.optionalKey( + Schema.Struct({ "type": Schema.optionalKey(NoiseReductionType) }).annotate({ + "description": + "Configuration for input audio noise reduction. This can be set to `null` to turn off.\nNoise reduction filters audio added to the input audio buffer before it is sent to VAD and the model.\nFiltering the audio can improve VAD and turn detection accuracy (reducing false positives) and model performance by improving perception of the input audio.\n" + }) + ), + "turn_detection": Schema.optionalKey(RealtimeTurnDetection) + })), + "output": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the output audio." }) + ), + "voice": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals(["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse", "marin", "cedar"]) + ]).annotate({ + "description": + "The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\nbest quality.\n" + }) + ), + "speed": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The speed of the model's spoken response as a multiple of the original speed.\n1.0 is the default speed. 0.25 is the minimum speed. 1.5 is the maximum speed. This value can only be changed in between model turns, not while a response is in progress.\n\nThis parameter is a post-processing adjustment to the audio after it is generated, it's\nalso possible to prompt the model to speak faster or slower.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0.25)).check(Schema.isLessThanOrEqualTo(1.5)) + ) + })) + }).annotate({ "description": "Configuration for input and output audio.\n" }) + ), + "include": Schema.optionalKey( + Schema.Array(Schema.Literal("item.input_audio_transcription.logprobs")).annotate({ + "description": + "Additional fields to include in server outputs.\n\n`item.input_audio_transcription.logprobs`: Include logprobs for input audio transcription.\n" + }) + ), + "tracing": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Literal("auto").annotate({ + "title": "auto", + "description": "Enables tracing and sets default values for tracing configuration options. Always `auto`.\n" + }), + Schema.Struct({ + "workflow_name": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The name of the workflow to attach to this trace. This is used to\nname the trace in the Traces Dashboard.\n" + }) + ), + "group_id": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The group id to attach to this trace to enable filtering and\ngrouping in the Traces Dashboard.\n" + }) + ), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": + "The arbitrary metadata to attach to this trace to enable\nfiltering in the Traces Dashboard.\n" + }) + ) + }).annotate({ "title": "Tracing Configuration", "description": "Granular configuration for tracing.\n" }) + ], { mode: "oneOf" }).annotate({ + "title": "Tracing Configuration", + "description": + "Realtime API can write session traces to the [Traces Dashboard](https://platform.openai.com/logs?api=traces). Set to null to disable tracing. Once\ntracing is enabled for a session, the configuration cannot be modified.\n\n`auto` will create a trace for the session with default values for the\nworkflow name, group id, and metadata.\n" + }), + Schema.Null + ]) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Union([RealtimeFunctionTool, MCPTool], { mode: "oneOf" })).annotate({ + "description": "Tools available to the model." + }) + ), + "tool_choice": Schema.optionalKey( + Schema.Union([ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], { mode: "oneOf" }).annotate({ + "description": + "How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n" + }) + ), + "reasoning": Schema.optionalKey(RealtimeReasoning), + "max_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n" + }) + ), + "truncation": Schema.optionalKey(RealtimeTruncation), + "prompt": Schema.optionalKey(Prompt) +}).annotate({ + "title": "Realtime session configuration object", + "description": "A Realtime session configuration object.\n" +}) +export type CreateVectorStoreFileRequest = { + readonly "file_id": string + readonly "chunking_strategy"?: ChunkingStrategyRequestParam + readonly "attributes"?: VectorStoreFileAttributes +} +export const CreateVectorStoreFileRequest = Schema.Struct({ + "file_id": Schema.String.annotate({ + "description": + "A [File](/docs/api-reference/files) ID that the vector store should use. Useful for tools like `file_search` that can access files. For multi-file ingestion, we recommend [`file_batches`](/docs/api-reference/vector-stores-file-batches/createBatch) to minimize per-vector-store write requests." + }), + "chunking_strategy": Schema.optionalKey(ChunkingStrategyRequestParam), + "attributes": Schema.optionalKey(VectorStoreFileAttributes) +}) +export type CreateTranscriptionResponseStreamEvent = + | TranscriptTextSegmentEvent + | TranscriptTextDeltaEvent + | TranscriptTextDoneEvent +export const CreateTranscriptionResponseStreamEvent = Schema.Union([ + TranscriptTextSegmentEvent, + TranscriptTextDeltaEvent, + TranscriptTextDoneEvent +]) +export type UsageResponse = { + readonly "object": "page" + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next_page": string | null +} +export const UsageResponse = Schema.Struct({ + "object": Schema.Literal("page"), + "data": Schema.Array(UsageTimeBucket), + "has_more": Schema.Boolean, + "next_page": Schema.Union([Schema.String, Schema.Null]) +}) +export type ListVectorStoresResponse = { + readonly "object": string + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean + readonly [x: string]: unknown +} +export const ListVectorStoresResponse = Schema.StructWithRest( + Schema.Struct({ + "object": Schema.String, + "data": Schema.Array(VectorStoreObject), + "first_id": Schema.String, + "last_id": Schema.String, + "has_more": Schema.Boolean + }), + [Schema.Record(Schema.String, Schema.Json)] +) +export type ListVectorStoreFilesResponse = { + readonly "object": string + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean + readonly [x: string]: unknown +} +export const ListVectorStoreFilesResponse = Schema.StructWithRest( + Schema.Struct({ + "object": Schema.String, + "data": Schema.Array(VectorStoreFileObject), + "first_id": Schema.String, + "last_id": Schema.String, + "has_more": Schema.Boolean + }), + [Schema.Record(Schema.String, Schema.Json)] +) +export type VectorStoreSearchResultsPage = { + readonly "object": "vector_store.search_results.page" + readonly "search_query": ReadonlyArray + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "next_page": string | null +} +export const VectorStoreSearchResultsPage = Schema.Struct({ + "object": Schema.Literal("vector_store.search_results.page").annotate({ + "description": "The object type, which is always `vector_store.search_results.page`" + }), + "search_query": Schema.Array(Schema.String.annotate({ "description": "The query used for this search." })), + "data": Schema.Array(VectorStoreSearchResultItem).annotate({ "description": "The list of search result items." }), + "has_more": Schema.Boolean.annotate({ "description": "Indicates if there are more results to fetch." }), + "next_page": Schema.Union([ + Schema.String.annotate({ "description": "The token for the next page, if any." }), + Schema.Null + ]) +}) +export type CreateContainerBody = { + readonly "name": string + readonly "file_ids"?: ReadonlyArray + readonly "expires_after"?: { readonly "anchor": "last_active_at"; readonly "minutes": number } + readonly "skills"?: ReadonlyArray + readonly "memory_limit"?: "1g" | "4g" | "16g" | "64g" + readonly "network_policy"?: ContainerNetworkPolicyDisabledParam | ContainerNetworkPolicyAllowlistParam +} +export const CreateContainerBody = Schema.Struct({ + "name": Schema.String.annotate({ "description": "Name of the container to create." }), + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ "description": "IDs of files to copy to the container." }) + ), + "expires_after": Schema.optionalKey( + Schema.Struct({ + "anchor": Schema.Literal("last_active_at").annotate({ + "description": "Time anchor for the expiration time. Currently only 'last_active_at' is supported." + }), + "minutes": Schema.Number.check(Schema.isInt()) + }).annotate({ "description": "Container expiration time in seconds relative to the 'anchor' time." }) + ), + "skills": Schema.optionalKey( + Schema.Array(Schema.Union([SkillReferenceParam, InlineSkillParam], { mode: "oneOf" })).annotate({ + "description": "An optional list of skills referenced by id or inline data." + }) + ), + "memory_limit": Schema.optionalKey( + Schema.Literals(["1g", "4g", "16g", "64g"]).annotate({ + "description": "Optional memory limit for the container. Defaults to \"1g\"." + }) + ), + "network_policy": Schema.optionalKey( + Schema.Union([ContainerNetworkPolicyDisabledParam, ContainerNetworkPolicyAllowlistParam], { mode: "oneOf" }) + .annotate({ "description": "Network access policy for the container." }) + ) +}) +export type AutoCodeInterpreterToolParam = { + readonly "type": "auto" + readonly "file_ids"?: ReadonlyArray + readonly "memory_limit"?: "1g" | "4g" | "16g" | "64g" | null + readonly "network_policy"?: ContainerNetworkPolicyDisabledParam | ContainerNetworkPolicyAllowlistParam +} +export const AutoCodeInterpreterToolParam = Schema.Struct({ + "type": Schema.Literal("auto").annotate({ "description": "Always `auto`." }), + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": "An optional list of uploaded files to make available to your code." + }).check(Schema.isMaxLength(50)) + ), + "memory_limit": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["1g", "4g", "16g", "64g"]).annotate({ + "description": "The memory limit for the code interpreter container." + }), + Schema.Null + ]) + ), + "network_policy": Schema.optionalKey( + Schema.Union([ContainerNetworkPolicyDisabledParam, ContainerNetworkPolicyAllowlistParam], { mode: "oneOf" }) + .annotate({ "description": "Network access policy for the container." }) + ) +}).annotate({ + "title": "CodeInterpreterToolAuto", + "description": + "Configuration for a code interpreter container. Optionally specify the IDs of the files to run the code on." +}) +export type ContainerAutoParam = { + readonly "type": "container_auto" + readonly "file_ids"?: ReadonlyArray + readonly "memory_limit"?: "1g" | "4g" | "16g" | "64g" | null + readonly "network_policy"?: ContainerNetworkPolicyDisabledParam | ContainerNetworkPolicyAllowlistParam + readonly "skills"?: ReadonlyArray +} +export const ContainerAutoParam = Schema.Struct({ + "type": Schema.Literal("container_auto").annotate({ + "description": "Automatically creates a container for this request" + }), + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": "An optional list of uploaded files to make available to your code." + }).check(Schema.isMaxLength(50)) + ), + "memory_limit": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["1g", "4g", "16g", "64g"]).annotate({ "description": "The memory limit for the container." }), + Schema.Null + ]) + ), + "network_policy": Schema.optionalKey( + Schema.Union([ContainerNetworkPolicyDisabledParam, ContainerNetworkPolicyAllowlistParam], { mode: "oneOf" }) + .annotate({ "description": "Network access policy for the container." }) + ), + "skills": Schema.optionalKey( + Schema.Array(Schema.Union([SkillReferenceParam, InlineSkillParam], { mode: "oneOf" })).annotate({ + "description": "An optional list of skills referenced by id or inline data." + }).check(Schema.isMaxLength(200)) + ) +}) +export type EvalItemContentArray = ReadonlyArray +export const EvalItemContentArray = Schema.Array(EvalItemContentItem).annotate({ + "title": "An array of Input text, Output text, Input image, and Input audio", + "description": + "A list of inputs, each of which may be either an input text, output text, input\nimage, or input audio object.\n" +}) +export type OutputTextContent = { + readonly "type": "output_text" + readonly "text": string + readonly "annotations": ReadonlyArray + readonly "logprobs": ReadonlyArray +} +export const OutputTextContent = Schema.Struct({ + "type": Schema.Literal("output_text").annotate({ + "description": "The type of the output text. Always `output_text`." + }), + "text": Schema.String.annotate({ "description": "The text output from the model." }), + "annotations": Schema.Array(Annotation).annotate({ "description": "The annotations of the text output." }), + "logprobs": Schema.Array(LogProb) +}).annotate({ "title": "Output text", "description": "A text output from the model." }) +export type CustomToolCallOutput = { + readonly "type": "custom_tool_call_output" + readonly "id"?: string + readonly "call_id": string + readonly "output": string | ReadonlyArray +} +export const CustomToolCallOutput = Schema.Struct({ + "type": Schema.Literal("custom_tool_call_output").annotate({ + "description": "The type of the custom tool call output. Always `custom_tool_call_output`.\n" + }), + "id": Schema.optionalKey( + Schema.String.annotate({ "description": "The unique ID of the custom tool call output in the OpenAI platform.\n" }) + ), + "call_id": Schema.String.annotate({ + "description": "The call ID, used to map this custom tool call output to a custom tool call.\n" + }), + "output": Schema.Union([ + Schema.String.annotate({ + "title": "string output", + "description": "A string of the output of the custom tool call.\n" + }), + Schema.Array(FunctionAndCustomToolCallOutput).annotate({ + "title": "output content list", + "description": "Text, image, or file output of the custom tool call.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "The output from the custom tool call generated by your code.\nCan be a string or an list of output content.\n" + }) +}).annotate({ + "title": "Custom tool call output", + "description": "The output of a custom tool call from your code, being sent back to the model.\n" +}) +export type CustomToolCallOutputResource = { + readonly "type": "custom_tool_call_output" + readonly "id": string + readonly "call_id": string + readonly "output": string | ReadonlyArray + readonly "status": "in_progress" | "completed" | "incomplete" + readonly "created_by"?: string +} +export const CustomToolCallOutputResource = Schema.Struct({ + "type": Schema.Literal("custom_tool_call_output").annotate({ + "description": "The type of the custom tool call output. Always `custom_tool_call_output`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the custom tool call output item.\n" }), + "call_id": Schema.String.annotate({ + "description": "The call ID, used to map this custom tool call output to a custom tool call.\n" + }), + "output": Schema.Union([ + Schema.String.annotate({ + "title": "string output", + "description": "A string of the output of the custom tool call.\n" + }), + Schema.Array(FunctionAndCustomToolCallOutput).annotate({ + "title": "output content list", + "description": "Text, image, or file output of the custom tool call.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "The output from the custom tool call generated by your code.\nCan be a string or an list of output content.\n" + }), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item.\n" }) + ) +}).annotate({ + "title": "Custom tool call output", + "description": "The output of a custom tool call from your code, being sent back to the model.\n" +}) +export type FunctionToolCallOutput = { + readonly "id"?: string + readonly "type": "function_call_output" + readonly "call_id": string + readonly "output": string | ReadonlyArray + readonly "status"?: "in_progress" | "completed" | "incomplete" +} +export const FunctionToolCallOutput = Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ + "description": "The unique ID of the function tool call output. Populated when this item\nis returned via API.\n" + }) + ), + "type": Schema.Literal("function_call_output").annotate({ + "description": "The type of the function tool call output. Always `function_call_output`.\n" + }), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the function tool call generated by the model.\n" + }), + "output": Schema.Union([ + Schema.String.annotate({ + "title": "string output", + "description": "A string of the output of the function call.\n" + }), + Schema.Array(FunctionAndCustomToolCallOutput).annotate({ + "title": "output content list", + "description": "Text, image, or file output of the function call.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "The output from the function call generated by your code.\nCan be a string or an list of output content.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + ) +}).annotate({ "title": "Function tool call output", "description": "The output of a function tool call.\n" }) +export type FunctionToolCallOutputResource = { + readonly "id": string + readonly "type": "function_call_output" + readonly "call_id": string + readonly "output": string | ReadonlyArray + readonly "status": "in_progress" | "completed" | "incomplete" + readonly "created_by"?: string +} +export const FunctionToolCallOutputResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the function call tool output.\n" }), + "type": Schema.Literal("function_call_output").annotate({ + "description": "The type of the function tool call output. Always `function_call_output`.\n" + }), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the function tool call generated by the model.\n" + }), + "output": Schema.Union([ + Schema.String.annotate({ + "title": "string output", + "description": "A string of the output of the function call.\n" + }), + Schema.Array(FunctionAndCustomToolCallOutput).annotate({ + "title": "output content list", + "description": "Text, image, or file output of the function call.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "The output from the function call generated by your code.\nCan be a string or an list of output content.\n" + }), + "status": Schema.Union([ + Schema.Literal("in_progress").annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }), + Schema.Literal("completed").annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }), + Schema.Literal("incomplete").annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + ]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item.\n" }) + ) +}).annotate({ "title": "Function tool call output", "description": "The output of a function tool call.\n" }) +export type InputMessageContentList = ReadonlyArray +export const InputMessageContentList = Schema.Array(InputContent).annotate({ + "title": "Input item content list", + "description": "A list of one or many input items to the model, containing different content \ntypes.\n" +}) +export type ComputerAction = + | ClickParam + | DoubleClickAction + | DragParam + | KeyPressAction + | MoveParam + | ScreenshotParam + | ScrollParam + | TypeParam + | WaitParam +export const ComputerAction = Schema.Union([ + ClickParam, + DoubleClickAction, + DragParam, + KeyPressAction, + MoveParam, + ScreenshotParam, + ScrollParam, + TypeParam, + WaitParam +], { mode: "oneOf" }) +export type NamespaceToolParam = { + readonly "type": "namespace" + readonly "name": string + readonly "description": string + readonly "tools": ReadonlyArray +} +export const NamespaceToolParam = Schema.Struct({ + "type": Schema.Literal("namespace").annotate({ "description": "The type of the tool. Always `namespace`." }), + "name": Schema.String.annotate({ "description": "The namespace name used in tool calls (for example, `crm`)." }) + .check(Schema.isMinLength(1)), + "description": Schema.String.annotate({ "description": "A description of the namespace shown to the model." }).check( + Schema.isMinLength(1) + ), + "tools": Schema.Array( + Schema.Union([FunctionToolParam, CustomToolParam], { mode: "oneOf" }).annotate({ + "description": "A function or custom tool that belongs to a namespace." + }) + ).annotate({ "description": "The function/custom tools available inside this namespace." }).check( + Schema.isMinLength(1) + ) +}).annotate({ "title": "Namespace", "description": "Groups function/custom tools under a shared namespace." }) +export type FunctionShellCallOutput = { + readonly "type": "shell_call_output" + readonly "id": string + readonly "call_id": string + readonly "status": "in_progress" | "completed" | "incomplete" + readonly "output": ReadonlyArray + readonly "max_output_length": number | null + readonly "created_by"?: string +} +export const FunctionShellCallOutput = Schema.Struct({ + "type": Schema.Literal("shell_call_output").annotate({ + "description": "The type of the shell call output. Always `shell_call_output`." + }), + "id": Schema.String.annotate({ + "description": "The unique ID of the shell call output. Populated when this item is returned via API." + }), + "call_id": Schema.String.annotate({ "description": "The unique ID of the shell tool call generated by the model." }), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the shell call output. One of `in_progress`, `completed`, or `incomplete`." + }), + "output": Schema.Array(FunctionShellCallOutputContent).annotate({ + "description": "An array of shell call output contents" + }), + "max_output_length": Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum length of the shell command output. This is generated by the model and should be passed back with the raw output." + }).check(Schema.isInt()), + Schema.Null + ]), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item." }) + ) +}).annotate({ "title": "Shell call output", "description": "The output of a shell tool call that was emitted." }) +export type ImagesResponse = { + readonly "created": number + readonly "data"?: ReadonlyArray + readonly "background"?: "transparent" | "opaque" + readonly "output_format"?: "png" | "webp" | "jpeg" + readonly "size"?: "1024x1024" | "1024x1536" | "1536x1024" + readonly "quality"?: "low" | "medium" | "high" + readonly "usage"?: ImageGenUsage +} +export const ImagesResponse = Schema.Struct({ + "created": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the image was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "data": Schema.optionalKey(Schema.Array(Image).annotate({ "description": "The list of generated images." })), + "background": Schema.optionalKey( + Schema.Literals(["transparent", "opaque"]).annotate({ + "description": "The background parameter used for the image generation. Either `transparent` or `opaque`." + }) + ), + "output_format": Schema.optionalKey( + Schema.Literals(["png", "webp", "jpeg"]).annotate({ + "description": "The output format of the image generation. Either `png`, `webp`, or `jpeg`." + }) + ), + "size": Schema.optionalKey( + Schema.Literals(["1024x1024", "1024x1536", "1536x1024"]).annotate({ + "description": "The size of the image generated. Either `1024x1024`, `1024x1536`, or `1536x1024`." + }) + ), + "quality": Schema.optionalKey( + Schema.Literals(["low", "medium", "high"]).annotate({ + "description": "The quality of the image generated. Either `low`, `medium`, or `high`." + }) + ), + "usage": Schema.optionalKey(ImageGenUsage) +}).annotate({ "title": "Image generation response", "description": "The response from the image generation endpoint." }) +export type AssistantMessageItem = { + readonly "id": string + readonly "object": "chatkit.thread_item" + readonly "created_at": number + readonly "thread_id": string + readonly "type": "chatkit.assistant_message" + readonly "content": ReadonlyArray +} +export const AssistantMessageItem = Schema.Struct({ + "id": Schema.String.annotate({ "description": "Identifier of the thread item." }), + "object": Schema.Literal("chatkit.thread_item").annotate({ + "description": "Type discriminator that is always `chatkit.thread_item`." + }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) for when the item was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "thread_id": Schema.String.annotate({ "description": "Identifier of the parent thread." }), + "type": Schema.Literal("chatkit.assistant_message").annotate({ + "description": "Type discriminator that is always `chatkit.assistant_message`." + }), + "content": Schema.Array(ResponseOutputText).annotate({ "description": "Ordered assistant response segments." }) +}).annotate({ "title": "Assistant message", "description": "Assistant-authored message within a thread." }) +export type ThreadListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "last_id": string | null + readonly "has_more": boolean +} +export const ThreadListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The type of object returned, must be `list`." }), + "data": Schema.Array(ThreadResource).annotate({ "description": "A list of items" }), + "first_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the first item in the list." }), + Schema.Null + ]), + "last_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the last item in the list." }), + Schema.Null + ]), + "has_more": Schema.Boolean.annotate({ "description": "Whether there are more items available." }) +}).annotate({ "title": "Threads", "description": "A paginated list of ChatKit threads." }) +export type AuditLog = { + readonly "id": string + readonly "type": AuditLogEventType + readonly "effective_at": number + readonly "project"?: { readonly "id"?: string; readonly "name"?: string } + readonly "actor"?: AuditLogActor | null + readonly "api_key.created"?: { + readonly "id"?: string + readonly "data"?: { readonly "scopes"?: ReadonlyArray } + } + readonly "api_key.updated"?: { + readonly "id"?: string + readonly "changes_requested"?: { readonly "scopes"?: ReadonlyArray } + } + readonly "api_key.deleted"?: { readonly "id"?: string } + readonly "checkpoint.permission.created"?: { + readonly "id"?: string + readonly "data"?: { readonly "project_id"?: string; readonly "fine_tuned_model_checkpoint"?: string } + } + readonly "checkpoint.permission.deleted"?: { readonly "id"?: string } + readonly "external_key.registered"?: { readonly "id"?: string; readonly "data"?: {} } + readonly "external_key.removed"?: { readonly "id"?: string } + readonly "group.created"?: { readonly "id"?: string; readonly "data"?: { readonly "group_name"?: string } } + readonly "group.updated"?: { + readonly "id"?: string + readonly "changes_requested"?: { readonly "group_name"?: string } + } + readonly "group.deleted"?: { readonly "id"?: string } + readonly "scim.enabled"?: { readonly "id"?: string } + readonly "scim.disabled"?: { readonly "id"?: string } + readonly "invite.sent"?: { + readonly "id"?: string + readonly "data"?: { readonly "email"?: string; readonly "role"?: string } + } + readonly "invite.accepted"?: { readonly "id"?: string } + readonly "invite.deleted"?: { readonly "id"?: string } + readonly "ip_allowlist.created"?: { + readonly "id"?: string + readonly "name"?: string + readonly "allowed_ips"?: ReadonlyArray + } + readonly "ip_allowlist.updated"?: { readonly "id"?: string; readonly "allowed_ips"?: ReadonlyArray } + readonly "ip_allowlist.deleted"?: { + readonly "id"?: string + readonly "name"?: string + readonly "allowed_ips"?: ReadonlyArray + } + readonly "ip_allowlist.config.activated"?: { + readonly "configs"?: ReadonlyArray<{ readonly "id"?: string; readonly "name"?: string }> + } + readonly "ip_allowlist.config.deactivated"?: { + readonly "configs"?: ReadonlyArray<{ readonly "id"?: string; readonly "name"?: string }> + } + readonly "login.succeeded"?: {} + readonly "login.failed"?: { readonly "error_code"?: string; readonly "error_message"?: string } + readonly "logout.succeeded"?: {} + readonly "logout.failed"?: { readonly "error_code"?: string; readonly "error_message"?: string } + readonly "organization.updated"?: { + readonly "id"?: string + readonly "changes_requested"?: { + readonly "title"?: string + readonly "description"?: string + readonly "name"?: string + readonly "threads_ui_visibility"?: string + readonly "usage_dashboard_visibility"?: string + readonly "api_call_logging"?: string + readonly "api_call_logging_project_ids"?: string + } + } + readonly "project.created"?: { + readonly "id"?: string + readonly "data"?: { readonly "name"?: string; readonly "title"?: string } + } + readonly "project.updated"?: { readonly "id"?: string; readonly "changes_requested"?: { readonly "title"?: string } } + readonly "project.archived"?: { readonly "id"?: string } + readonly "project.deleted"?: { readonly "id"?: string } + readonly "rate_limit.updated"?: { + readonly "id"?: string + readonly "changes_requested"?: { + readonly "max_requests_per_1_minute"?: number + readonly "max_tokens_per_1_minute"?: number + readonly "max_images_per_1_minute"?: number + readonly "max_audio_megabytes_per_1_minute"?: number + readonly "max_requests_per_1_day"?: number + readonly "batch_1_day_max_input_tokens"?: number + } + } + readonly "rate_limit.deleted"?: { readonly "id"?: string } + readonly "role.created"?: { + readonly "id"?: string + readonly "role_name"?: string + readonly "permissions"?: ReadonlyArray + readonly "resource_type"?: string + readonly "resource_id"?: string + } + readonly "role.updated"?: { + readonly "id"?: string + readonly "changes_requested"?: { + readonly "role_name"?: string + readonly "resource_id"?: string + readonly "resource_type"?: string + readonly "permissions_added"?: ReadonlyArray + readonly "permissions_removed"?: ReadonlyArray + readonly "description"?: string + readonly "metadata"?: {} + } + } + readonly "role.deleted"?: { readonly "id"?: string } + readonly "role.assignment.created"?: { + readonly "id"?: string + readonly "principal_id"?: string + readonly "principal_type"?: string + readonly "resource_id"?: string + readonly "resource_type"?: string + } + readonly "role.assignment.deleted"?: { + readonly "id"?: string + readonly "principal_id"?: string + readonly "principal_type"?: string + readonly "resource_id"?: string + readonly "resource_type"?: string + } + readonly "service_account.created"?: { readonly "id"?: string; readonly "data"?: { readonly "role"?: string } } + readonly "service_account.updated"?: { + readonly "id"?: string + readonly "changes_requested"?: { readonly "role"?: string } + } + readonly "service_account.deleted"?: { readonly "id"?: string } + readonly "user.added"?: { readonly "id"?: string; readonly "data"?: { readonly "role"?: string } } + readonly "user.updated"?: { readonly "id"?: string; readonly "changes_requested"?: { readonly "role"?: string } } + readonly "user.deleted"?: { readonly "id"?: string } + readonly "certificate.created"?: { readonly "id"?: string; readonly "name"?: string } + readonly "certificate.updated"?: { readonly "id"?: string; readonly "name"?: string } + readonly "certificate.deleted"?: { readonly "id"?: string; readonly "name"?: string; readonly "certificate"?: string } + readonly "certificates.activated"?: { + readonly "certificates"?: ReadonlyArray<{ readonly "id"?: string; readonly "name"?: string }> + } + readonly "certificates.deactivated"?: { + readonly "certificates"?: ReadonlyArray<{ readonly "id"?: string; readonly "name"?: string }> + } +} +export const AuditLog = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The ID of this log." }), + "type": AuditLogEventType, + "effective_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of the event.", + "format": "unixtime" + }).check(Schema.isInt()), + "project": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The project ID." })), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The project title." })) + }).annotate({ + "description": + "The project that the action was scoped to. Absent for actions not scoped to projects. Note that any admin actions taken via Admin API keys are associated with the default project." + }) + ), + "actor": Schema.optionalKey(Schema.Union([AuditLogActor, Schema.Null])), + "api_key.created": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The tracking ID of the API key." })), + "data": Schema.optionalKey( + Schema.Struct({ + "scopes": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": "A list of scopes allowed for the API key, e.g. `[\"api.model.request\"]`" + }) + ) + }).annotate({ "description": "The payload used to create the API key." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "api_key.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The tracking ID of the API key." })), + "changes_requested": Schema.optionalKey( + Schema.Struct({ + "scopes": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": "A list of scopes allowed for the API key, e.g. `[\"api.model.request\"]`" + }) + ) + }).annotate({ "description": "The payload used to update the API key." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "api_key.deleted": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The tracking ID of the API key." })) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "checkpoint.permission.created": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the checkpoint permission." })), + "data": Schema.optionalKey( + Schema.Struct({ + "project_id": Schema.optionalKey( + Schema.String.annotate({ + "description": "The ID of the project that the checkpoint permission was created for." + }) + ), + "fine_tuned_model_checkpoint": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the fine-tuned model checkpoint." }) + ) + }).annotate({ "description": "The payload used to create the checkpoint permission." }) + ) + }).annotate({ + "description": "The project and fine-tuned model checkpoint that the checkpoint permission was created for." + }) + ), + "checkpoint.permission.deleted": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the checkpoint permission." })) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "external_key.registered": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the external key configuration." })), + "data": Schema.optionalKey( + Schema.Struct({}).annotate({ "description": "The configuration for the external key." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "external_key.removed": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the external key configuration." })) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "group.created": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the group." })), + "data": Schema.optionalKey( + Schema.Struct({ + "group_name": Schema.optionalKey(Schema.String.annotate({ "description": "The group name." })) + }).annotate({ "description": "Information about the created group." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "group.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the group." })), + "changes_requested": Schema.optionalKey( + Schema.Struct({ + "group_name": Schema.optionalKey(Schema.String.annotate({ "description": "The updated group name." })) + }).annotate({ "description": "The payload used to update the group." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "group.deleted": Schema.optionalKey( + Schema.Struct({ "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the group." })) }) + .annotate({ "description": "The details for events with this `type`." }) + ), + "scim.enabled": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the SCIM was enabled for." })) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "scim.disabled": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the SCIM was disabled for." })) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "invite.sent": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the invite." })), + "data": Schema.optionalKey( + Schema.Struct({ + "email": Schema.optionalKey( + Schema.String.annotate({ "description": "The email invited to the organization." }) + ), + "role": Schema.optionalKey( + Schema.String.annotate({ + "description": "The role the email was invited to be. Is either `owner` or `member`." + }) + ) + }).annotate({ "description": "The payload used to create the invite." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "invite.accepted": Schema.optionalKey( + Schema.Struct({ "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the invite." })) }) + .annotate({ "description": "The details for events with this `type`." }) + ), + "invite.deleted": Schema.optionalKey( + Schema.Struct({ "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the invite." })) }) + .annotate({ "description": "The details for events with this `type`." }) + ), + "ip_allowlist.created": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the IP allowlist configuration." })), + "name": Schema.optionalKey( + Schema.String.annotate({ "description": "The name of the IP allowlist configuration." }) + ), + "allowed_ips": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": "The IP addresses or CIDR ranges included in the configuration." + }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "ip_allowlist.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the IP allowlist configuration." })), + "allowed_ips": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": "The updated set of IP addresses or CIDR ranges in the configuration." + }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "ip_allowlist.deleted": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The ID of the IP allowlist configuration." })), + "name": Schema.optionalKey( + Schema.String.annotate({ "description": "The name of the IP allowlist configuration." }) + ), + "allowed_ips": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": "The IP addresses or CIDR ranges that were in the configuration." + }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "ip_allowlist.config.activated": Schema.optionalKey( + Schema.Struct({ + "configs": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the IP allowlist configuration." }) + ), + "name": Schema.optionalKey( + Schema.String.annotate({ "description": "The name of the IP allowlist configuration." }) + ) + }) + ).annotate({ "description": "The configurations that were activated." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "ip_allowlist.config.deactivated": Schema.optionalKey( + Schema.Struct({ + "configs": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the IP allowlist configuration." }) + ), + "name": Schema.optionalKey( + Schema.String.annotate({ "description": "The name of the IP allowlist configuration." }) + ) + }) + ).annotate({ "description": "The configurations that were deactivated." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "login.succeeded": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": "This event has no additional fields beyond the standard audit log attributes." + }) + ), + "login.failed": Schema.optionalKey( + Schema.Struct({ + "error_code": Schema.optionalKey(Schema.String.annotate({ "description": "The error code of the failure." })), + "error_message": Schema.optionalKey( + Schema.String.annotate({ "description": "The error message of the failure." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "logout.succeeded": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": "This event has no additional fields beyond the standard audit log attributes." + }) + ), + "logout.failed": Schema.optionalKey( + Schema.Struct({ + "error_code": Schema.optionalKey(Schema.String.annotate({ "description": "The error code of the failure." })), + "error_message": Schema.optionalKey( + Schema.String.annotate({ "description": "The error message of the failure." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "organization.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The organization ID." })), + "changes_requested": Schema.optionalKey( + Schema.Struct({ + "title": Schema.optionalKey(Schema.String.annotate({ "description": "The organization title." })), + "description": Schema.optionalKey(Schema.String.annotate({ "description": "The organization description." })), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The organization name." })), + "threads_ui_visibility": Schema.optionalKey( + Schema.String.annotate({ + "description": + "Visibility of the threads page which shows messages created with the Assistants API and Playground. One of `ANY_ROLE`, `OWNERS`, or `NONE`." + }) + ), + "usage_dashboard_visibility": Schema.optionalKey( + Schema.String.annotate({ + "description": + "Visibility of the usage dashboard which shows activity and costs for your organization. One of `ANY_ROLE` or `OWNERS`." + }) + ), + "api_call_logging": Schema.optionalKey( + Schema.String.annotate({ + "description": + "How your organization logs data from supported API calls. One of `disabled`, `enabled_per_call`, `enabled_for_all_projects`, or `enabled_for_selected_projects`" + }) + ), + "api_call_logging_project_ids": Schema.optionalKey( + Schema.String.annotate({ + "description": "The list of project ids if api_call_logging is set to `enabled_for_selected_projects`" + }) + ) + }).annotate({ "description": "The payload used to update the organization settings." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "project.created": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The project ID." })), + "data": Schema.optionalKey( + Schema.Struct({ + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The project name." })), + "title": Schema.optionalKey( + Schema.String.annotate({ "description": "The title of the project as seen on the dashboard." }) + ) + }).annotate({ "description": "The payload used to create the project." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "project.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The project ID." })), + "changes_requested": Schema.optionalKey( + Schema.Struct({ + "title": Schema.optionalKey( + Schema.String.annotate({ "description": "The title of the project as seen on the dashboard." }) + ) + }).annotate({ "description": "The payload used to update the project." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "project.archived": Schema.optionalKey( + Schema.Struct({ "id": Schema.optionalKey(Schema.String.annotate({ "description": "The project ID." })) }).annotate({ + "description": "The details for events with this `type`." + }) + ), + "project.deleted": Schema.optionalKey( + Schema.Struct({ "id": Schema.optionalKey(Schema.String.annotate({ "description": "The project ID." })) }).annotate({ + "description": "The details for events with this `type`." + }) + ), + "rate_limit.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The rate limit ID" })), + "changes_requested": Schema.optionalKey( + Schema.Struct({ + "max_requests_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum requests per minute." }).check(Schema.isInt()) + ), + "max_tokens_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum tokens per minute." }).check(Schema.isInt()) + ), + "max_images_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The maximum images per minute. Only relevant for certain models." + }).check(Schema.isInt()) + ), + "max_audio_megabytes_per_1_minute": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The maximum audio megabytes per minute. Only relevant for certain models." + }).check(Schema.isInt()) + ), + "max_requests_per_1_day": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum requests per day. Only relevant for certain models." }) + .check(Schema.isInt()) + ), + "batch_1_day_max_input_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The maximum batch input tokens per day. Only relevant for certain models." + }).check(Schema.isInt()) + ) + }).annotate({ "description": "The payload used to update the rate limits." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "rate_limit.deleted": Schema.optionalKey( + Schema.Struct({ "id": Schema.optionalKey(Schema.String.annotate({ "description": "The rate limit ID" })) }) + .annotate({ "description": "The details for events with this `type`." }) + ), + "role.created": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The role ID." })), + "role_name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the role." })), + "permissions": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ "description": "The permissions granted by the role." }) + ), + "resource_type": Schema.optionalKey( + Schema.String.annotate({ "description": "The type of resource the role belongs to." }) + ), + "resource_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The resource the role is scoped to." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "role.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The role ID." })), + "changes_requested": Schema.optionalKey( + Schema.Struct({ + "role_name": Schema.optionalKey( + Schema.String.annotate({ "description": "The updated role name, when provided." }) + ), + "resource_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The resource the role is scoped to." }) + ), + "resource_type": Schema.optionalKey( + Schema.String.annotate({ "description": "The type of resource the role belongs to." }) + ), + "permissions_added": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ "description": "The permissions added to the role." }) + ), + "permissions_removed": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ "description": "The permissions removed from the role." }) + ), + "description": Schema.optionalKey( + Schema.String.annotate({ "description": "The updated role description, when provided." }) + ), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ "description": "Additional metadata stored on the role." }) + ) + }).annotate({ "description": "The payload used to update the role." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "role.deleted": Schema.optionalKey( + Schema.Struct({ "id": Schema.optionalKey(Schema.String.annotate({ "description": "The role ID." })) }).annotate({ + "description": "The details for events with this `type`." + }) + ), + "role.assignment.created": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The identifier of the role assignment." })), + "principal_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The principal (user or group) that received the role." }) + ), + "principal_type": Schema.optionalKey( + Schema.String.annotate({ "description": "The type of principal (user or group) that received the role." }) + ), + "resource_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The resource the role assignment is scoped to." }) + ), + "resource_type": Schema.optionalKey( + Schema.String.annotate({ "description": "The type of resource the role assignment is scoped to." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "role.assignment.deleted": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The identifier of the role assignment." })), + "principal_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The principal (user or group) that had the role removed." }) + ), + "principal_type": Schema.optionalKey( + Schema.String.annotate({ "description": "The type of principal (user or group) that had the role removed." }) + ), + "resource_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The resource the role assignment was scoped to." }) + ), + "resource_type": Schema.optionalKey( + Schema.String.annotate({ "description": "The type of resource the role assignment was scoped to." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "service_account.created": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The service account ID." })), + "data": Schema.optionalKey( + Schema.Struct({ + "role": Schema.optionalKey( + Schema.String.annotate({ "description": "The role of the service account. Is either `owner` or `member`." }) + ) + }).annotate({ "description": "The payload used to create the service account." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "service_account.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The service account ID." })), + "changes_requested": Schema.optionalKey( + Schema.Struct({ + "role": Schema.optionalKey( + Schema.String.annotate({ "description": "The role of the service account. Is either `owner` or `member`." }) + ) + }).annotate({ "description": "The payload used to updated the service account." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "service_account.deleted": Schema.optionalKey( + Schema.Struct({ "id": Schema.optionalKey(Schema.String.annotate({ "description": "The service account ID." })) }) + .annotate({ "description": "The details for events with this `type`." }) + ), + "user.added": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The user ID." })), + "data": Schema.optionalKey( + Schema.Struct({ + "role": Schema.optionalKey( + Schema.String.annotate({ "description": "The role of the user. Is either `owner` or `member`." }) + ) + }).annotate({ "description": "The payload used to add the user to the project." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "user.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The project ID." })), + "changes_requested": Schema.optionalKey( + Schema.Struct({ + "role": Schema.optionalKey( + Schema.String.annotate({ "description": "The role of the user. Is either `owner` or `member`." }) + ) + }).annotate({ "description": "The payload used to update the user." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "user.deleted": Schema.optionalKey( + Schema.Struct({ "id": Schema.optionalKey(Schema.String.annotate({ "description": "The user ID." })) }).annotate({ + "description": "The details for events with this `type`." + }) + ), + "certificate.created": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The certificate ID." })), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the certificate." })) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "certificate.updated": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The certificate ID." })), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the certificate." })) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "certificate.deleted": Schema.optionalKey( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The certificate ID." })), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the certificate." })), + "certificate": Schema.optionalKey( + Schema.String.annotate({ "description": "The certificate content in PEM format." }) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "certificates.activated": Schema.optionalKey( + Schema.Struct({ + "certificates": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The certificate ID." })), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the certificate." })) + }) + ) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ), + "certificates.deactivated": Schema.optionalKey( + Schema.Struct({ + "certificates": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The certificate ID." })), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the certificate." })) + }) + ) + ) + }).annotate({ "description": "The details for events with this `type`." }) + ) +}).annotate({ "description": "A log of a user action or configuration change within this organization." }) +export type CreateChatCompletionResponse = { + readonly "id": string + readonly "choices": ReadonlyArray< + { + readonly "finish_reason": "stop" | "length" | "tool_calls" | "content_filter" | "function_call" + readonly "index": number + readonly "message": ChatCompletionResponseMessage + readonly "logprobs": { + readonly "content": ReadonlyArray | null + readonly "refusal": ReadonlyArray | null + } | null + } + > + readonly "created": number + readonly "model": string + readonly "service_tier"?: ServiceTier + readonly "system_fingerprint"?: string + readonly "object": "chat.completion" + readonly "usage"?: CompletionUsage +} +export const CreateChatCompletionResponse = Schema.Struct({ + "id": Schema.String.annotate({ "description": "A unique identifier for the chat completion." }), + "choices": Schema.Array(Schema.Struct({ + "finish_reason": Schema.Literals(["stop", "length", "tool_calls", "content_filter", "function_call"]).annotate({ + "description": + "The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop sequence,\n`length` if the maximum number of tokens specified in the request was reached,\n`content_filter` if content was omitted due to a flag from our content filters,\n`tool_calls` if the model called a tool, or `function_call` (deprecated) if the model called a function.\n" + }), + "index": Schema.Number.annotate({ "description": "The index of the choice in the list of choices." }).check( + Schema.isInt() + ), + "message": ChatCompletionResponseMessage, + "logprobs": Schema.Union([ + Schema.Struct({ + "content": Schema.Union([ + Schema.Array(ChatCompletionTokenLogprob).annotate({ + "description": "A list of message content tokens with log probability information." + }), + Schema.Null + ]), + "refusal": Schema.Union([ + Schema.Array(ChatCompletionTokenLogprob).annotate({ + "description": "A list of message refusal tokens with log probability information." + }), + Schema.Null + ]) + }).annotate({ "description": "Log probability information for the choice." }), + Schema.Null + ]) + })).annotate({ "description": "A list of chat completion choices. Can be more than one if `n` is greater than 1." }), + "created": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) of when the chat completion was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "model": Schema.String.annotate({ "description": "The model used for the chat completion." }), + "service_tier": Schema.optionalKey(ServiceTier), + "system_fingerprint": Schema.optionalKey( + Schema.String.annotate({ + "description": + "This fingerprint represents the backend configuration that the model runs with.\n\nCan be used in conjunction with the `seed` request parameter to understand when backend changes have been made that might impact determinism.\n" + }) + ), + "object": Schema.Literal("chat.completion").annotate({ + "description": "The object type, which is always `chat.completion`." + }), + "usage": Schema.optionalKey(CompletionUsage) +}).annotate({ "description": "Represents a chat completion response returned by model, based on the provided input." }) +export type ChatCompletionRequestMessage = + | ChatCompletionRequestDeveloperMessage + | ChatCompletionRequestSystemMessage + | ChatCompletionRequestUserMessage + | ChatCompletionRequestAssistantMessage + | ChatCompletionRequestToolMessage + | ChatCompletionRequestFunctionMessage +export const ChatCompletionRequestMessage = Schema.Union([ + ChatCompletionRequestDeveloperMessage, + ChatCompletionRequestSystemMessage, + ChatCompletionRequestUserMessage, + ChatCompletionRequestAssistantMessage, + ChatCompletionRequestToolMessage, + ChatCompletionRequestFunctionMessage +], { mode: "oneOf" }) +export type RunStepObject = { + readonly "id": string + readonly "object": "thread.run.step" + readonly "created_at": number + readonly "assistant_id": string + readonly "thread_id": string + readonly "run_id": string + readonly "type": "message_creation" | "tool_calls" + readonly "status": "in_progress" | "cancelled" | "failed" | "completed" | "expired" + readonly "step_details": { + readonly "type": "message_creation" + readonly "message_creation": { readonly "message_id": string } + } | { + readonly "type": "tool_calls" + readonly "tool_calls": ReadonlyArray< + | RunStepDetailsToolCallsCodeObject + | RunStepDetailsToolCallsFileSearchObject + | RunStepDetailsToolCallsFunctionObject + > + } + readonly "last_error": { readonly "code": "server_error" | "rate_limit_exceeded"; readonly "message": string } | null + readonly "expired_at": number | null + readonly "cancelled_at": number | null + readonly "failed_at": number | null + readonly "completed_at": number | null + readonly "metadata": Metadata + readonly "usage": RunStepCompletionUsage +} +export const RunStepObject = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The identifier of the run step, which can be referenced in API endpoints." + }), + "object": Schema.Literal("thread.run.step").annotate({ + "description": "The object type, which is always `thread.run.step`." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the run step was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "assistant_id": Schema.String.annotate({ + "description": "The ID of the [assistant](/docs/api-reference/assistants) associated with the run step." + }), + "thread_id": Schema.String.annotate({ + "description": "The ID of the [thread](/docs/api-reference/threads) that was run." + }), + "run_id": Schema.String.annotate({ + "description": "The ID of the [run](/docs/api-reference/runs) that this run step is a part of." + }), + "type": Schema.Literals(["message_creation", "tool_calls"]).annotate({ + "description": "The type of run step, which can be either `message_creation` or `tool_calls`." + }), + "status": Schema.Literals(["in_progress", "cancelled", "failed", "completed", "expired"]).annotate({ + "description": + "The status of the run step, which can be either `in_progress`, `cancelled`, `failed`, `completed`, or `expired`." + }), + "step_details": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("message_creation").annotate({ "description": "Always `message_creation`." }), + "message_creation": Schema.Struct({ + "message_id": Schema.String.annotate({ + "description": "The ID of the message that was created by this run step." + }) + }) + }).annotate({ "title": "Message creation", "description": "The details of the run step." }), + Schema.Struct({ + "type": Schema.Literal("tool_calls").annotate({ "description": "Always `tool_calls`." }), + "tool_calls": Schema.Array( + Schema.Union([ + RunStepDetailsToolCallsCodeObject, + RunStepDetailsToolCallsFileSearchObject, + RunStepDetailsToolCallsFunctionObject + ], { mode: "oneOf" }) + ).annotate({ + "description": + "An array of tool calls the run step was involved in. These can be associated with one of three types of tools: `code_interpreter`, `file_search`, or `function`.\n" + }) + }).annotate({ "title": "Tool calls", "description": "The details of the run step." }) + ], { mode: "oneOf" }), + "last_error": Schema.Union([ + Schema.Struct({ + "code": Schema.Literals(["server_error", "rate_limit_exceeded"]).annotate({ + "description": "One of `server_error` or `rate_limit_exceeded`." + }), + "message": Schema.String.annotate({ "description": "A human-readable description of the error." }) + }).annotate({ + "description": "The last error associated with this run step. Will be `null` if there are no errors." + }), + Schema.Null + ]), + "expired_at": Schema.Union([ + Schema.Number.annotate({ + "description": + "The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "cancelled_at": Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the run step was cancelled.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "failed_at": Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the run step failed.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "completed_at": Schema.Union([ + Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the run step completed.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "metadata": Metadata, + "usage": RunStepCompletionUsage +}).annotate({ "title": "Run steps", "description": "Represents a step in execution of a run.\n" }) +export type ListMessagesResponse = { + readonly "object": string + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean + readonly [x: string]: unknown +} +export const ListMessagesResponse = Schema.StructWithRest( + Schema.Struct({ + "object": Schema.String, + "data": Schema.Array(MessageObject), + "first_id": Schema.String, + "last_id": Schema.String, + "has_more": Schema.Boolean + }), + [Schema.Record(Schema.String, Schema.Json)] +) +export type MessageStreamEvent = + | { readonly "event": "thread.message.created"; readonly "data": MessageObject } + | { readonly "event": "thread.message.in_progress"; readonly "data": MessageObject } + | { readonly "event": "thread.message.delta"; readonly "data": MessageDeltaObject } + | { readonly "event": "thread.message.completed"; readonly "data": MessageObject } + | { readonly "event": "thread.message.incomplete"; readonly "data": MessageObject } +export const MessageStreamEvent = Schema.Union([ + Schema.Struct({ "event": Schema.Literal("thread.message.created"), "data": MessageObject }).annotate({ + "description": "Occurs when a [message](/docs/api-reference/messages/object) is created." + }), + Schema.Struct({ "event": Schema.Literal("thread.message.in_progress"), "data": MessageObject }).annotate({ + "description": "Occurs when a [message](/docs/api-reference/messages/object) moves to an `in_progress` state." + }), + Schema.Struct({ "event": Schema.Literal("thread.message.delta"), "data": MessageDeltaObject }).annotate({ + "description": "Occurs when parts of a [Message](/docs/api-reference/messages/object) are being streamed." + }), + Schema.Struct({ "event": Schema.Literal("thread.message.completed"), "data": MessageObject }).annotate({ + "description": "Occurs when a [message](/docs/api-reference/messages/object) is completed." + }), + Schema.Struct({ "event": Schema.Literal("thread.message.incomplete"), "data": MessageObject }).annotate({ + "description": "Occurs when a [message](/docs/api-reference/messages/object) ends before it is completed." + }) +], { mode: "oneOf" }) +export type RealtimeBetaResponse = { + readonly "id"?: string + readonly "object"?: "realtime.response" + readonly "status"?: "completed" | "cancelled" | "failed" | "incomplete" | "in_progress" + readonly "status_details"?: { + readonly "type"?: "completed" | "cancelled" | "failed" | "incomplete" + readonly "reason"?: "turn_detected" | "client_cancelled" | "max_output_tokens" | "content_filter" + readonly "error"?: { readonly "type"?: string; readonly "code"?: string } + } + readonly "output"?: ReadonlyArray + readonly "metadata"?: Metadata + readonly "usage"?: { + readonly "total_tokens"?: number + readonly "input_tokens"?: number + readonly "output_tokens"?: number + readonly "input_token_details"?: { + readonly "cached_tokens"?: number + readonly "text_tokens"?: number + readonly "image_tokens"?: number + readonly "audio_tokens"?: number + readonly "cached_tokens_details"?: { + readonly "text_tokens"?: number + readonly "image_tokens"?: number + readonly "audio_tokens"?: number + } + } + readonly "output_token_details"?: { readonly "text_tokens"?: number; readonly "audio_tokens"?: number } + } + readonly "conversation_id"?: string + readonly "voice"?: + | string + | "alloy" + | "ash" + | "ballad" + | "coral" + | "echo" + | "sage" + | "shimmer" + | "verse" + | "marin" + | "cedar" + readonly "modalities"?: ReadonlyArray<"text" | "audio"> + readonly "output_audio_format"?: "pcm16" | "g711_ulaw" | "g711_alaw" + readonly "temperature"?: number + readonly "max_output_tokens"?: number | "inf" +} +export const RealtimeBetaResponse = Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The unique ID of the response." })), + "object": Schema.optionalKey( + Schema.Literal("realtime.response").annotate({ "description": "The object type, must be `realtime.response`." }) + ), + "status": Schema.optionalKey( + Schema.Literals(["completed", "cancelled", "failed", "incomplete", "in_progress"]).annotate({ + "description": + "The final status of the response (`completed`, `cancelled`, `failed`, or \n`incomplete`, `in_progress`).\n" + }) + ), + "status_details": Schema.optionalKey( + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literals(["completed", "cancelled", "failed", "incomplete"]).annotate({ + "description": + "The type of error that caused the response to fail, corresponding \nwith the `status` field (`completed`, `cancelled`, `incomplete`, \n`failed`).\n" + }) + ), + "reason": Schema.optionalKey( + Schema.Literals(["turn_detected", "client_cancelled", "max_output_tokens", "content_filter"]).annotate({ + "description": + "The reason the Response did not complete. For a `cancelled` Response, \none of `turn_detected` (the server VAD detected a new start of speech) \nor `client_cancelled` (the client sent a cancel event). For an \n`incomplete` Response, one of `max_output_tokens` or `content_filter` \n(the server-side safety filter activated and cut off the response).\n" + }) + ), + "error": Schema.optionalKey( + Schema.Struct({ + "type": Schema.optionalKey(Schema.String.annotate({ "description": "The type of error." })), + "code": Schema.optionalKey(Schema.String.annotate({ "description": "Error code, if any." })) + }).annotate({ + "description": + "A description of the error that caused the response to fail, \npopulated when the `status` is `failed`.\n" + }) + ) + }).annotate({ "description": "Additional details about the status." }) + ), + "output": Schema.optionalKey( + Schema.Array(RealtimeConversationItem).annotate({ + "description": "The list of output items generated by the response." + }) + ), + "metadata": Schema.optionalKey(Metadata), + "usage": Schema.optionalKey( + Schema.Struct({ + "total_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The total number of tokens in the Response including input and output \ntext and audio tokens.\n" + }).check(Schema.isInt()) + ), + "input_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of input tokens used in the Response, including text and \naudio tokens.\n" + }).check(Schema.isInt()) + ), + "output_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of output tokens sent in the Response, including text and \naudio tokens.\n" + }).check(Schema.isInt()) + ), + "input_token_details": Schema.optionalKey( + Schema.Struct({ + "cached_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of cached tokens used as input for the Response." }) + .check(Schema.isInt()) + ), + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of text tokens used as input for the Response." }) + .check(Schema.isInt()) + ), + "image_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of image tokens used as input for the Response." }) + .check(Schema.isInt()) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of audio tokens used as input for the Response." }) + .check(Schema.isInt()) + ), + "cached_tokens_details": Schema.optionalKey( + Schema.Struct({ + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of cached text tokens used as input for the Response." + }).check(Schema.isInt()) + ), + "image_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of cached image tokens used as input for the Response." + }).check(Schema.isInt()) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of cached audio tokens used as input for the Response." + }).check(Schema.isInt()) + ) + }).annotate({ "description": "Details about the cached tokens used as input for the Response." }) + ) + }).annotate({ "description": "Details about the input tokens used in the Response." }) + ), + "output_token_details": Schema.optionalKey( + Schema.Struct({ + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of text tokens used in the Response." }).check( + Schema.isInt() + ) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of audio tokens used in the Response." }).check( + Schema.isInt() + ) + ) + }).annotate({ "description": "Details about the output tokens used in the Response." }) + ) + }).annotate({ + "description": + "Usage statistics for the Response, this will correspond to billing. A \nRealtime API session will maintain a conversation context and append new \nItems to the Conversation, thus output from previous turns (text and \naudio tokens) will become the input for later turns.\n" + }) + ), + "conversation_id": Schema.optionalKey(Schema.String.annotate({ + "description": + "Which conversation the response is added to, determined by the `conversation`\nfield in the `response.create` event. If `auto`, the response will be added to\nthe default conversation and the value of `conversation_id` will be an id like\n`conv_1234`. If `none`, the response will not be added to any conversation and\nthe value of `conversation_id` will be `null`. If responses are being triggered\nby server VAD, the response will be added to the default conversation, thus\nthe `conversation_id` will be an id like `conv_1234`.\n" + })), + "voice": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals(["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse", "marin", "cedar"]) + ]).annotate({ + "description": + "The voice the model used to respond.\nCurrent voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, and `verse`.\n" + }) + ), + "modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": + "The set of modalities the model used to respond. If there are multiple modalities,\nthe model will pick one, for example if `modalities` is `[\"text\", \"audio\"]`, the model\ncould be responding in either text or audio.\n" + }) + ), + "output_audio_format": Schema.optionalKey( + Schema.Literals(["pcm16", "g711_ulaw", "g711_alaw"]).annotate({ + "description": "The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n" + }).check(Schema.isFinite()) + ), + "max_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls, that was used in this response.\n" + }) + ) +}).annotate({ "description": "The response resource." }) +export type RealtimeBetaResponseCreateParams = { + readonly "modalities"?: ReadonlyArray<"text" | "audio"> + readonly "instructions"?: string + readonly "voice"?: VoiceIdsShared | { readonly "id": string } + readonly "output_audio_format"?: "pcm16" | "g711_ulaw" | "g711_alaw" + readonly "tools"?: ReadonlyArray< + { + readonly "type"?: "function" + readonly "name"?: string + readonly "description"?: string + readonly "parameters"?: {} + } + > + readonly "tool_choice"?: ToolChoiceOptions | ToolChoiceFunction | ToolChoiceMCP + readonly "temperature"?: number + readonly "max_output_tokens"?: number | "inf" + readonly "conversation"?: string | "auto" | "none" + readonly "metadata"?: Metadata + readonly "prompt"?: Prompt + readonly "input"?: ReadonlyArray +} +export const RealtimeBetaResponseCreateParams = Schema.Struct({ + "modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": "The set of modalities the model can respond with. To disable audio,\nset this to [\"text\"].\n" + }) + ), + "instructions": Schema.optionalKey(Schema.String.annotate({ + "description": + "The default system instructions (i.e. system message) prepended to model \ncalls. This field allows the client to guide the model on desired \nresponses. The model can be instructed on response content and format, \n(e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good \nresponses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion \ninto your voice\", \"laugh frequently\"). The instructions are not guaranteed \nto be followed by the model, but they provide guidance to the model on the \ndesired behavior.\n\nNote that the server sets default instructions which will be used if this \nfield is not set and are visible in the `session.created` event at the \nstart of the session.\n" + })), + "voice": Schema.optionalKey( + Schema.Union([ + VoiceIdsShared, + Schema.Struct({ "id": Schema.String.annotate({ "description": "The custom voice ID, e.g. `voice_1234`." }) }) + .annotate({ "description": "Custom voice reference." }) + ]).annotate({ + "title": "Voice", + "description": + "The voice the model uses to respond. Supported built-in voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, `verse`,\n`marin`, and `cedar`. You may also provide a custom voice object with an\n`id`, for example `{ \"id\": \"voice_1234\" }`. Voice cannot be changed during\nthe session once the model has responded with audio at least once.\n" + }) + ), + "output_audio_format": Schema.optionalKey( + Schema.Literals(["pcm16", "g711_ulaw", "g711_alaw"]).annotate({ + "description": "The format of output audio. Options are `pcm16`, `g711_ulaw`, or `g711_alaw`.\n" + }) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("function").annotate({ "description": "The type of the tool, i.e. `function`." }) + ), + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the function." })), + "description": Schema.optionalKey( + Schema.String.annotate({ + "description": + "The description of the function, including guidance on when and how \nto call it, and guidance about what to tell the user when calling \n(if anything).\n" + }) + ), + "parameters": Schema.optionalKey( + Schema.Struct({}).annotate({ "description": "Parameters of the function in JSON Schema." }) + ) + })).annotate({ "description": "Tools (functions) available to the model." }) + ), + "tool_choice": Schema.optionalKey( + Schema.Union([ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], { mode: "oneOf" }).annotate({ + "description": + "How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n" + }) + ), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Sampling temperature for the model, limited to [0.6, 1.2]. Defaults to 0.8.\n" + }).check(Schema.isFinite()) + ), + "max_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n" + }) + ), + "conversation": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Literals(["auto", "none"])], { mode: "oneOf" }).annotate({ + "description": + "Controls which conversation the response is added to. Currently supports\n`auto` and `none`, with `auto` as the default value. The `auto` value\nmeans that the contents of the response will be added to the default\nconversation. Set this to `none` to create an out-of-band response which \nwill not add items to default conversation.\n" + }) + ), + "metadata": Schema.optionalKey(Metadata), + "prompt": Schema.optionalKey(Prompt), + "input": Schema.optionalKey( + Schema.Array(RealtimeConversationItem).annotate({ + "description": + "Input items to include in the prompt for the model. Using this field\ncreates a new context for this Response instead of using the default\nconversation. An empty array `[]` will clear the context for this Response.\nNote that this can include references to items from the default conversation.\n" + }) + ) +}).annotate({ "description": "Create a new Realtime response with these parameters" }) +export type RealtimeClientEventConversationItemCreate = { + readonly "event_id"?: string + readonly "type": "conversation.item.create" + readonly "previous_item_id"?: string + readonly "item": RealtimeConversationItem +} +export const RealtimeClientEventConversationItemCreate = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("conversation.item.create").annotate({ + "description": "The event type, must be `conversation.item.create`." + }), + "previous_item_id": Schema.optionalKey(Schema.String.annotate({ + "description": + "The ID of the preceding item after which the new item will be inserted. If not set, the new item will be appended to the end of the conversation.\n\nIf set to `root`, the new item will be added to the beginning of the conversation.\n\nIf set to an existing ID, it allows an item to be inserted mid-conversation. If the ID cannot be found, an error will be returned and the item will not be added.\n" + })), + "item": RealtimeConversationItem +}).annotate({ + "description": + "Add a new Item to the Conversation's context, including messages, function \ncalls, and function call responses. This event can be used both to populate a \n\"history\" of the conversation and to add new items mid-stream, but has the \ncurrent limitation that it cannot populate assistant audio messages.\n\nIf successful, the server will respond with a `conversation.item.created` \nevent, otherwise an `error` event will be sent.\n" +}) +export type RealtimeResponse = { + readonly "id"?: string + readonly "object"?: "realtime.response" + readonly "status"?: "completed" | "cancelled" | "failed" | "incomplete" | "in_progress" + readonly "status_details"?: { + readonly "type"?: "completed" | "cancelled" | "failed" | "incomplete" + readonly "reason"?: "turn_detected" | "client_cancelled" | "max_output_tokens" | "content_filter" + readonly "error"?: { readonly "type"?: string; readonly "code"?: string } + } + readonly "output"?: ReadonlyArray + readonly "metadata"?: Metadata + readonly "audio"?: { + readonly "output"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "voice"?: + | string + | "alloy" + | "ash" + | "ballad" + | "coral" + | "echo" + | "sage" + | "shimmer" + | "verse" + | "marin" + | "cedar" + } + } + readonly "usage"?: { + readonly "total_tokens"?: number + readonly "input_tokens"?: number + readonly "output_tokens"?: number + readonly "input_token_details"?: { + readonly "cached_tokens"?: number + readonly "text_tokens"?: number + readonly "image_tokens"?: number + readonly "audio_tokens"?: number + readonly "cached_tokens_details"?: { + readonly "text_tokens"?: number + readonly "image_tokens"?: number + readonly "audio_tokens"?: number + } + } + readonly "output_token_details"?: { readonly "text_tokens"?: number; readonly "audio_tokens"?: number } + } + readonly "conversation_id"?: string + readonly "output_modalities"?: ReadonlyArray<"text" | "audio"> + readonly "max_output_tokens"?: number | "inf" +} +export const RealtimeResponse = Schema.Struct({ + "id": Schema.optionalKey( + Schema.String.annotate({ "description": "The unique ID of the response, will look like `resp_1234`." }) + ), + "object": Schema.optionalKey( + Schema.Literal("realtime.response").annotate({ "description": "The object type, must be `realtime.response`." }) + ), + "status": Schema.optionalKey( + Schema.Literals(["completed", "cancelled", "failed", "incomplete", "in_progress"]).annotate({ + "description": + "The final status of the response (`completed`, `cancelled`, `failed`, or \n`incomplete`, `in_progress`).\n" + }) + ), + "status_details": Schema.optionalKey( + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literals(["completed", "cancelled", "failed", "incomplete"]).annotate({ + "description": + "The type of error that caused the response to fail, corresponding \nwith the `status` field (`completed`, `cancelled`, `incomplete`, \n`failed`).\n" + }) + ), + "reason": Schema.optionalKey( + Schema.Literals(["turn_detected", "client_cancelled", "max_output_tokens", "content_filter"]).annotate({ + "description": + "The reason the Response did not complete. For a `cancelled` Response, one of `turn_detected` (the server VAD detected a new start of speech) or `client_cancelled` (the client sent a cancel event). For an `incomplete` Response, one of `max_output_tokens` or `content_filter` (the server-side safety filter activated and cut off the response).\n" + }) + ), + "error": Schema.optionalKey( + Schema.Struct({ + "type": Schema.optionalKey(Schema.String.annotate({ "description": "The type of error." })), + "code": Schema.optionalKey(Schema.String.annotate({ "description": "Error code, if any." })) + }).annotate({ + "description": + "A description of the error that caused the response to fail, \npopulated when the `status` is `failed`.\n" + }) + ) + }).annotate({ "description": "Additional details about the status." }) + ), + "output": Schema.optionalKey( + Schema.Array(RealtimeConversationItem).annotate({ + "description": "The list of output items generated by the response." + }) + ), + "metadata": Schema.optionalKey(Metadata), + "audio": Schema.optionalKey( + Schema.Struct({ + "output": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the output audio." }) + ), + "voice": Schema.optionalKey( + Schema.Union([ + Schema.String, + Schema.Literals(["alloy", "ash", "ballad", "coral", "echo", "sage", "shimmer", "verse", "marin", "cedar"]) + ]).annotate({ + "description": + "The voice the model uses to respond. Voice cannot be changed during the\nsession once the model has responded with audio at least once. Current\nvoice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`,\n`shimmer`, `verse`, `marin`, and `cedar`. We recommend `marin` and `cedar` for\nbest quality.\n" + }) + ) + })) + }).annotate({ "description": "Configuration for audio output." }) + ), + "usage": Schema.optionalKey( + Schema.Struct({ + "total_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The total number of tokens in the Response including input and output \ntext and audio tokens.\n" + }).check(Schema.isInt()) + ), + "input_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of input tokens used in the Response, including text and \naudio tokens.\n" + }).check(Schema.isInt()) + ), + "output_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of output tokens sent in the Response, including text and \naudio tokens.\n" + }).check(Schema.isInt()) + ), + "input_token_details": Schema.optionalKey( + Schema.Struct({ + "cached_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of cached tokens used as input for the Response." }) + .check(Schema.isInt()) + ), + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of text tokens used as input for the Response." }) + .check(Schema.isInt()) + ), + "image_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of image tokens used as input for the Response." }) + .check(Schema.isInt()) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of audio tokens used as input for the Response." }) + .check(Schema.isInt()) + ), + "cached_tokens_details": Schema.optionalKey( + Schema.Struct({ + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of cached text tokens used as input for the Response." + }).check(Schema.isInt()) + ), + "image_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of cached image tokens used as input for the Response." + }).check(Schema.isInt()) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The number of cached audio tokens used as input for the Response." + }).check(Schema.isInt()) + ) + }).annotate({ "description": "Details about the cached tokens used as input for the Response." }) + ) + }).annotate({ + "description": + "Details about the input tokens used in the Response. Cached tokens are tokens from previous turns in the conversation that are included as context for the current response. Cached tokens here are counted as a subset of input tokens, meaning input tokens will include cached and uncached tokens." + }) + ), + "output_token_details": Schema.optionalKey( + Schema.Struct({ + "text_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of text tokens used in the Response." }).check( + Schema.isInt() + ) + ), + "audio_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The number of audio tokens used in the Response." }).check( + Schema.isInt() + ) + ) + }).annotate({ "description": "Details about the output tokens used in the Response." }) + ) + }).annotate({ + "description": + "Usage statistics for the Response, this will correspond to billing. A \nRealtime API session will maintain a conversation context and append new \nItems to the Conversation, thus output from previous turns (text and \naudio tokens) will become the input for later turns.\n" + }) + ), + "conversation_id": Schema.optionalKey(Schema.String.annotate({ + "description": + "Which conversation the response is added to, determined by the `conversation`\nfield in the `response.create` event. If `auto`, the response will be added to\nthe default conversation and the value of `conversation_id` will be an id like\n`conv_1234`. If `none`, the response will not be added to any conversation and\nthe value of `conversation_id` will be `null`. If responses are being triggered\nautomatically by VAD the response will be added to the default conversation\n" + })), + "output_modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": + "The set of modalities the model used to respond, currently the only possible values are\n`[\\\"audio\\\"]`, `[\\\"text\\\"]`. Audio output always include a text transcript. Setting the\noutput to mode `text` will disable audio output from the model.\n" + }) + ), + "max_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls, that was used in this response.\n" + }) + ) +}).annotate({ "description": "The response resource." }) +export type RealtimeResponseCreateParams = { + readonly "output_modalities"?: ReadonlyArray<"text" | "audio"> + readonly "instructions"?: string + readonly "audio"?: { + readonly "output"?: { + readonly "format"?: { readonly "type"?: "audio/pcm"; readonly "rate"?: 24000 } | { + readonly "type"?: "audio/pcmu" + } | { readonly "type"?: "audio/pcma" } + readonly "voice"?: VoiceIdsShared | { readonly "id": string } + } + } + readonly "tools"?: ReadonlyArray + readonly "tool_choice"?: ToolChoiceOptions | ToolChoiceFunction | ToolChoiceMCP + readonly "parallel_tool_calls"?: boolean + readonly "reasoning"?: RealtimeReasoning + readonly "max_output_tokens"?: number | "inf" + readonly "conversation"?: string | "auto" | "none" + readonly "metadata"?: Metadata + readonly "prompt"?: Prompt + readonly "input"?: ReadonlyArray +} +export const RealtimeResponseCreateParams = Schema.Struct({ + "output_modalities": Schema.optionalKey( + Schema.Array(Schema.Literals(["text", "audio"])).annotate({ + "description": + "The set of modalities the model used to respond, currently the only possible values are\n`[\\\"audio\\\"]`, `[\\\"text\\\"]`. Audio output always include a text transcript. Setting the\noutput to mode `text` will disable audio output from the model.\n" + }) + ), + "instructions": Schema.optionalKey(Schema.String.annotate({ + "description": + "The default system instructions (i.e. system message) prepended to model calls. This field allows the client to guide the model on desired responses. The model can be instructed on response content and format, (e.g. \"be extremely succinct\", \"act friendly\", \"here are examples of good responses\") and on audio behavior (e.g. \"talk quickly\", \"inject emotion into your voice\", \"laugh frequently\"). The instructions are not guaranteed to be followed by the model, but they provide guidance to the model on the desired behavior.\nNote that the server sets default instructions which will be used if this field is not set and are visible in the `session.created` event at the start of the session.\n" + })), + "audio": Schema.optionalKey( + Schema.Struct({ + "output": Schema.optionalKey(Schema.Struct({ + "format": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcm").annotate({ "description": "The audio format. Always `audio/pcm`." }) + ), + "rate": Schema.optionalKey( + Schema.Literal(24000).annotate({ "description": "The sample rate of the audio. Always `24000`." }) + ) + }).annotate({ + "title": "PCM audio format", + "description": "The PCM audio format. Only a 24kHz sample rate is supported." + }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcmu").annotate({ "description": "The audio format. Always `audio/pcmu`." }) + ) + }).annotate({ "title": "PCMU audio format", "description": "The G.711 μ-law format." }), + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("audio/pcma").annotate({ "description": "The audio format. Always `audio/pcma`." }) + ) + }).annotate({ "title": "PCMA audio format", "description": "The G.711 A-law format." }) + ]).annotate({ "description": "The format of the output audio." }) + ), + "voice": Schema.optionalKey( + Schema.Union([ + VoiceIdsShared, + Schema.Struct({ + "id": Schema.String.annotate({ "description": "The custom voice ID, e.g. `voice_1234`." }) + }).annotate({ "description": "Custom voice reference." }) + ]).annotate({ + "title": "Voice", + "description": + "The voice the model uses to respond. Supported built-in voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, `verse`,\n`marin`, and `cedar`. You may also provide a custom voice object with\nan `id`, for example `{ \"id\": \"voice_1234\" }`. Voice cannot be changed\nduring the session once the model has responded with audio at least once.\nWe recommend `marin` and `cedar` for best quality.\n" + }) + ) + })) + }).annotate({ "description": "Configuration for audio input and output." }) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Union([RealtimeFunctionTool, MCPTool], { mode: "oneOf" })).annotate({ + "description": "Tools available to the model." + }) + ), + "tool_choice": Schema.optionalKey( + Schema.Union([ToolChoiceOptions, ToolChoiceFunction, ToolChoiceMCP], { mode: "oneOf" }).annotate({ + "description": + "How the model chooses tools. Provide one of the string modes or force a specific\nfunction/MCP tool.\n" + }) + ), + "parallel_tool_calls": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": + "Whether the model may call multiple tools in parallel. Only supported by\nreasoning Realtime models such as `gpt-realtime-2`.\n" + }) + ), + "reasoning": Schema.optionalKey(RealtimeReasoning), + "max_output_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Literal("inf")], { mode: "oneOf" }).annotate({ + "description": + "Maximum number of output tokens for a single assistant response,\ninclusive of tool calls. Provide an integer between 1 and 4096 to\nlimit output tokens, or `inf` for the maximum available tokens for a\ngiven model. Defaults to `inf`.\n" + }) + ), + "conversation": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Literals(["auto", "none"])], { mode: "oneOf" }).annotate({ + "description": + "Controls which conversation the response is added to. Currently supports\n`auto` and `none`, with `auto` as the default value. The `auto` value\nmeans that the contents of the response will be added to the default\nconversation. Set this to `none` to create an out-of-band response which\nwill not add items to default conversation.\n" + }) + ), + "metadata": Schema.optionalKey(Metadata), + "prompt": Schema.optionalKey(Prompt), + "input": Schema.optionalKey( + Schema.Array(RealtimeConversationItem).annotate({ + "description": + "Input items to include in the prompt for the model. Using this field\ncreates a new context for this Response instead of using the default\nconversation. An empty array `[]` will clear the context for this Response.\nNote that this can include references to items that previously appeared in the session\nusing their id.\n" + }) + ) +}).annotate({ "description": "Create a new Realtime response with these parameters" }) +export type RealtimeServerEventConversationItemAdded = { + readonly "event_id": string + readonly "type": "conversation.item.added" + readonly "previous_item_id"?: string | null + readonly "item": RealtimeConversationItem +} +export const RealtimeServerEventConversationItemAdded = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.added").annotate({ + "description": "The event type, must be `conversation.item.added`." + }), + "previous_item_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The ID of the item that precedes this one, if any. This is used to\nmaintain ordering when items are inserted.\n" + }), + Schema.Null + ]) + ), + "item": RealtimeConversationItem +}).annotate({ + "description": + "Sent by the server when an Item is added to the default Conversation. This can happen in several cases:\n- When the client sends a `conversation.item.create` event.\n- When the input audio buffer is committed. In this case the item will be a user message containing the audio from the buffer.\n- When the model is generating a Response. In this case the `conversation.item.added` event will be sent when the model starts generating a specific Item, and thus it will not yet have any content (and `status` will be `in_progress`).\n\nThe event will include the full content of the Item (except when model is generating a Response) except for audio data, which can be retrieved separately with a `conversation.item.retrieve` event if necessary.\n" +}) +export type RealtimeServerEventConversationItemCreated = { + readonly "event_id": string + readonly "type": "conversation.item.created" + readonly "previous_item_id"?: string | null + readonly "item": RealtimeConversationItem +} +export const RealtimeServerEventConversationItemCreated = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.created").annotate({ + "description": "The event type, must be `conversation.item.created`." + }), + "previous_item_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The ID of the preceding item in the Conversation context, allows the\nclient to understand the order of the conversation. Can be `null` if the\nitem has no predecessor.\n" + }), + Schema.Null + ]) + ), + "item": RealtimeConversationItem +}).annotate({ + "description": + "Returned when a conversation item is created. There are several scenarios that produce this event:\n - The server is generating a Response, which if successful will produce\n either one or two Items, which will be of type `message`\n (role `assistant`) or type `function_call`.\n - The input audio buffer has been committed, either by the client or the\n server (in `server_vad` mode). The server will take the content of the\n input audio buffer and add it to a new user message Item.\n - The client has sent a `conversation.item.create` event to add a new Item\n to the Conversation.\n" +}) +export type RealtimeServerEventConversationItemDone = { + readonly "event_id": string + readonly "type": "conversation.item.done" + readonly "previous_item_id"?: string | null + readonly "item": RealtimeConversationItem +} +export const RealtimeServerEventConversationItemDone = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.done").annotate({ + "description": "The event type, must be `conversation.item.done`." + }), + "previous_item_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The ID of the item that precedes this one, if any. This is used to\nmaintain ordering when items are inserted.\n" + }), + Schema.Null + ]) + ), + "item": RealtimeConversationItem +}).annotate({ + "description": + "Returned when a conversation item is finalized.\n\nThe event will include the full content of the Item except for audio data, which can be retrieved separately with a `conversation.item.retrieve` event if needed.\n" +}) +export type RealtimeServerEventConversationItemRetrieved = { + readonly "event_id": string + readonly "type": "conversation.item.retrieved" + readonly "item": RealtimeConversationItem +} +export const RealtimeServerEventConversationItemRetrieved = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("conversation.item.retrieved").annotate({ + "description": "The event type, must be `conversation.item.retrieved`." + }), + "item": RealtimeConversationItem +}).annotate({ + "description": + "Returned when a conversation item is retrieved with `conversation.item.retrieve`. This is provided as a way to fetch the server's representation of an item, for example to get access to the post-processed audio data after noise cancellation and VAD. It includes the full content of the Item, including audio data.\n" +}) +export type RealtimeServerEventResponseOutputItemAdded = { + readonly "event_id": string + readonly "type": "response.output_item.added" + readonly "response_id": string + readonly "output_index": number + readonly "item": RealtimeConversationItem +} +export const RealtimeServerEventResponseOutputItemAdded = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.output_item.added").annotate({ + "description": "The event type, must be `response.output_item.added`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the Response to which the item belongs." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the Response." }).check( + Schema.isInt() + ), + "item": RealtimeConversationItem +}).annotate({ "description": "Returned when a new Item is created during Response generation." }) +export type RealtimeServerEventResponseOutputItemDone = { + readonly "event_id": string + readonly "type": "response.output_item.done" + readonly "response_id": string + readonly "output_index": number + readonly "item": RealtimeConversationItem +} +export const RealtimeServerEventResponseOutputItemDone = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.output_item.done").annotate({ + "description": "The event type, must be `response.output_item.done`." + }), + "response_id": Schema.String.annotate({ "description": "The ID of the Response to which the item belongs." }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item in the Response." }).check( + Schema.isInt() + ), + "item": RealtimeConversationItem +}).annotate({ + "description": + "Returned when an Item is done streaming. Also emitted when a Response is \ninterrupted, incomplete, or cancelled.\n" +}) +export type AssistantObject = { + readonly "id": string + readonly "object": "assistant" + readonly "created_at": number + readonly "name": string | null + readonly "description": string | null + readonly "model": string + readonly "instructions": string | null + readonly "tools": ReadonlyArray + readonly "tool_resources"?: { + readonly "code_interpreter"?: { readonly "file_ids"?: ReadonlyArray } + readonly "file_search"?: { readonly "vector_store_ids"?: ReadonlyArray } + } | null + readonly "metadata": Metadata + readonly "temperature"?: number | null + readonly "top_p"?: number | null + readonly "response_format"?: AssistantsApiResponseFormatOption | null +} +export const AssistantObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints." }), + "object": Schema.Literal("assistant").annotate({ "description": "The object type, which is always `assistant`." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the assistant was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "name": Schema.Union([ + Schema.String.annotate({ "description": "The name of the assistant. The maximum length is 256 characters.\n" }) + .check(Schema.isMaxLength(256)), + Schema.Null + ]), + "description": Schema.Union([ + Schema.String.annotate({ + "description": "The description of the assistant. The maximum length is 512 characters.\n" + }).check(Schema.isMaxLength(512)), + Schema.Null + ]), + "model": Schema.String.annotate({ + "description": + "ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models) for descriptions of them.\n" + }), + "instructions": Schema.Union([ + Schema.String.annotate({ + "description": "The system instructions that the assistant uses. The maximum length is 256,000 characters.\n" + }).check(Schema.isMaxLength(256000)), + Schema.Null + ]), + "tools": Schema.Array( + Schema.Union([AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction], { mode: "oneOf" }) + ).annotate({ + "description": + "A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n" + }).check(Schema.isMaxLength(128)), + "tool_resources": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "code_interpreter": Schema.optionalKey(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter`` tool. There can be a maximum of 20 files associated with the tool.\n" + }).check(Schema.isMaxLength(20)) + ) + })), + "file_search": Schema.optionalKey(Schema.Struct({ + "vector_store_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n" + }).check(Schema.isMaxLength(1)) + ) + })) + }).annotate({ + "description": + "A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + }), + Schema.Null + ])), + "metadata": Metadata, + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey(Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ])), + "response_format": Schema.optionalKey(Schema.Union([AssistantsApiResponseFormatOption, Schema.Null])) +}).annotate({ "title": "Assistant", "description": "Represents an `assistant` that can call the model and use tools." }) +export type CreateAssistantRequest = { + readonly "model": string | AssistantSupportedModels + readonly "name"?: string | null + readonly "description"?: string | null + readonly "instructions"?: string | null + readonly "reasoning_effort"?: ReasoningEffort + readonly "tools"?: ReadonlyArray + readonly "tool_resources"?: { + readonly "code_interpreter"?: { readonly "file_ids"?: ReadonlyArray } + readonly "file_search"?: { + readonly "vector_store_ids": ReadonlyArray + readonly "vector_stores"?: ReadonlyArray< + { + readonly "file_ids"?: ReadonlyArray + readonly "chunking_strategy"?: { readonly "type": "auto" } | { + readonly "type": "static" + readonly "static": { readonly "max_chunk_size_tokens": number; readonly "chunk_overlap_tokens": number } + } + readonly "metadata"?: Metadata + } + > + } | { + readonly "vector_stores": ReadonlyArray< + { + readonly "file_ids"?: ReadonlyArray + readonly "chunking_strategy"?: { readonly "type": "auto" } | { + readonly "type": "static" + readonly "static": { readonly "max_chunk_size_tokens": number; readonly "chunk_overlap_tokens": number } + } + readonly "metadata"?: Metadata + } + > + readonly "vector_store_ids"?: ReadonlyArray + } + } | null + readonly "metadata"?: Metadata + readonly "temperature"?: number | null + readonly "top_p"?: number | null + readonly "response_format"?: AssistantsApiResponseFormatOption | null +} +export const CreateAssistantRequest = Schema.Struct({ + "model": Schema.Union([Schema.String, AssistantSupportedModels]).annotate({ + "description": + "ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models) for descriptions of them.\n" + }), + "name": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The name of the assistant. The maximum length is 256 characters.\n" }) + .check(Schema.isMaxLength(256)), + Schema.Null + ]) + ), + "description": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "The description of the assistant. The maximum length is 512 characters.\n" + }).check(Schema.isMaxLength(512)), + Schema.Null + ]) + ), + "instructions": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "The system instructions that the assistant uses. The maximum length is 256,000 characters.\n" + }).check(Schema.isMaxLength(256000)), + Schema.Null + ]) + ), + "reasoning_effort": Schema.optionalKey(ReasoningEffort), + "tools": Schema.optionalKey( + Schema.Array( + Schema.Union([AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction], { mode: "oneOf" }) + ).annotate({ + "description": + "A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n" + }).check(Schema.isMaxLength(128)) + ), + "tool_resources": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "code_interpreter": Schema.optionalKey(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n" + }).check(Schema.isMaxLength(20)) + ) + })), + "file_search": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "vector_store_ids": Schema.Array(Schema.String).annotate({ + "description": + "The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n" + }).check(Schema.isMaxLength(1)), + "vector_stores": Schema.optionalKey( + Schema.Array(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs to add to the vector store. For vector stores created before Nov 2025, there can be a maximum of 10,000 files in a vector store. For vector stores created starting in Nov 2025, the limit is 100,000,000 files.\n" + }).check(Schema.isMaxLength(100000000)) + ), + "chunking_strategy": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": Schema.Literal("auto").annotate({ "description": "Always `auto`." }) }) + .annotate({ + "title": "Auto Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }), + Schema.Struct({ + "type": Schema.Literal("static").annotate({ "description": "Always `static`." }), + "static": Schema.Struct({ + "max_chunk_size_tokens": Schema.Number.annotate({ + "description": + "The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(100)).check( + Schema.isLessThanOrEqualTo(4096) + ), + "chunk_overlap_tokens": Schema.Number.annotate({ + "description": + "The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" + }).check(Schema.isInt()) + }) + }).annotate({ + "title": "Static Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }) + ], { mode: "oneOf" }) + ), + "metadata": Schema.optionalKey(Metadata) + })).annotate({ + "description": + "A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n" + }).check(Schema.isMaxLength(1)) + ) + }), + Schema.Struct({ + "vector_stores": Schema.Array(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs to add to the vector store. For vector stores created before Nov 2025, there can be a maximum of 10,000 files in a vector store. For vector stores created starting in Nov 2025, the limit is 100,000,000 files.\n" + }).check(Schema.isMaxLength(100000000)) + ), + "chunking_strategy": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ "type": Schema.Literal("auto").annotate({ "description": "Always `auto`." }) }) + .annotate({ + "title": "Auto Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }), + Schema.Struct({ + "type": Schema.Literal("static").annotate({ "description": "Always `static`." }), + "static": Schema.Struct({ + "max_chunk_size_tokens": Schema.Number.annotate({ + "description": + "The maximum number of tokens in each chunk. The default value is `800`. The minimum value is `100` and the maximum value is `4096`." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(100)).check( + Schema.isLessThanOrEqualTo(4096) + ), + "chunk_overlap_tokens": Schema.Number.annotate({ + "description": + "The number of tokens that overlap between chunks. The default value is `400`.\n\nNote that the overlap must not exceed half of `max_chunk_size_tokens`.\n" + }).check(Schema.isInt()) + }) + }).annotate({ + "title": "Static Chunking Strategy", + "description": + "The chunking strategy used to chunk the file(s). If not set, will use the `auto` strategy." + }) + ], { mode: "oneOf" }) + ), + "metadata": Schema.optionalKey(Metadata) + })).annotate({ + "description": + "A helper to create a [vector store](/docs/api-reference/vector-stores/object) with file_ids and attach it to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n" + }).check(Schema.isMaxLength(1)), + "vector_store_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "The [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n" + }).check(Schema.isMaxLength(1)) + ) + }) + ], { mode: "oneOf" })) + }).annotate({ + "description": + "A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + }), + Schema.Null + ])), + "metadata": Schema.optionalKey(Metadata), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey(Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ])), + "response_format": Schema.optionalKey(Schema.Union([AssistantsApiResponseFormatOption, Schema.Null])) +}) +export type CreateRunRequest = { + readonly "assistant_id": string + readonly "model"?: string | AssistantSupportedModels | null + readonly "reasoning_effort"?: ReasoningEffort + readonly "instructions"?: string | null + readonly "additional_instructions"?: string | null + readonly "additional_messages"?: ReadonlyArray< + { + readonly "role": "user" | "assistant" + readonly "content": + | string + | ReadonlyArray + readonly "attachments"?: + | ReadonlyArray< + { + readonly "file_id"?: string + readonly "tools"?: ReadonlyArray + } + > + | null + readonly "metadata"?: Metadata + } + > + readonly "tools"?: ReadonlyArray + readonly "metadata"?: Metadata + readonly "temperature"?: number + readonly "top_p"?: number + readonly "stream"?: boolean | null + readonly "max_prompt_tokens"?: number + readonly "max_completion_tokens"?: number + readonly "truncation_strategy"?: { + readonly "type": "auto" | "last_messages" + readonly "last_messages"?: number | null + } + readonly "tool_choice"?: "none" | "auto" | "required" | { + readonly "type": "function" | "code_interpreter" | "file_search" + readonly "function"?: { readonly "name": string } + } + readonly "parallel_tool_calls"?: ParallelToolCalls + readonly "response_format"?: AssistantsApiResponseFormatOption | null +} +export const CreateRunRequest = Schema.Struct({ + "assistant_id": Schema.String.annotate({ + "description": "The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run." + }), + "model": Schema.optionalKey( + Schema.Union([ + Schema.Union([Schema.String, AssistantSupportedModels]).annotate({ + "description": + "The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used." + }), + Schema.Null + ]) + ), + "reasoning_effort": Schema.optionalKey(ReasoningEffort), + "instructions": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Overrides the [instructions](/docs/api-reference/assistants/createAssistant) of the assistant. This is useful for modifying the behavior on a per-run basis." + }) + ), + "additional_instructions": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Appends additional instructions at the end of the instructions for the run. This is useful for modifying the behavior on a per-run basis without overriding other instructions." + }) + ), + "additional_messages": Schema.optionalKey(Schema.Union([ + Schema.Array(Schema.Struct({ + "role": Schema.Literals(["user", "assistant"]).annotate({ + "description": + "The role of the entity that is creating the message. Allowed values include:\n- `user`: Indicates the message is sent by an actual user and should be used in most cases to represent user-generated messages.\n- `assistant`: Indicates the message is generated by the assistant. Use this value to insert messages from the assistant into the conversation.\n" + }), + "content": Schema.Union([ + Schema.String.annotate({ "title": "Text content", "description": "The text contents of the message." }), + Schema.Array( + Schema.Union([MessageContentImageFileObject, MessageContentImageUrlObject, MessageRequestContentTextObject], { + mode: "oneOf" + }) + ).annotate({ + "title": "Array of content parts", + "description": + "An array of content parts with a defined type, each can be of type `text` or images can be passed with `image_url` or `image_file`. Image types are only supported on [Vision-compatible models](/docs/models)." + }).check(Schema.isMinLength(1)) + ], { mode: "oneOf" }), + "attachments": Schema.optionalKey(Schema.Union([ + Schema.Array(Schema.Struct({ + "file_id": Schema.optionalKey( + Schema.String.annotate({ "description": "The ID of the file to attach to the message." }) + ), + "tools": Schema.optionalKey( + Schema.Array(Schema.Union([AssistantToolsCode, AssistantToolsFileSearchTypeOnly], { mode: "oneOf" })) + .annotate({ "description": "The tools to add this file to." }) + ) + })).annotate({ + "description": "A list of files attached to the message, and the tools they should be added to." + }), + Schema.Null + ])), + "metadata": Schema.optionalKey(Metadata) + })).annotate({ "description": "Adds additional messages to the thread before creating the run." }) + ])), + "tools": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction], { mode: "oneOf" }) + ).check( + Schema.isMaxLength(20, { + "description": + "Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis." + }) + ) + ]) + ), + "metadata": Schema.optionalKey(Metadata), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(2)], { + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n" + }) + ) + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(1)], { + "description": + "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }) + ) + ]) + ), + "stream": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": + "If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" + }) + ), + "max_prompt_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(256)], { + "description": + "The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n" + }) + ) + ]) + ), + "max_completion_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(256)], { + "description": + "The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n" + }) + ) + ]) + ), + "truncation_strategy": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "type": Schema.Literals(["auto", "last_messages"]).annotate({ + "description": + "The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`." + }), + "last_messages": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The number of most recent messages from the thread when constructing the context for the run." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null + ]) + ) + }).annotate({ + "title": "Thread Truncation Controls", + "description": + "Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run." + }) + ])), + "tool_choice": Schema.optionalKey( + Schema.Union([ + Schema.Union([Schema.Literal("none"), Schema.Literal("auto"), Schema.Literal("required")]).annotate({ + "description": + "`none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n" + }), + Schema.Union([ + Schema.Struct({ + "type": Schema.Literals(["function", "code_interpreter", "file_search"]).annotate({ + "description": "The type of the tool. If type is `function`, the function name must be set" + }), + "function": Schema.optionalKey( + Schema.Struct({ "name": Schema.String.annotate({ "description": "The name of the function to call." }) }) + ) + }).annotate({ + "description": "Specifies a tool the model should use. Use to force the model to call a specific tool." + }) + ]) + ], { mode: "oneOf" }).annotate({ + "description": + "Controls which (if any) tool is called by the model.\n`none` means the model will not call any tools and instead generates a message.\n`auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools before responding to the user.\nSpecifying a particular tool like `{\"type\": \"file_search\"}` or `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n" + }) + ), + "parallel_tool_calls": Schema.optionalKey(ParallelToolCalls), + "response_format": Schema.optionalKey(Schema.Union([AssistantsApiResponseFormatOption, Schema.Null])) +}) +export type CreateThreadAndRunRequest = { + readonly "assistant_id": string + readonly "thread"?: CreateThreadRequest + readonly "model"?: + | string + | "gpt-5" + | "gpt-5-mini" + | "gpt-5-nano" + | "gpt-5-2025-08-07" + | "gpt-5-mini-2025-08-07" + | "gpt-5-nano-2025-08-07" + | "gpt-4.1" + | "gpt-4.1-mini" + | "gpt-4.1-nano" + | "gpt-4.1-2025-04-14" + | "gpt-4.1-mini-2025-04-14" + | "gpt-4.1-nano-2025-04-14" + | "gpt-4o" + | "gpt-4o-2024-11-20" + | "gpt-4o-2024-08-06" + | "gpt-4o-2024-05-13" + | "gpt-4o-mini" + | "gpt-4o-mini-2024-07-18" + | "gpt-4.5-preview" + | "gpt-4.5-preview-2025-02-27" + | "gpt-4-turbo" + | "gpt-4-turbo-2024-04-09" + | "gpt-4-0125-preview" + | "gpt-4-turbo-preview" + | "gpt-4-1106-preview" + | "gpt-4-vision-preview" + | "gpt-4" + | "gpt-4-0314" + | "gpt-4-0613" + | "gpt-4-32k" + | "gpt-4-32k-0314" + | "gpt-4-32k-0613" + | "gpt-3.5-turbo" + | "gpt-3.5-turbo-16k" + | "gpt-3.5-turbo-0613" + | "gpt-3.5-turbo-1106" + | "gpt-3.5-turbo-0125" + | "gpt-3.5-turbo-16k-0613" + | null + readonly "instructions"?: string | null + readonly "tools"?: ReadonlyArray + readonly "tool_resources"?: { + readonly "code_interpreter"?: { readonly "file_ids"?: ReadonlyArray } + readonly "file_search"?: { readonly "vector_store_ids"?: ReadonlyArray } + } + readonly "metadata"?: Metadata + readonly "temperature"?: number + readonly "top_p"?: number + readonly "stream"?: boolean | null + readonly "max_prompt_tokens"?: number + readonly "max_completion_tokens"?: number + readonly "truncation_strategy"?: { + readonly "type": "auto" | "last_messages" + readonly "last_messages"?: number | null + } + readonly "tool_choice"?: "none" | "auto" | "required" | { + readonly "type": "function" | "code_interpreter" | "file_search" + readonly "function"?: { readonly "name": string } + } + readonly "parallel_tool_calls"?: ParallelToolCalls + readonly "response_format"?: AssistantsApiResponseFormatOption | null +} +export const CreateThreadAndRunRequest = Schema.Struct({ + "assistant_id": Schema.String.annotate({ + "description": "The ID of the [assistant](/docs/api-reference/assistants) to use to execute this run." + }), + "thread": Schema.optionalKey(CreateThreadRequest), + "model": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.String, + Schema.Literals([ + "gpt-5", + "gpt-5-mini", + "gpt-5-nano", + "gpt-5-2025-08-07", + "gpt-5-mini-2025-08-07", + "gpt-5-nano-2025-08-07", + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4.5-preview", + "gpt-4.5-preview-2025-02-27", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613" + ]) + ]).annotate({ + "description": + "The ID of the [Model](/docs/api-reference/models) to be used to execute this run. If a value is provided here, it will override the model associated with the assistant. If not, the model associated with the assistant will be used." + }), + Schema.Null + ]) + ), + "instructions": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Override the default system message of the assistant. This is useful for modifying the behavior on a per-run basis." + }) + ), + "tools": Schema.optionalKey( + Schema.Union([ + Schema.Array( + Schema.Union([AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction], { mode: "oneOf" }) + ).check( + Schema.isMaxLength(20, { + "description": + "Override the tools the assistant can use for this run. This is useful for modifying the behavior on a per-run basis." + }) + ) + ]) + ), + "tool_resources": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "code_interpreter": Schema.optionalKey(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n" + }).check(Schema.isMaxLength(20)) + ) + })), + "file_search": Schema.optionalKey(Schema.Struct({ + "vector_store_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "The ID of the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n" + }).check(Schema.isMaxLength(1)) + ) + })) + }).annotate({ + "description": + "A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + }) + ])), + "metadata": Schema.optionalKey(Metadata), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(2)], { + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n" + }) + ) + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(1)], { + "description": + "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }) + ) + ]) + ), + "stream": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": + "If `true`, returns a stream of events that happen during the Run as server-sent events, terminating when the Run enters a terminal state with a `data: [DONE]` message.\n" + }) + ), + "max_prompt_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(256)], { + "description": + "The maximum number of prompt tokens that may be used over the course of the run. The run will make a best effort to use only the number of prompt tokens specified, across multiple turns of the run. If the run exceeds the number of prompt tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n" + }) + ) + ]) + ), + "max_completion_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(256)], { + "description": + "The maximum number of completion tokens that may be used over the course of the run. The run will make a best effort to use only the number of completion tokens specified, across multiple turns of the run. If the run exceeds the number of completion tokens specified, the run will end with status `incomplete`. See `incomplete_details` for more info.\n" + }) + ) + ]) + ), + "truncation_strategy": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "type": Schema.Literals(["auto", "last_messages"]).annotate({ + "description": + "The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`." + }), + "last_messages": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The number of most recent messages from the thread when constructing the context for the run." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null + ]) + ) + }).annotate({ + "title": "Thread Truncation Controls", + "description": + "Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run." + }) + ])), + "tool_choice": Schema.optionalKey( + Schema.Union([ + Schema.Union([Schema.Literal("none"), Schema.Literal("auto"), Schema.Literal("required")]).annotate({ + "description": + "`none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n" + }), + Schema.Union([ + Schema.Struct({ + "type": Schema.Literals(["function", "code_interpreter", "file_search"]).annotate({ + "description": "The type of the tool. If type is `function`, the function name must be set" + }), + "function": Schema.optionalKey( + Schema.Struct({ "name": Schema.String.annotate({ "description": "The name of the function to call." }) }) + ) + }).annotate({ + "description": "Specifies a tool the model should use. Use to force the model to call a specific tool." + }) + ]) + ], { mode: "oneOf" }).annotate({ + "description": + "Controls which (if any) tool is called by the model.\n`none` means the model will not call any tools and instead generates a message.\n`auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools before responding to the user.\nSpecifying a particular tool like `{\"type\": \"file_search\"}` or `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n" + }) + ), + "parallel_tool_calls": Schema.optionalKey(ParallelToolCalls), + "response_format": Schema.optionalKey(Schema.Union([AssistantsApiResponseFormatOption, Schema.Null])) +}) +export type ModifyAssistantRequest = { + readonly "model"?: string | AssistantSupportedModels + readonly "reasoning_effort"?: ReasoningEffort + readonly "name"?: string | null + readonly "description"?: string | null + readonly "instructions"?: string | null + readonly "tools"?: ReadonlyArray + readonly "tool_resources"?: { + readonly "code_interpreter"?: { readonly "file_ids"?: ReadonlyArray } + readonly "file_search"?: { readonly "vector_store_ids"?: ReadonlyArray } + } | null + readonly "metadata"?: Metadata + readonly "temperature"?: number | null + readonly "top_p"?: number | null + readonly "response_format"?: AssistantsApiResponseFormatOption | null +} +export const ModifyAssistantRequest = Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([Schema.String, AssistantSupportedModels]).annotate({ + "description": + "ID of the model to use. You can use the [List models](/docs/api-reference/models/list) API to see all of your available models, or see our [Model overview](/docs/models) for descriptions of them.\n" + }) + ), + "reasoning_effort": Schema.optionalKey(ReasoningEffort), + "name": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The name of the assistant. The maximum length is 256 characters.\n" }) + .check(Schema.isMaxLength(256)), + Schema.Null + ]) + ), + "description": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "The description of the assistant. The maximum length is 512 characters.\n" + }).check(Schema.isMaxLength(512)), + Schema.Null + ]) + ), + "instructions": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "The system instructions that the assistant uses. The maximum length is 256,000 characters.\n" + }).check(Schema.isMaxLength(256000)), + Schema.Null + ]) + ), + "tools": Schema.optionalKey( + Schema.Array( + Schema.Union([AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction], { mode: "oneOf" }) + ).annotate({ + "description": + "A list of tool enabled on the assistant. There can be a maximum of 128 tools per assistant. Tools can be of types `code_interpreter`, `file_search`, or `function`.\n" + }).check(Schema.isMaxLength(128)) + ), + "tool_resources": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "code_interpreter": Schema.optionalKey(Schema.Struct({ + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "Overrides the list of [file](/docs/api-reference/files) IDs made available to the `code_interpreter` tool. There can be a maximum of 20 files associated with the tool.\n" + }).check(Schema.isMaxLength(20)) + ) + })), + "file_search": Schema.optionalKey(Schema.Struct({ + "vector_store_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "Overrides the [vector store](/docs/api-reference/vector-stores/object) attached to this assistant. There can be a maximum of 1 vector store attached to the assistant.\n" + }).check(Schema.isMaxLength(1)) + ) + })) + }).annotate({ + "description": + "A set of resources that are used by the assistant's tools. The resources are specific to the type of tool. For example, the `code_interpreter` tool requires a list of file IDs, while the `file_search` tool requires a list of vector store IDs.\n" + }), + Schema.Null + ])), + "metadata": Schema.optionalKey(Metadata), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey(Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the top 10% probability mass are considered.\n\nWe generally recommend altering this or temperature but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ])), + "response_format": Schema.optionalKey(Schema.Union([AssistantsApiResponseFormatOption, Schema.Null])) +}) +export type RunObject = { + readonly "id": string + readonly "object": "thread.run" + readonly "created_at": number + readonly "thread_id": string + readonly "assistant_id": string + readonly "status": + | "queued" + | "in_progress" + | "requires_action" + | "cancelling" + | "cancelled" + | "failed" + | "completed" + | "incomplete" + | "expired" + readonly "required_action": { + readonly "type": "submit_tool_outputs" + readonly "submit_tool_outputs": { readonly "tool_calls": ReadonlyArray } + } + readonly "last_error": { + readonly "code": "server_error" | "rate_limit_exceeded" | "invalid_prompt" + readonly "message": string + } + readonly "expires_at": never + readonly "started_at": never + readonly "cancelled_at": never + readonly "failed_at": never + readonly "completed_at": never + readonly "incomplete_details": { readonly "reason"?: "max_completion_tokens" | "max_prompt_tokens" } + readonly "model": string + readonly "instructions": string + readonly "tools": ReadonlyArray + readonly "metadata": Metadata + readonly "usage": RunCompletionUsage + readonly "temperature"?: number | null + readonly "top_p"?: number | null + readonly "max_prompt_tokens": number + readonly "max_completion_tokens": number + readonly "truncation_strategy": { + readonly "type": "auto" | "last_messages" + readonly "last_messages"?: number | null + } + readonly "tool_choice": "none" | "auto" | "required" | { + readonly "type": "function" | "code_interpreter" | "file_search" + readonly "function"?: { readonly "name": string } + } + readonly "parallel_tool_calls": ParallelToolCalls + readonly "response_format": AssistantsApiResponseFormatOption | null +} +export const RunObject = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The identifier, which can be referenced in API endpoints." }), + "object": Schema.Literal("thread.run").annotate({ "description": "The object type, which is always `thread.run`." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the run was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "thread_id": Schema.String.annotate({ + "description": "The ID of the [thread](/docs/api-reference/threads) that was executed on as a part of this run." + }), + "assistant_id": Schema.String.annotate({ + "description": "The ID of the [assistant](/docs/api-reference/assistants) used for execution of this run." + }), + "status": Schema.Literals([ + "queued", + "in_progress", + "requires_action", + "cancelling", + "cancelled", + "failed", + "completed", + "incomplete", + "expired" + ]).annotate({ + "description": + "The status of the run, which can be either `queued`, `in_progress`, `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, `incomplete`, or `expired`." + }), + "required_action": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("submit_tool_outputs").annotate({ + "description": "For now, this is always `submit_tool_outputs`." + }), + "submit_tool_outputs": Schema.Struct({ + "tool_calls": Schema.Array(RunToolCallObject).annotate({ "description": "A list of the relevant tool calls." }) + }).annotate({ "description": "Details on the tool outputs needed for this run to continue." }) + }).annotate({ + "description": "Details on the action required to continue the run. Will be `null` if no action is required." + }) + ]), + "last_error": Schema.Union([ + Schema.Struct({ + "code": Schema.Literals(["server_error", "rate_limit_exceeded", "invalid_prompt"]).annotate({ + "description": "One of `server_error`, `rate_limit_exceeded`, or `invalid_prompt`." + }), + "message": Schema.String.annotate({ "description": "A human-readable description of the error." }) + }).annotate({ "description": "The last error associated with this run. Will be `null` if there are no errors." }) + ]), + "expires_at": Schema.Never, + "started_at": Schema.Never, + "cancelled_at": Schema.Never, + "failed_at": Schema.Never, + "completed_at": Schema.Never, + "incomplete_details": Schema.Union([ + Schema.Struct({ + "reason": Schema.optionalKey( + Schema.Literals(["max_completion_tokens", "max_prompt_tokens"]).annotate({ + "description": + "The reason why the run is incomplete. This will point to which specific token limit was reached over the course of the run." + }) + ) + }).annotate({ "description": "Details on why the run is incomplete. Will be `null` if the run is not incomplete." }) + ]), + "model": Schema.String.annotate({ + "description": "The model that the [assistant](/docs/api-reference/assistants) used for this run." + }), + "instructions": Schema.String.annotate({ + "description": "The instructions that the [assistant](/docs/api-reference/assistants) used for this run." + }), + "tools": Schema.Array( + Schema.Union([AssistantToolsCode, AssistantToolsFileSearch, AssistantToolsFunction], { mode: "oneOf" }) + ).annotate({ + "description": "The list of tools that the [assistant](/docs/api-reference/assistants) used for this run." + }).check(Schema.isMaxLength(20)), + "metadata": Metadata, + "usage": RunCompletionUsage, + "temperature": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isFinite()), Schema.Null]).annotate({ + "description": "The sampling temperature used for this run. If not set, defaults to 1." + }) + ), + "top_p": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isFinite()), Schema.Null]).annotate({ + "description": "The nucleus sampling value used for this run. If not set, defaults to 1." + }) + ), + "max_prompt_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(256)], { + "description": "The maximum number of prompt tokens specified to have been used over the course of the run.\n" + }) + ) + ]), + "max_completion_tokens": Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(256)], { + "description": + "The maximum number of completion tokens specified to have been used over the course of the run.\n" + }) + ) + ]), + "truncation_strategy": Schema.Union([ + Schema.Struct({ + "type": Schema.Literals(["auto", "last_messages"]).annotate({ + "description": + "The truncation strategy to use for the thread. The default is `auto`. If set to `last_messages`, the thread will be truncated to the n most recent messages in the thread. When set to `auto`, messages in the middle of the thread will be dropped to fit the context length of the model, `max_prompt_tokens`." + }), + "last_messages": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The number of most recent messages from the thread when constructing the context for the run." + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null + ]) + ) + }).annotate({ + "title": "Thread Truncation Controls", + "description": + "Controls for how a thread will be truncated prior to the run. Use this to control the initial context window of the run." + }) + ]), + "tool_choice": Schema.Union([ + Schema.Union([Schema.Literal("none"), Schema.Literal("auto"), Schema.Literal("required")]).annotate({ + "description": + "`none` means the model will not call any tools and instead generates a message. `auto` means the model can pick between generating a message or calling one or more tools. `required` means the model must call one or more tools before responding to the user.\n" + }), + Schema.Union([ + Schema.Struct({ + "type": Schema.Literals(["function", "code_interpreter", "file_search"]).annotate({ + "description": "The type of the tool. If type is `function`, the function name must be set" + }), + "function": Schema.optionalKey( + Schema.Struct({ "name": Schema.String.annotate({ "description": "The name of the function to call." }) }) + ) + }).annotate({ + "description": "Specifies a tool the model should use. Use to force the model to call a specific tool." + }) + ]) + ], { mode: "oneOf" }).annotate({ + "description": + "Controls which (if any) tool is called by the model.\n`none` means the model will not call any tools and instead generates a message.\n`auto` is the default value and means the model can pick between generating a message or calling one or more tools.\n`required` means the model must call one or more tools before responding to the user.\nSpecifying a particular tool like `{\"type\": \"file_search\"}` or `{\"type\": \"function\", \"function\": {\"name\": \"my_function\"}}` forces the model to call that tool.\n" + }), + "parallel_tool_calls": ParallelToolCalls, + "response_format": Schema.Union([AssistantsApiResponseFormatOption, Schema.Null]) +}).annotate({ + "title": "A run on a thread", + "description": "Represents an execution run on a [thread](/docs/api-reference/threads)." +}) +export type ResponseTextParam = { + readonly "format"?: TextResponseFormatConfiguration + readonly "verbosity"?: Verbosity +} +export const ResponseTextParam = Schema.Struct({ + "format": Schema.optionalKey(TextResponseFormatConfiguration), + "verbosity": Schema.optionalKey(Verbosity) +}).annotate({ + "description": + "Configuration options for a text response from the model. Can be plain\ntext or structured JSON data. Learn more:\n- [Text inputs and outputs](/docs/guides/text)\n- [Structured Outputs](/docs/guides/structured-outputs)\n" +}) +export type RealtimeCreateClientSecretRequest = { + readonly "expires_after"?: { readonly "anchor"?: "created_at"; readonly "seconds"?: number } + readonly "session"?: RealtimeSessionCreateRequestGA | RealtimeTranscriptionSessionCreateRequestGA +} +export const RealtimeCreateClientSecretRequest = Schema.Struct({ + "expires_after": Schema.optionalKey( + Schema.Struct({ + "anchor": Schema.optionalKey( + Schema.Literal("created_at").annotate({ + "description": + "The anchor point for the client secret expiration, meaning that `seconds` will be added to the `created_at` time of the client secret to produce an expiration timestamp. Only `created_at` is currently supported.\n" + }) + ), + "seconds": Schema.optionalKey( + Schema.Number.annotate({ + "description": + "The number of seconds from the anchor point to the expiration. Select a value between `10` and `7200` (2 hours). This default to 600 seconds (10 minutes) if not specified.\n", + "format": "int64" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(10)).check(Schema.isLessThanOrEqualTo(7200)) + ) + }).annotate({ + "title": "Client secret expiration", + "description": + "Configuration for the client secret expiration. Expiration refers to the time after which\na client secret will no longer be valid for creating sessions. The session itself may\ncontinue after that time once started. A secret can be used to create multiple sessions\nuntil it expires.\n" + }) + ), + "session": Schema.optionalKey( + Schema.Union([RealtimeSessionCreateRequestGA, RealtimeTranscriptionSessionCreateRequestGA], { mode: "oneOf" }) + .annotate({ + "title": "Session configuration", + "description": + "Session configuration to use for the client secret. Choose either a realtime\nsession or a transcription session.\n" + }) + ) +}).annotate({ + "title": "Realtime client secret creation request", + "description": + "Create a session and client secret for the Realtime API. The request can specify\neither a realtime or a transcription session configuration.\n[Learn more about the Realtime API](/docs/guides/realtime).\n" +}) +export type RealtimeCreateClientSecretResponse = { + readonly "value": string + readonly "expires_at": number + readonly "session": RealtimeSessionCreateResponseGA | RealtimeTranscriptionSessionCreateResponseGA +} +export const RealtimeCreateClientSecretResponse = Schema.Struct({ + "value": Schema.String.annotate({ "description": "The generated client secret value." }), + "expires_at": Schema.Number.annotate({ + "description": "Expiration timestamp for the client secret, in seconds since epoch.", + "format": "unixtime" + }).check(Schema.isInt()), + "session": Schema.Union([RealtimeSessionCreateResponseGA, RealtimeTranscriptionSessionCreateResponseGA], { + mode: "oneOf" + }).annotate({ + "title": "Session configuration", + "description": "The session configuration for either a realtime or transcription session.\n" + }) +}).annotate({ + "title": "Realtime session and client secret", + "description": "Response from creating a session and client secret for the Realtime API.\n" +}) +export type RealtimeServerEventSessionCreated = { + readonly "event_id": string + readonly "type": "session.created" + readonly "session": RealtimeSessionCreateResponseGA | RealtimeTranscriptionSessionCreateResponseGA +} +export const RealtimeServerEventSessionCreated = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("session.created").annotate({ "description": "The event type, must be `session.created`." }), + "session": Schema.Union([RealtimeSessionCreateResponseGA, RealtimeTranscriptionSessionCreateResponseGA], { + mode: "oneOf" + }).annotate({ "description": "The session configuration." }) +}).annotate({ + "description": + "Returned when a Session is created. Emitted automatically when a new\nconnection is established as the first server event. This event will contain\nthe default Session configuration.\n" +}) +export type RealtimeServerEventSessionUpdated = { + readonly "event_id": string + readonly "type": "session.updated" + readonly "session": RealtimeSessionCreateResponseGA | RealtimeTranscriptionSessionCreateResponseGA +} +export const RealtimeServerEventSessionUpdated = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("session.updated").annotate({ "description": "The event type, must be `session.updated`." }), + "session": Schema.Union([RealtimeSessionCreateResponseGA, RealtimeTranscriptionSessionCreateResponseGA], { + mode: "oneOf" + }).annotate({ "description": "The session configuration." }) +}).annotate({ + "description": "Returned when a session is updated with a `session.update` event, unless\nthere is an error.\n" +}) +export type CreateVectorStoreFileBatchRequest = { + readonly "file_ids": ReadonlyArray + readonly "files"?: ReadonlyArray + readonly "chunking_strategy"?: ChunkingStrategyRequestParam + readonly "attributes"?: VectorStoreFileAttributes +} | { + readonly "files": ReadonlyArray + readonly "file_ids"?: ReadonlyArray + readonly "chunking_strategy"?: ChunkingStrategyRequestParam + readonly "attributes"?: VectorStoreFileAttributes +} +export const CreateVectorStoreFileBatchRequest = Schema.Union([ + Schema.Struct({ + "file_ids": Schema.Array(Schema.String).annotate({ + "description": + "A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. If `attributes` or `chunking_strategy` are provided, they will be applied to all files in the batch. The maximum batch size is 2000 files. This endpoint is recommended for multi-file ingestion and helps reduce per-vector-store write request pressure. Mutually exclusive with `files`." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(2000)), + "files": Schema.optionalKey( + Schema.Array(CreateVectorStoreFileRequest).annotate({ + "description": + "A list of objects that each include a `file_id` plus optional `attributes` or `chunking_strategy`. Use this when you need to override metadata for specific files. The global `attributes` or `chunking_strategy` will be ignored and must be specified for each file. The maximum batch size is 2000 files. This endpoint is recommended for multi-file ingestion and helps reduce per-vector-store write request pressure. Mutually exclusive with `file_ids`." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(2000)) + ), + "chunking_strategy": Schema.optionalKey(ChunkingStrategyRequestParam), + "attributes": Schema.optionalKey(VectorStoreFileAttributes) + }), + Schema.Struct({ + "files": Schema.Array(CreateVectorStoreFileRequest).annotate({ + "description": + "A list of objects that each include a `file_id` plus optional `attributes` or `chunking_strategy`. Use this when you need to override metadata for specific files. The global `attributes` or `chunking_strategy` will be ignored and must be specified for each file. The maximum batch size is 2000 files. This endpoint is recommended for multi-file ingestion and helps reduce per-vector-store write request pressure. Mutually exclusive with `file_ids`." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(2000)), + "file_ids": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of [File](/docs/api-reference/files) IDs that the vector store should use. Useful for tools like `file_search` that can access files. If `attributes` or `chunking_strategy` are provided, they will be applied to all files in the batch. The maximum batch size is 2000 files. This endpoint is recommended for multi-file ingestion and helps reduce per-vector-store write request pressure. Mutually exclusive with `files`." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(2000)) + ), + "chunking_strategy": Schema.optionalKey(ChunkingStrategyRequestParam), + "attributes": Schema.optionalKey(VectorStoreFileAttributes) + }) +]) +export type CodeInterpreterTool = { + readonly "type": "code_interpreter" + readonly "container": string | AutoCodeInterpreterToolParam +} +export const CodeInterpreterTool = Schema.Struct({ + "type": Schema.Literal("code_interpreter").annotate({ + "description": "The type of the code interpreter tool. Always `code_interpreter`.\n" + }), + "container": Schema.Union([ + Schema.String.annotate({ "description": "The container ID." }), + AutoCodeInterpreterToolParam + ], { mode: "oneOf" }).annotate({ + "description": + "The code interpreter container. Can be a container ID or an object that\nspecifies uploaded file IDs to make available to your code, along with an\noptional `memory_limit` setting.\n" + }) +}).annotate({ + "title": "Code interpreter", + "description": "A tool that runs Python code to help generate a response to a prompt.\n" +}) +export type FunctionShellToolParam = { + readonly "type": "shell" + readonly "environment"?: ContainerAutoParam | LocalEnvironmentParam | ContainerReferenceParam | null +} +export const FunctionShellToolParam = Schema.Struct({ + "type": Schema.Literal("shell").annotate({ "description": "The type of the shell tool. Always `shell`." }), + "environment": Schema.optionalKey( + Schema.Union([ + Schema.Union([ContainerAutoParam, LocalEnvironmentParam, ContainerReferenceParam], { mode: "oneOf" }), + Schema.Null + ]) + ) +}).annotate({ "title": "Shell tool", "description": "A tool that allows the model to execute shell commands." }) +export type EvalItemContent = EvalItemContentItem | EvalItemContentArray +export const EvalItemContent = Schema.Union([EvalItemContentItem, EvalItemContentArray], { mode: "oneOf" }).annotate({ + "title": "Eval content", + "description": + "Inputs to the model - can contain template strings. Supports text, output text, input images, and input audio, either as a single item or an array of items.\n" +}) +export type OutputMessageContent = OutputTextContent | RefusalContent +export const OutputMessageContent = Schema.Union([OutputTextContent, RefusalContent], { mode: "oneOf" }) +export type ResponseContentPartAddedEvent = { + readonly "type": "response.content_part.added" + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "part": OutputTextContent | RefusalContent | ReasoningTextContent + readonly "sequence_number": number +} +export const ResponseContentPartAddedEvent = Schema.Struct({ + "type": Schema.Literal("response.content_part.added").annotate({ + "description": "The type of the event. Always `response.content_part.added`.\n" + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the output item that the content part was added to.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the content part was added to.\n" + }).check(Schema.isInt()), + "content_index": Schema.Number.annotate({ "description": "The index of the content part that was added.\n" }).check( + Schema.isInt() + ), + "part": Schema.Union([OutputTextContent, RefusalContent, ReasoningTextContent], { mode: "oneOf" }).annotate({ + "description": "The content part that was added.\n" + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when a new content part is added." }) +export type ResponseContentPartDoneEvent = { + readonly "type": "response.content_part.done" + readonly "item_id": string + readonly "output_index": number + readonly "content_index": number + readonly "sequence_number": number + readonly "part": OutputTextContent | RefusalContent | ReasoningTextContent +} +export const ResponseContentPartDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.content_part.done").annotate({ + "description": "The type of the event. Always `response.content_part.done`.\n" + }), + "item_id": Schema.String.annotate({ + "description": "The ID of the output item that the content part was added to.\n" + }), + "output_index": Schema.Number.annotate({ + "description": "The index of the output item that the content part was added to.\n" + }).check(Schema.isInt()), + "content_index": Schema.Number.annotate({ "description": "The index of the content part that is done.\n" }).check( + Schema.isInt() + ), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "part": Schema.Union([OutputTextContent, RefusalContent, ReasoningTextContent], { mode: "oneOf" }).annotate({ + "description": "The content part that is done.\n" + }) +}).annotate({ "description": "Emitted when a content part is done." }) +export type Message = { + readonly "type": "message" + readonly "id": string + readonly "status": "in_progress" | "completed" | "incomplete" + readonly "role": "unknown" | "user" | "assistant" | "system" | "critic" | "discriminator" | "developer" | "tool" + readonly "content": ReadonlyArray< + | InputTextContent + | OutputTextContent + | TextContent + | SummaryTextContent + | ReasoningTextContent + | RefusalContent + | InputImageContent + | ComputerScreenshotContent + | InputFileContent + > + readonly "phase"?: "commentary" | "final_answer" | null +} +export const Message = Schema.Struct({ + "type": Schema.Literal("message").annotate({ "description": "The type of the message. Always set to `message`." }), + "id": Schema.String.annotate({ "description": "The unique ID of the message." }), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API." + }), + "role": Schema.Literals(["unknown", "user", "assistant", "system", "critic", "discriminator", "developer", "tool"]) + .annotate({ + "description": + "The role of the message. One of `unknown`, `user`, `assistant`, `system`, `critic`, `discriminator`, `developer`, or `tool`." + }), + "content": Schema.Array( + Schema.Union([ + InputTextContent, + OutputTextContent, + TextContent, + SummaryTextContent, + ReasoningTextContent, + RefusalContent, + InputImageContent, + ComputerScreenshotContent, + InputFileContent + ], { mode: "oneOf" }).annotate({ "description": "A content part that makes up an input or output item." }) + ).annotate({ "description": "The content of the message" }), + "phase": Schema.optionalKey(Schema.Union([ + Schema.Literals(["commentary", "final_answer"]).annotate({ + "description": + "Labels an `assistant` message as intermediate commentary (`commentary`) or the final answer (`final_answer`). For models like `gpt-5.3-codex` and beyond, when sending follow-up requests, preserve and resend phase on all assistant messages — dropping it can degrade performance. Not used for user messages." + }), + Schema.Null + ])) +}).annotate({ "title": "Message", "description": "A message to or from the model." }) +export type EasyInputMessage = { + readonly "role": "user" | "assistant" | "system" | "developer" + readonly "content": string | InputMessageContentList + readonly "phase"?: MessagePhase | null + readonly "type"?: "message" +} +export const EasyInputMessage = Schema.Struct({ + "role": Schema.Literals(["user", "assistant", "system", "developer"]).annotate({ + "description": "The role of the message input. One of `user`, `assistant`, `system`, or\n`developer`.\n" + }), + "content": Schema.Union([ + Schema.String.annotate({ "title": "Text input", "description": "A text input to the model.\n" }), + InputMessageContentList + ], { mode: "oneOf" }).annotate({ + "description": + "Text, image, or audio input to the model, used to generate a response.\nCan also contain previous assistant responses.\n" + }), + "phase": Schema.optionalKey(Schema.Union([MessagePhase, Schema.Null])), + "type": Schema.optionalKey( + Schema.Literal("message").annotate({ "description": "The type of the message input. Always `message`.\n" }) + ) +}).annotate({ + "title": "Input message", + "description": + "A message input to the model with a role indicating instruction following\nhierarchy. Instructions given with the `developer` or `system` role take\nprecedence over instructions given with the `user` role. Messages with the\n`assistant` role are presumed to have been generated by the model in previous\ninteractions.\n" +}) +export type InputMessageResource = { + readonly "type": "message" + readonly "role": "user" | "system" | "developer" + readonly "status"?: "in_progress" | "completed" | "incomplete" + readonly "content": InputMessageContentList + readonly "id": string +} +export const InputMessageResource = Schema.Struct({ + "type": Schema.Literal("message").annotate({ + "description": "The type of the message input. Always set to `message`.\n" + }), + "role": Schema.Literals(["user", "system", "developer"]).annotate({ + "description": "The role of the message input. One of `user`, `system`, or `developer`.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + ), + "content": InputMessageContentList, + "id": Schema.String.annotate({ "description": "The unique ID of the message input.\n" }) +}).annotate({ + "title": "Input message", + "description": + "A message input to the model with a role indicating instruction following\nhierarchy. Instructions given with the `developer` or `system` role take\nprecedence over instructions given with the `user` role.\n" +}) +export type ComputerActionList = ReadonlyArray +export const ComputerActionList = Schema.Array(ComputerAction).annotate({ + "title": "Computer Action List", + "description": + "Flattened batched actions for `computer_use`. Each action includes an\n`type` discriminator and action-specific fields.\n" +}) +export type ThreadItem = + | UserMessageItem + | AssistantMessageItem + | WidgetMessageItem + | ClientToolCallItem + | TaskItem + | TaskGroupItem +export const ThreadItem = Schema.Union([ + UserMessageItem, + AssistantMessageItem, + WidgetMessageItem, + ClientToolCallItem, + TaskItem, + TaskGroupItem +], { mode: "oneOf" }).annotate({ "title": "The thread item" }) +export type ListAuditLogsResponse = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id"?: string | null + readonly "last_id"?: string | null + readonly "has_more": boolean +} +export const ListAuditLogsResponse = Schema.Struct({ + "object": Schema.Literal("list"), + "data": Schema.Array(AuditLog), + "first_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "last_id": Schema.optionalKey(Schema.Union([Schema.String, Schema.Null])), + "has_more": Schema.Boolean +}) +export type ChatCompletionList = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const ChatCompletionList = Schema.Struct({ + "object": Schema.Literal("list").annotate({ + "description": "The type of this object. It is always set to \"list\".\n" + }), + "data": Schema.Array(CreateChatCompletionResponse).annotate({ + "description": "An array of chat completion objects.\n" + }), + "first_id": Schema.String.annotate({ + "description": "The identifier of the first chat completion in the data array." + }), + "last_id": Schema.String.annotate({ "description": "The identifier of the last chat completion in the data array." }), + "has_more": Schema.Boolean.annotate({ "description": "Indicates whether there are more Chat Completions available." }) +}).annotate({ "title": "ChatCompletionList", "description": "An object representing a list of Chat Completions.\n" }) +export type CreateChatCompletionRequest = { + readonly "metadata"?: Metadata + readonly "top_logprobs"?: number + readonly "temperature"?: number | null + readonly "top_p"?: number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "messages": ReadonlyArray + readonly "model": + | string + | "gpt-5.4" + | "gpt-5.4-mini" + | "gpt-5.4-nano" + | "gpt-5.4-mini-2026-03-17" + | "gpt-5.4-nano-2026-03-17" + | "gpt-5.3-chat-latest" + | "gpt-5.2" + | "gpt-5.2-2025-12-11" + | "gpt-5.2-chat-latest" + | "gpt-5.2-pro" + | "gpt-5.2-pro-2025-12-11" + | "gpt-5.1" + | "gpt-5.1-2025-11-13" + | "gpt-5.1-codex" + | "gpt-5.1-mini" + | "gpt-5.1-chat-latest" + | "gpt-5" + | "gpt-5-mini" + | "gpt-5-nano" + | "gpt-5-2025-08-07" + | "gpt-5-mini-2025-08-07" + | "gpt-5-nano-2025-08-07" + | "gpt-5-chat-latest" + | "gpt-4.1" + | "gpt-4.1-mini" + | "gpt-4.1-nano" + | "gpt-4.1-2025-04-14" + | "gpt-4.1-mini-2025-04-14" + | "gpt-4.1-nano-2025-04-14" + | "o4-mini" + | "o4-mini-2025-04-16" + | "o3" + | "o3-2025-04-16" + | "o3-mini" + | "o3-mini-2025-01-31" + | "o1" + | "o1-2024-12-17" + | "o1-preview" + | "o1-preview-2024-09-12" + | "o1-mini" + | "o1-mini-2024-09-12" + | "gpt-4o" + | "gpt-4o-2024-11-20" + | "gpt-4o-2024-08-06" + | "gpt-4o-2024-05-13" + | "gpt-4o-audio-preview" + | "gpt-4o-audio-preview-2024-10-01" + | "gpt-4o-audio-preview-2024-12-17" + | "gpt-4o-audio-preview-2025-06-03" + | "gpt-4o-mini-audio-preview" + | "gpt-4o-mini-audio-preview-2024-12-17" + | "gpt-4o-search-preview" + | "gpt-4o-mini-search-preview" + | "gpt-4o-search-preview-2025-03-11" + | "gpt-4o-mini-search-preview-2025-03-11" + | "chatgpt-4o-latest" + | "codex-mini-latest" + | "gpt-4o-mini" + | "gpt-4o-mini-2024-07-18" + | "gpt-4-turbo" + | "gpt-4-turbo-2024-04-09" + | "gpt-4-0125-preview" + | "gpt-4-turbo-preview" + | "gpt-4-1106-preview" + | "gpt-4-vision-preview" + | "gpt-4" + | "gpt-4-0314" + | "gpt-4-0613" + | "gpt-4-32k" + | "gpt-4-32k-0314" + | "gpt-4-32k-0613" + | "gpt-3.5-turbo" + | "gpt-3.5-turbo-16k" + | "gpt-3.5-turbo-0301" + | "gpt-3.5-turbo-0613" + | "gpt-3.5-turbo-1106" + | "gpt-3.5-turbo-0125" + | "gpt-3.5-turbo-16k-0613" + readonly "modalities"?: ResponseModalities + readonly "verbosity"?: Verbosity + readonly "reasoning_effort"?: ReasoningEffort + readonly "max_completion_tokens"?: number | null + readonly "frequency_penalty"?: number + readonly "presence_penalty"?: number + readonly "web_search_options"?: { + readonly "user_location"?: { readonly "type": "approximate"; readonly "approximate": WebSearchLocation } + readonly "search_context_size"?: WebSearchContextSize + } + readonly "response_format"?: ResponseFormatText | ResponseFormatJsonSchema | ResponseFormatJsonObject + readonly "audio"?: { + readonly "voice": VoiceIdsShared | { readonly "id": string } + readonly "format": "wav" | "aac" | "mp3" | "flac" | "opus" | "pcm16" + } + readonly "store"?: boolean | null + readonly "stream"?: boolean | null + readonly "stop"?: StopConfiguration + readonly "logit_bias"?: {} + readonly "logprobs"?: boolean | null + readonly "max_tokens"?: number | null + readonly "n"?: number + readonly "prediction"?: PredictionContent | null + readonly "seed"?: number + readonly "stream_options"?: ChatCompletionStreamOptions + readonly "tools"?: ReadonlyArray + readonly "tool_choice"?: ChatCompletionToolChoiceOption + readonly "parallel_tool_calls"?: ParallelToolCalls + readonly "function_call"?: "none" | "auto" | ChatCompletionFunctionCallOption + readonly "functions"?: ReadonlyArray +} +export const CreateChatCompletionRequest = Schema.Struct({ + "metadata": Schema.optionalKey(Metadata), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup( + [Schema.isFinite(), Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(20)], + { + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n`logprobs` must be set to `true` if this parameter is used.\n" + } + ) + ).check( + Schema.makeFilterGroup([ + Schema.isGreaterThanOrEqualTo(0), + Schema.isLessThanOrEqualTo(20), + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(20)], { + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }) + ], { + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }) + ) + ]) + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey(Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ])), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "messages": Schema.Array(ChatCompletionRequestMessage).annotate({ + "description": + "A list of messages comprising the conversation so far. Depending on the\n[model](/docs/models) you use, different message types (modalities) are\nsupported, like [text](/docs/guides/text-generation),\n[images](/docs/guides/vision), and [audio](/docs/guides/audio).\n" + }).check(Schema.isMinLength(1)), + "model": Schema.Union([ + Schema.String, + Schema.Literals([ + "gpt-5.4", + "gpt-5.4-mini", + "gpt-5.4-nano", + "gpt-5.4-mini-2026-03-17", + "gpt-5.4-nano-2026-03-17", + "gpt-5.3-chat-latest", + "gpt-5.2", + "gpt-5.2-2025-12-11", + "gpt-5.2-chat-latest", + "gpt-5.2-pro", + "gpt-5.2-pro-2025-12-11", + "gpt-5.1", + "gpt-5.1-2025-11-13", + "gpt-5.1-codex", + "gpt-5.1-mini", + "gpt-5.1-chat-latest", + "gpt-5", + "gpt-5-mini", + "gpt-5-nano", + "gpt-5-2025-08-07", + "gpt-5-mini-2025-08-07", + "gpt-5-nano-2025-08-07", + "gpt-5-chat-latest", + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "gpt-4.1-2025-04-14", + "gpt-4.1-mini-2025-04-14", + "gpt-4.1-nano-2025-04-14", + "o4-mini", + "o4-mini-2025-04-16", + "o3", + "o3-2025-04-16", + "o3-mini", + "o3-mini-2025-01-31", + "o1", + "o1-2024-12-17", + "o1-preview", + "o1-preview-2024-09-12", + "o1-mini", + "o1-mini-2024-09-12", + "gpt-4o", + "gpt-4o-2024-11-20", + "gpt-4o-2024-08-06", + "gpt-4o-2024-05-13", + "gpt-4o-audio-preview", + "gpt-4o-audio-preview-2024-10-01", + "gpt-4o-audio-preview-2024-12-17", + "gpt-4o-audio-preview-2025-06-03", + "gpt-4o-mini-audio-preview", + "gpt-4o-mini-audio-preview-2024-12-17", + "gpt-4o-search-preview", + "gpt-4o-mini-search-preview", + "gpt-4o-search-preview-2025-03-11", + "gpt-4o-mini-search-preview-2025-03-11", + "chatgpt-4o-latest", + "codex-mini-latest", + "gpt-4o-mini", + "gpt-4o-mini-2024-07-18", + "gpt-4-turbo", + "gpt-4-turbo-2024-04-09", + "gpt-4-0125-preview", + "gpt-4-turbo-preview", + "gpt-4-1106-preview", + "gpt-4-vision-preview", + "gpt-4", + "gpt-4-0314", + "gpt-4-0613", + "gpt-4-32k", + "gpt-4-32k-0314", + "gpt-4-32k-0613", + "gpt-3.5-turbo", + "gpt-3.5-turbo-16k", + "gpt-3.5-turbo-0301", + "gpt-3.5-turbo-0613", + "gpt-3.5-turbo-1106", + "gpt-3.5-turbo-0125", + "gpt-3.5-turbo-16k-0613" + ]) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }), + "modalities": Schema.optionalKey(ResponseModalities), + "verbosity": Schema.optionalKey(Verbosity), + "reasoning_effort": Schema.optionalKey(ReasoningEffort), + "max_completion_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a completion, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }) + ), + "frequency_penalty": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(-2), Schema.isLessThanOrEqualTo(2)], { + "description": + "Number between -2.0 and 2.0. Positive values penalize new tokens based on\ntheir existing frequency in the text so far, decreasing the model's\nlikelihood to repeat the same line verbatim.\n" + }) + ) + ]) + ), + "presence_penalty": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isFinite()).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(-2), Schema.isLessThanOrEqualTo(2)], { + "description": + "Number between -2.0 and 2.0. Positive values penalize new tokens based on\nwhether they appear in the text so far, increasing the model's likelihood\nto talk about new topics.\n" + }) + ) + ]) + ), + "web_search_options": Schema.optionalKey( + Schema.Struct({ + "user_location": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("approximate").annotate({ + "description": "The type of location approximation. Always `approximate`.\n" + }), + "approximate": WebSearchLocation + }).annotate({ "description": "Approximate location parameters for the search.\n" }) + ]) + ), + "search_context_size": Schema.optionalKey(WebSearchContextSize) + }).annotate({ + "title": "Web search", + "description": + "This tool searches the web for relevant results to use in a response.\nLearn more about the [web search tool](/docs/guides/tools-web-search?api-mode=chat).\n" + }) + ), + "response_format": Schema.optionalKey( + Schema.Union([ResponseFormatText, ResponseFormatJsonSchema, ResponseFormatJsonObject], { mode: "oneOf" }).annotate({ + "description": + "An object specifying the format that the model must output.\n\nSetting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables\nStructured Outputs which ensures the model will match your supplied JSON\nschema. Learn more in the [Structured Outputs\nguide](/docs/guides/structured-outputs).\n\nSetting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n" + }) + ), + "audio": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "voice": Schema.Union([ + VoiceIdsShared, + Schema.Struct({ "id": Schema.String.annotate({ "description": "The custom voice ID, e.g. `voice_1234`." }) }) + .annotate({ "description": "Custom voice reference." }) + ]).annotate({ + "title": "Voice", + "description": + "The voice the model uses to respond. Supported built-in voices are\n`alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, `onyx`,\n`sage`, `shimmer`, `marin`, and `cedar`. You may also provide a\ncustom voice object with an `id`, for example `{ \"id\": \"voice_1234\" }`.\n" + }), + "format": Schema.Literals(["wav", "aac", "mp3", "flac", "opus", "pcm16"]).annotate({ + "description": "Specifies the output audio format. Must be one of `wav`, `mp3`, `flac`,\n`opus`, or `pcm16`.\n" + }) + }).annotate({ + "description": + "Parameters for audio output. Required when audio output is requested with\n`modalities: [\"audio\"]`. [Learn more](/docs/guides/audio).\n" + }) + ])), + "store": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": + "Whether or not to store the output of this chat completion request for\nuse in our [model distillation](/docs/guides/distillation) or\n[evals](/docs/guides/evals) products.\n\nSupports text and image inputs. Note: image inputs over 8MB will be dropped.\n" + }) + ), + "stream": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": + "If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section below](/docs/api-reference/chat/streaming)\nfor more information, along with the [streaming responses](/docs/guides/streaming-responses)\nguide for more information on how to handle the streaming events.\n" + }) + ), + "stop": Schema.optionalKey(StopConfiguration), + "logit_bias": Schema.optionalKey(Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Modify the likelihood of specified tokens appearing in the completion.\n\nAccepts a JSON object that maps tokens (specified by their token ID in the\ntokenizer) to an associated bias value from -100 to 100. Mathematically,\nthe bias is added to the logits generated by the model prior to sampling.\nThe exact effect will vary per model, but values between -1 and 1 should\ndecrease or increase likelihood of selection; values like -100 or 100\nshould result in a ban or exclusive selection of the relevant token.\n" + }) + ])), + "logprobs": Schema.optionalKey( + Schema.Union([Schema.Boolean, Schema.Null]).annotate({ + "description": + "Whether to return log probabilities of the output tokens or not. If true,\nreturns the log probabilities of each output token returned in the\n`content` of `message`.\n" + }) + ), + "max_tokens": Schema.optionalKey( + Schema.Union([Schema.Number.check(Schema.isInt()), Schema.Null]).annotate({ + "description": + "The maximum number of [tokens](/tokenizer) that can be generated in the\nchat completion. This value can be used to control\n[costs](https://openai.com/api/pricing/) for text generated via API.\n\nThis value is now deprecated in favor of `max_completion_tokens`, and is\nnot compatible with [o-series models](/docs/guides/reasoning).\n" + }) + ), + "n": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([Schema.isFinite(), Schema.isGreaterThanOrEqualTo(1), Schema.isLessThanOrEqualTo(128)], { + "description": + "How many chat completion choices to generate for each input message. Note that you will be charged based on the number of generated tokens across all of the choices. Keep `n` as `1` to minimize costs." + }) + ) + ]) + ), + "prediction": Schema.optionalKey(Schema.Union([ + Schema.Union([PredictionContent], { mode: "oneOf" }).annotate({ + "description": + "Configuration for a [Predicted Output](/docs/guides/predicted-outputs),\nwhich can greatly improve response times when large parts of the model\nresponse are known ahead of time. This is most common when you are\nregenerating a file with only minor changes to most of the content.\n" + }), + Schema.Null + ])), + "seed": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([ + Schema.isFinite(), + Schema.isGreaterThanOrEqualTo(-9223372036854776000), + Schema.isLessThanOrEqualTo(9223372036854776000) + ], { + "description": + "This feature is in Beta.\nIf specified, our system will make a best effort to sample deterministically, such that repeated requests with the same `seed` and parameters should return the same result.\nDeterminism is not guaranteed, and you should refer to the `system_fingerprint` response parameter to monitor changes in the backend.\n" + }) + ) + ]) + ), + "stream_options": Schema.optionalKey(ChatCompletionStreamOptions), + "tools": Schema.optionalKey( + Schema.Array(Schema.Union([ChatCompletionTool, CustomToolChatCompletions], { mode: "oneOf" })).annotate({ + "description": + "A list of tools the model may call. You can provide either\n[custom tools](/docs/guides/function-calling#custom-tools) or\n[function tools](/docs/guides/function-calling).\n" + }) + ), + "tool_choice": Schema.optionalKey(ChatCompletionToolChoiceOption), + "parallel_tool_calls": Schema.optionalKey(ParallelToolCalls), + "function_call": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["none", "auto"]).annotate({ + "description": + "`none` means the model will not call a function and instead generates a message. `auto` means the model can pick between generating a message or calling a function.\n" + }), + ChatCompletionFunctionCallOption + ], { mode: "oneOf" }).annotate({ + "description": + "Deprecated in favor of `tool_choice`.\n\nControls which (if any) function is called by the model.\n\n`none` means the model will not call a function and instead generates a\nmessage.\n\n`auto` means the model can pick between generating a message or calling a\nfunction.\n\nSpecifying a particular function via `{\"name\": \"my_function\"}` forces the\nmodel to call that function.\n\n`none` is the default when no functions are present. `auto` is the default\nif functions are present.\n" + }) + ), + "functions": Schema.optionalKey( + Schema.Array(ChatCompletionFunctions).annotate({ + "description": "Deprecated in favor of `tools`.\n\nA list of functions the model may generate JSON inputs for.\n" + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(128)) + ) +}) +export type ListRunStepsResponse = { + readonly "object": string + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean + readonly [x: string]: unknown +} +export const ListRunStepsResponse = Schema.StructWithRest( + Schema.Struct({ + "object": Schema.String, + "data": Schema.Array(RunStepObject), + "first_id": Schema.String, + "last_id": Schema.String, + "has_more": Schema.Boolean + }), + [Schema.Record(Schema.String, Schema.Json)] +) +export type RunStepStreamEvent = + | { readonly "event": "thread.run.step.created"; readonly "data": RunStepObject } + | { readonly "event": "thread.run.step.in_progress"; readonly "data": RunStepObject } + | { readonly "event": "thread.run.step.delta"; readonly "data": RunStepDeltaObject } + | { readonly "event": "thread.run.step.completed"; readonly "data": RunStepObject } + | { readonly "event": "thread.run.step.failed"; readonly "data": RunStepObject } + | { readonly "event": "thread.run.step.cancelled"; readonly "data": RunStepObject } + | { readonly "event": "thread.run.step.expired"; readonly "data": RunStepObject } +export const RunStepStreamEvent = Schema.Union([ + Schema.Struct({ "event": Schema.Literal("thread.run.step.created"), "data": RunStepObject }).annotate({ + "description": "Occurs when a [run step](/docs/api-reference/run-steps/step-object) is created." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.step.in_progress"), "data": RunStepObject }).annotate({ + "description": + "Occurs when a [run step](/docs/api-reference/run-steps/step-object) moves to an `in_progress` state." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.step.delta"), "data": RunStepDeltaObject }).annotate({ + "description": "Occurs when parts of a [run step](/docs/api-reference/run-steps/step-object) are being streamed." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.step.completed"), "data": RunStepObject }).annotate({ + "description": "Occurs when a [run step](/docs/api-reference/run-steps/step-object) is completed." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.step.failed"), "data": RunStepObject }).annotate({ + "description": "Occurs when a [run step](/docs/api-reference/run-steps/step-object) fails." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.step.cancelled"), "data": RunStepObject }).annotate({ + "description": "Occurs when a [run step](/docs/api-reference/run-steps/step-object) is cancelled." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.step.expired"), "data": RunStepObject }).annotate({ + "description": "Occurs when a [run step](/docs/api-reference/run-steps/step-object) expires." + }) +], { mode: "oneOf" }) +export type RealtimeServerEventResponseCreated = { + readonly "event_id": string + readonly "type": "response.created" + readonly "response": RealtimeResponse +} +export const RealtimeServerEventResponseCreated = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.created").annotate({ "description": "The event type, must be `response.created`." }), + "response": RealtimeResponse +}).annotate({ + "description": + "Returned when a new Response is created. The first event of response creation,\nwhere the response is in an initial state of `in_progress`.\n" +}) +export type RealtimeServerEventResponseDone = { + readonly "event_id": string + readonly "type": "response.done" + readonly "response": RealtimeResponse +} +export const RealtimeServerEventResponseDone = Schema.Struct({ + "event_id": Schema.String.annotate({ "description": "The unique ID of the server event." }), + "type": Schema.Literal("response.done").annotate({ "description": "The event type, must be `response.done`." }), + "response": RealtimeResponse +}).annotate({ + "description": + "Returned when a Response is done streaming. Always emitted, no matter the \nfinal state. The Response object included in the `response.done` event will \ninclude all output Items in the Response but will omit the raw audio data.\n\nClients should check the `status` field of the Response to determine if it was successful\n(`completed`) or if there was another outcome: `cancelled`, `failed`, or `incomplete`.\n\nA response will contain all output items that were generated during the response, excluding\nany audio content.\n" +}) +export type RealtimeClientEventResponseCreate = { + readonly "event_id"?: string + readonly "type": "response.create" + readonly "response"?: RealtimeResponseCreateParams +} +export const RealtimeClientEventResponseCreate = Schema.Struct({ + "event_id": Schema.optionalKey( + Schema.String.annotate({ "description": "Optional client-generated ID used to identify this event." }).check( + Schema.isMaxLength(512) + ) + ), + "type": Schema.Literal("response.create").annotate({ "description": "The event type, must be `response.create`." }), + "response": Schema.optionalKey(RealtimeResponseCreateParams) +}).annotate({ + "description": + "This event instructs the server to create a Response, which means triggering \nmodel inference. When in Server VAD mode, the server will create Responses \nautomatically.\n\nA Response will include at least one Item, and may have two, in which case \nthe second will be a function call. These Items will be appended to the \nconversation history by default.\n\nThe server will respond with a `response.created` event, events for Items \nand content created, and finally a `response.done` event to indicate the \nResponse is complete.\n\nThe `response.create` event includes inference configuration like \n`instructions` and `tools`. If these are set, they will override the Session's \nconfiguration for this Response only.\n\nResponses can be created out-of-band of the default Conversation, meaning that they can\nhave arbitrary input, and it's possible to disable writing the output to the Conversation.\nOnly one Response can write to the default Conversation at a time, but otherwise multiple\nResponses can be created in parallel. The `metadata` field is a good way to disambiguate\nmultiple simultaneous Responses.\n\nClients can set `conversation` to `none` to create a Response that does not write to the default\nConversation. Arbitrary input can be provided with the `input` field, which is an array accepting\nraw Items and references to existing Items.\n" +}) +export type ListAssistantsResponse = { + readonly "object": string + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const ListAssistantsResponse = Schema.Struct({ + "object": Schema.String, + "data": Schema.Array(AssistantObject), + "first_id": Schema.String, + "last_id": Schema.String, + "has_more": Schema.Boolean +}) +export type ListRunsResponse = { + readonly "object": string + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const ListRunsResponse = Schema.Struct({ + "object": Schema.String, + "data": Schema.Array(RunObject), + "first_id": Schema.String, + "last_id": Schema.String, + "has_more": Schema.Boolean +}) +export type RunStreamEvent = + | { readonly "event": "thread.run.created"; readonly "data": RunObject } + | { readonly "event": "thread.run.queued"; readonly "data": RunObject } + | { readonly "event": "thread.run.in_progress"; readonly "data": RunObject } + | { readonly "event": "thread.run.requires_action"; readonly "data": RunObject } + | { readonly "event": "thread.run.completed"; readonly "data": RunObject } + | { readonly "event": "thread.run.incomplete"; readonly "data": RunObject } + | { readonly "event": "thread.run.failed"; readonly "data": RunObject } + | { readonly "event": "thread.run.cancelling"; readonly "data": RunObject } + | { readonly "event": "thread.run.cancelled"; readonly "data": RunObject } + | { readonly "event": "thread.run.expired"; readonly "data": RunObject } +export const RunStreamEvent = Schema.Union([ + Schema.Struct({ "event": Schema.Literal("thread.run.created"), "data": RunObject }).annotate({ + "description": "Occurs when a new [run](/docs/api-reference/runs/object) is created." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.queued"), "data": RunObject }).annotate({ + "description": "Occurs when a [run](/docs/api-reference/runs/object) moves to a `queued` status." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.in_progress"), "data": RunObject }).annotate({ + "description": "Occurs when a [run](/docs/api-reference/runs/object) moves to an `in_progress` status." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.requires_action"), "data": RunObject }).annotate({ + "description": "Occurs when a [run](/docs/api-reference/runs/object) moves to a `requires_action` status." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.completed"), "data": RunObject }).annotate({ + "description": "Occurs when a [run](/docs/api-reference/runs/object) is completed." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.incomplete"), "data": RunObject }).annotate({ + "description": "Occurs when a [run](/docs/api-reference/runs/object) ends with status `incomplete`." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.failed"), "data": RunObject }).annotate({ + "description": "Occurs when a [run](/docs/api-reference/runs/object) fails." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.cancelling"), "data": RunObject }).annotate({ + "description": "Occurs when a [run](/docs/api-reference/runs/object) moves to a `cancelling` status." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.cancelled"), "data": RunObject }).annotate({ + "description": "Occurs when a [run](/docs/api-reference/runs/object) is cancelled." + }), + Schema.Struct({ "event": Schema.Literal("thread.run.expired"), "data": RunObject }).annotate({ + "description": "Occurs when a [run](/docs/api-reference/runs/object) expires." + }) +], { mode: "oneOf" }) +export type Tool = + | FunctionTool + | FileSearchTool + | ComputerTool + | ComputerUsePreviewTool + | WebSearchTool + | MCPTool + | CodeInterpreterTool + | ImageGenTool + | LocalShellToolParam + | FunctionShellToolParam + | CustomToolParam + | NamespaceToolParam + | ToolSearchToolParam + | WebSearchPreviewTool + | ApplyPatchToolParam +export const Tool = Schema.Union([ + FunctionTool, + FileSearchTool, + ComputerTool, + ComputerUsePreviewTool, + WebSearchTool, + MCPTool, + CodeInterpreterTool, + ImageGenTool, + LocalShellToolParam, + FunctionShellToolParam, + CustomToolParam, + NamespaceToolParam, + ToolSearchToolParam, + WebSearchPreviewTool, + ApplyPatchToolParam +], { mode: "oneOf" }).annotate({ "description": "A tool that can be used to generate a response.\n" }) +export type CreateEvalItem = { readonly "role": string; readonly "content": string } | { + readonly "role": "user" | "assistant" | "system" | "developer" + readonly "content": EvalItemContent + readonly "type"?: "message" +} +export const CreateEvalItem = Schema.Union([ + Schema.Struct({ + "role": Schema.String.annotate({ + "description": "The role of the message (e.g. \"system\", \"assistant\", \"user\")." + }), + "content": Schema.String.annotate({ "description": "The content of the message." }) + }).annotate({ + "title": "CreateEvalItem", + "description": + "A chat message that makes up the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}." + }), + Schema.Struct({ + "role": Schema.Literals(["user", "assistant", "system", "developer"]).annotate({ + "description": "The role of the message input. One of `user`, `assistant`, `system`, or\n`developer`.\n" + }), + "content": EvalItemContent, + "type": Schema.optionalKey( + Schema.Literal("message").annotate({ "description": "The type of the message input. Always `message`.\n" }) + ) + }).annotate({ + "title": "CreateEvalItem", + "description": + "A chat message that makes up the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}." + }) +], { mode: "oneOf" }) +export type EvalItem = { + readonly "role": "user" | "assistant" | "system" | "developer" + readonly "content": EvalItemContent + readonly "type"?: "message" +} +export const EvalItem = Schema.Struct({ + "role": Schema.Literals(["user", "assistant", "system", "developer"]).annotate({ + "description": "The role of the message input. One of `user`, `assistant`, `system`, or\n`developer`.\n" + }), + "content": EvalItemContent, + "type": Schema.optionalKey( + Schema.Literal("message").annotate({ "description": "The type of the message input. Always `message`.\n" }) + ) +}).annotate({ + "title": "Eval message object", + "description": + "A message input to the model with a role indicating instruction following\nhierarchy. Instructions given with the `developer` or `system` role take\nprecedence over instructions given with the `user` role. Messages with the\n`assistant` role are presumed to have been generated by the model in previous\ninteractions.\n" +}) +export type OutputMessage = { + readonly "id": string + readonly "type": "message" + readonly "role": "assistant" + readonly "content": ReadonlyArray + readonly "phase"?: MessagePhase | null + readonly "status": "in_progress" | "completed" | "incomplete" +} +export const OutputMessage = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the output message.\n" }), + "type": Schema.Literal("message").annotate({ "description": "The type of the output message. Always `message`.\n" }), + "role": Schema.Literal("assistant").annotate({ + "description": "The role of the output message. Always `assistant`.\n" + }), + "content": Schema.Array(OutputMessageContent).annotate({ "description": "The content of the output message.\n" }), + "phase": Schema.optionalKey(Schema.Union([MessagePhase, Schema.Null])), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n" + }) +}).annotate({ "title": "Output message", "description": "An output message from the model.\n" }) +export type ComputerToolCall = { + readonly "type": "computer_call" + readonly "id": string + readonly "call_id": string + readonly "action"?: ComputerAction + readonly "actions"?: ComputerActionList + readonly "pending_safety_checks": ReadonlyArray + readonly "status": "in_progress" | "completed" | "incomplete" +} +export const ComputerToolCall = Schema.Struct({ + "type": Schema.Literal("computer_call").annotate({ + "description": "The type of the computer call. Always `computer_call`." + }), + "id": Schema.String.annotate({ "description": "The unique ID of the computer call." }), + "call_id": Schema.String.annotate({ + "description": "An identifier used when responding to the tool call with output.\n" + }), + "action": Schema.optionalKey(ComputerAction), + "actions": Schema.optionalKey(ComputerActionList), + "pending_safety_checks": Schema.Array(ComputerCallSafetyCheckParam).annotate({ + "description": "The pending safety checks for the computer call.\n" + }), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) +}).annotate({ + "title": "Computer tool call", + "description": + "A tool call to a computer use tool. See the\n[computer use guide](/docs/guides/tools-computer-use) for more information.\n" +}) +export type ThreadItemListResource = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string | null + readonly "last_id": string | null + readonly "has_more": boolean +} +export const ThreadItemListResource = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The type of object returned, must be `list`." }), + "data": Schema.Array(ThreadItem).annotate({ "description": "A list of items" }), + "first_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the first item in the list." }), + Schema.Null + ]), + "last_id": Schema.Union([ + Schema.String.annotate({ "description": "The ID of the last item in the list." }), + Schema.Null + ]), + "has_more": Schema.Boolean.annotate({ "description": "Whether there are more items available." }) +}).annotate({ + "title": "Thread Items", + "description": "A paginated list of thread items rendered for the ChatKit API." +}) +export type InputItem = + | EasyInputMessage + | { + readonly "type"?: "message" + readonly "role": "user" | "system" | "developer" + readonly "status"?: "in_progress" | "completed" | "incomplete" + readonly "content": InputMessageContentList + } + | { + readonly "id": string + readonly "type": "message" + readonly "role": "assistant" + readonly "content": ReadonlyArray + readonly "phase"?: MessagePhase | null + readonly "status": "in_progress" | "completed" | "incomplete" + } + | { + readonly "id": string + readonly "type": "file_search_call" + readonly "status": "in_progress" | "searching" | "completed" | "incomplete" | "failed" + readonly "queries": ReadonlyArray + readonly "results"?: + | ReadonlyArray< + { + readonly "file_id"?: string + readonly "text"?: string + readonly "filename"?: string + readonly "attributes"?: VectorStoreFileAttributes + readonly "score"?: number + } + > + | null + } + | { + readonly "type": "computer_call" + readonly "id": string + readonly "call_id": string + readonly "action"?: ComputerAction + readonly "actions"?: ComputerActionList + readonly "pending_safety_checks": ReadonlyArray + readonly "status": "in_progress" | "completed" | "incomplete" + } + | { + readonly "id"?: string | null + readonly "call_id": string + readonly "type": "computer_call_output" + readonly "output": ComputerScreenshotImage + readonly "acknowledged_safety_checks"?: ReadonlyArray | null + readonly "status"?: "in_progress" | "completed" | "incomplete" | null + } + | { + readonly "id": string + readonly "type": "web_search_call" + readonly "status": "in_progress" | "searching" | "completed" | "failed" + readonly "action": + | { + readonly "type": "search" + readonly "query"?: string + readonly "queries"?: ReadonlyArray + readonly "sources"?: ReadonlyArray<{ readonly "type": "url"; readonly "url": string }> + } + | { readonly "type": "open_page"; readonly "url"?: string | null } + | { readonly "type": "find_in_page"; readonly "url": string; readonly "pattern": string } + } + | { + readonly "id"?: string + readonly "type": "function_call" + readonly "call_id": string + readonly "namespace"?: string + readonly "name": string + readonly "arguments": string + readonly "status"?: "in_progress" | "completed" | "incomplete" + } + | { + readonly "id"?: string | null + readonly "call_id": string + readonly "type": "function_call_output" + readonly "output": + | string + | ReadonlyArray + readonly "status"?: "in_progress" | "completed" | "incomplete" | null + } + | { + readonly "id"?: string | null + readonly "call_id"?: string | null + readonly "type": "tool_search_call" + readonly "execution"?: "server" | "client" + readonly "arguments": {} + readonly "status"?: "in_progress" | "completed" | "incomplete" | null + } + | { + readonly "id"?: string | null + readonly "call_id"?: string | null + readonly "type": "tool_search_output" + readonly "execution"?: "server" | "client" + readonly "tools": ReadonlyArray + readonly "status"?: "in_progress" | "completed" | "incomplete" | null + } + | { + readonly "type": "reasoning" + readonly "id": string + readonly "encrypted_content"?: string | null + readonly "summary": ReadonlyArray + readonly "content"?: ReadonlyArray + readonly "status"?: "in_progress" | "completed" | "incomplete" + } + | { readonly "id"?: string | null; readonly "type": "compaction"; readonly "encrypted_content": string } + | { + readonly "type": "image_generation_call" + readonly "id": string + readonly "status": "in_progress" | "completed" | "generating" | "failed" + readonly "result": string | null + } + | { + readonly "type": "code_interpreter_call" + readonly "id": string + readonly "status": "in_progress" | "completed" | "incomplete" | "interpreting" | "failed" + readonly "container_id": string + readonly "code": string | null + readonly "outputs": ReadonlyArray | null + } + | { + readonly "type": "local_shell_call" + readonly "id": string + readonly "call_id": string + readonly "action": LocalShellExecAction + readonly "status": "in_progress" | "completed" | "incomplete" + } + | { + readonly "type": "local_shell_call_output" + readonly "id": string + readonly "output": string + readonly "status"?: "in_progress" | "completed" | "incomplete" | null + readonly "call_id": unknown + } + | { + readonly "id"?: string | null + readonly "call_id": string + readonly "type": "shell_call" + readonly "action": { + readonly "commands": ReadonlyArray + readonly "timeout_ms"?: number | null + readonly "max_output_length"?: number | null + } + readonly "status"?: "in_progress" | "completed" | "incomplete" | null + readonly "environment"?: LocalEnvironmentParam | ContainerReferenceParam | null + } + | { + readonly "id"?: string | null + readonly "call_id": string + readonly "type": "shell_call_output" + readonly "output": ReadonlyArray + readonly "status"?: "in_progress" | "completed" | "incomplete" | null + readonly "max_output_length"?: number | null + } + | { + readonly "type": "apply_patch_call" + readonly "id"?: string | null + readonly "call_id": string + readonly "status": "in_progress" | "completed" + readonly "operation": + | ApplyPatchCreateFileOperationParam + | ApplyPatchDeleteFileOperationParam + | ApplyPatchUpdateFileOperationParam + } + | { + readonly "type": "apply_patch_call_output" + readonly "id"?: string | null + readonly "call_id": string + readonly "status": "completed" | "failed" + readonly "output"?: string | null + } + | { + readonly "type": "mcp_list_tools" + readonly "id": string + readonly "server_label": string + readonly "tools": ReadonlyArray + readonly "error"?: string | null + } + | { + readonly "type": "mcp_approval_request" + readonly "id": string + readonly "server_label": string + readonly "name": string + readonly "arguments": string + } + | { + readonly "type": "mcp_approval_response" + readonly "id"?: string | null + readonly "approval_request_id": string + readonly "approve": boolean + readonly "reason"?: string | null + readonly "request_id": unknown + } + | { + readonly "type": "mcp_call" + readonly "id": string + readonly "server_label": string + readonly "name": string + readonly "arguments": string + readonly "output"?: string | null + readonly "error"?: string | null + readonly "status"?: "in_progress" | "completed" | "incomplete" | "calling" | "failed" + readonly "approval_request_id"?: string | null + } + | { + readonly "type": "custom_tool_call_output" + readonly "id"?: string + readonly "call_id": string + readonly "output": string | ReadonlyArray + } + | { + readonly "type": "custom_tool_call" + readonly "id"?: string + readonly "call_id": string + readonly "namespace"?: string + readonly "name": string + readonly "input": string + } + | CompactionTriggerItemParam + | ItemReferenceParam +export const InputItem = Schema.Union([ + EasyInputMessage, + Schema.Union([ + Schema.Struct({ + "type": Schema.optionalKey( + Schema.Literal("message").annotate({ + "description": "The type of the message input. Always set to `message`.\n" + }) + ), + "role": Schema.Literals(["user", "system", "developer"]).annotate({ + "description": "The role of the message input. One of `user`, `system`, or `developer`.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + ), + "content": InputMessageContentList + }).annotate({ "title": "Input message", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the output message.\n" }), + "type": Schema.Literal("message").annotate({ + "description": "The type of the output message. Always `message`.\n" + }), + "role": Schema.Literal("assistant").annotate({ + "description": "The role of the output message. Always `assistant`.\n" + }), + "content": Schema.Array(OutputMessageContent).annotate({ "description": "The content of the output message.\n" }), + "phase": Schema.optionalKey(Schema.Union([MessagePhase, Schema.Null])), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the message input. One of `in_progress`, `completed`, or\n`incomplete`. Populated when input items are returned via API.\n" + }) + }).annotate({ "title": "Output message", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the file search tool call.\n" }), + "type": Schema.Literal("file_search_call").annotate({ + "description": "The type of the file search tool call. Always `file_search_call`.\n" + }), + "status": Schema.Literals(["in_progress", "searching", "completed", "incomplete", "failed"]).annotate({ + "description": + "The status of the file search tool call. One of `in_progress`,\n`searching`, `incomplete` or `failed`,\n" + }), + "queries": Schema.Array(Schema.String).annotate({ "description": "The queries used to search for files.\n" }), + "results": Schema.optionalKey(Schema.Union([ + Schema.Array(Schema.Struct({ + "file_id": Schema.optionalKey(Schema.String.annotate({ "description": "The unique ID of the file.\n" })), + "text": Schema.optionalKey( + Schema.String.annotate({ "description": "The text that was retrieved from the file.\n" }) + ), + "filename": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the file.\n" })), + "attributes": Schema.optionalKey(VectorStoreFileAttributes), + "score": Schema.optionalKey( + Schema.Number.annotate({ + "description": "The relevance score of the file - a value between 0 and 1.\n", + "format": "float" + }).check(Schema.isFinite()) + ) + })).annotate({ "description": "The results of the file search tool call.\n" }), + Schema.Null + ])) + }).annotate({ "title": "File search tool call", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("computer_call").annotate({ + "description": "The type of the computer call. Always `computer_call`." + }), + "id": Schema.String.annotate({ "description": "The unique ID of the computer call." }), + "call_id": Schema.String.annotate({ + "description": "An identifier used when responding to the tool call with output.\n" + }), + "action": Schema.optionalKey(ComputerAction), + "actions": Schema.optionalKey(ComputerActionList), + "pending_safety_checks": Schema.Array(ComputerCallSafetyCheckParam).annotate({ + "description": "The pending safety checks for the computer call.\n" + }), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + }).annotate({ "title": "Computer tool call", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The ID of the computer tool call output." }), + Schema.Null + ]) + ), + "call_id": Schema.String.annotate({ "description": "The ID of the computer tool call that produced the output." }) + .check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)), + "type": Schema.Literal("computer_call_output").annotate({ + "description": "The type of the computer tool call output. Always `computer_call_output`." + }), + "output": ComputerScreenshotImage, + "acknowledged_safety_checks": Schema.optionalKey( + Schema.Union([ + Schema.Array(ComputerCallSafetyCheckParam).annotate({ + "description": "The safety checks reported by the API that have been acknowledged by the developer." + }), + Schema.Null + ]) + ), + "status": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API." + }), + Schema.Null + ]) + ) + }).annotate({ "title": "Computer tool call output", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique ID of the web search tool call.\n" }), + "type": Schema.Literal("web_search_call").annotate({ + "description": "The type of the web search tool call. Always `web_search_call`.\n" + }), + "status": Schema.Literals(["in_progress", "searching", "completed", "failed"]).annotate({ + "description": "The status of the web search tool call.\n" + }), + "action": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("search").annotate({ "description": "The action type.\n" }), + "query": Schema.optionalKey(Schema.String.annotate({ "description": "[DEPRECATED] The search query.\n" })), + "queries": Schema.optionalKey( + Schema.Array(Schema.String.annotate({ "description": "A search query.\n" })).annotate({ + "title": "Search queries", + "description": "The search queries.\n" + }) + ), + "sources": Schema.optionalKey( + Schema.Array( + Schema.Struct({ + "type": Schema.Literal("url").annotate({ "description": "The type of source. Always `url`.\n" }), + "url": Schema.String.annotate({ "description": "The URL of the source.\n", "format": "uri" }) + }).annotate({ "title": "Web search source", "description": "A source used in the search.\n" }) + ).annotate({ "title": "Web search sources", "description": "The sources used in the search.\n" }) + ) + }).annotate({ + "title": "Search action", + "description": + "An object describing the specific action taken in this web search call.\nIncludes details on how the model used the web (search, open_page, find_in_page).\n" + }), + Schema.Struct({ + "type": Schema.Literal("open_page").annotate({ "description": "The action type. Always `open_page`.\n" }), + "url": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "format": "uri" }), Schema.Null]).annotate({ + "description": "The URL opened by the model.\n" + }) + ) + }).annotate({ + "title": "Open page action", + "description": + "An object describing the specific action taken in this web search call.\nIncludes details on how the model used the web (search, open_page, find_in_page).\n" + }), + Schema.Struct({ + "type": Schema.Literal("find_in_page").annotate({ "description": "The action type.\n" }), + "url": Schema.String.annotate({ + "description": "The URL of the page searched for the pattern.\n", + "format": "uri" + }), + "pattern": Schema.String.annotate({ "description": "The pattern or text to search for within the page.\n" }) + }).annotate({ + "title": "Find action", + "description": + "An object describing the specific action taken in this web search call.\nIncludes details on how the model used the web (search, open_page, find_in_page).\n" + }) + ], { mode: "oneOf" }) + }).annotate({ "title": "Web search tool call", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.optionalKey(Schema.String.annotate({ "description": "The unique ID of the function tool call.\n" })), + "type": Schema.Literal("function_call").annotate({ + "description": "The type of the function tool call. Always `function_call`.\n" + }), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the function tool call generated by the model.\n" + }), + "namespace": Schema.optionalKey( + Schema.String.annotate({ "description": "The namespace of the function to run.\n" }) + ), + "name": Schema.String.annotate({ "description": "The name of the function to run.\n" }), + "arguments": Schema.String.annotate({ + "description": "A JSON string of the arguments to pass to the function.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + ) + }).annotate({ "title": "Function tool call", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the function tool call output. Populated when this item is returned via API." + }), + Schema.Null + ]) + ), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the function tool call generated by the model." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)), + "type": Schema.Literal("function_call_output").annotate({ + "description": "The type of the function tool call output. Always `function_call_output`." + }), + "output": Schema.Union([ + Schema.String.annotate({ "description": "A JSON string of the output of the function tool call." }).check( + Schema.isMaxLength(10485760) + ), + Schema.Array( + Schema.Union([InputTextContentParam, InputImageContentParamAutoParam, InputFileContentParam], { + mode: "oneOf" + }).annotate({ "description": "A piece of message content, such as text, an image, or a file." }) + ).annotate({ "description": "An array of content outputs (text, image, file) for the function tool call." }) + ], { mode: "oneOf" }).annotate({ "description": "Text, image, or file output of the function tool call." }), + "status": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API." + }), + Schema.Null + ]) + ) + }).annotate({ "title": "Function tool call output", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The unique ID of this tool search call." }), + Schema.Null + ]) + ), + "call_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The unique ID of the tool search call generated by the model." }) + .check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)), + Schema.Null + ]) + ), + "type": Schema.Literal("tool_search_call").annotate({ + "description": "The item type. Always `tool_search_call`." + }), + "execution": Schema.optionalKey( + Schema.Literals(["server", "client"]).annotate({ + "description": "Whether tool search was executed by the server or by the client." + }) + ), + "arguments": Schema.Struct({}).annotate({ "description": "The arguments supplied to the tool search call." }), + "status": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the tool search call." + }), + Schema.Null + ]) + ) + }).annotate({ "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The unique ID of this tool search output." }), + Schema.Null + ]) + ), + "call_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The unique ID of the tool search call generated by the model." }) + .check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)), + Schema.Null + ]) + ), + "type": Schema.Literal("tool_search_output").annotate({ + "description": "The item type. Always `tool_search_output`." + }), + "execution": Schema.optionalKey( + Schema.Literals(["server", "client"]).annotate({ + "description": "Whether tool search was executed by the server or by the client." + }) + ), + "tools": Schema.Array(Tool).annotate({ + "description": "The loaded tool definitions returned by the tool search output." + }), + "status": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the tool search output." + }), + Schema.Null + ]) + ) + }).annotate({ "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("reasoning").annotate({ "description": "The type of the object. Always `reasoning`.\n" }), + "id": Schema.String.annotate({ "description": "The unique identifier of the reasoning content.\n" }), + "encrypted_content": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The encrypted content of the reasoning item - populated when a response is\ngenerated with `reasoning.encrypted_content` in the `include` parameter.\n" + }), + Schema.Null + ]) + ), + "summary": Schema.Array(SummaryTextContent).annotate({ "description": "Reasoning summary content.\n" }), + "content": Schema.optionalKey( + Schema.Array(ReasoningTextContent).annotate({ "description": "Reasoning text content.\n" }) + ), + "status": Schema.optionalKey( + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": + "The status of the item. One of `in_progress`, `completed`, or\n`incomplete`. Populated when items are returned via API.\n" + }) + ) + }).annotate({ "title": "Reasoning", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "The ID of the compaction item." }), Schema.Null]) + ), + "type": Schema.Literal("compaction").annotate({ "description": "The type of the item. Always `compaction`." }), + "encrypted_content": Schema.String.annotate({ "description": "The encrypted content of the compaction summary." }) + .check(Schema.isMaxLength(10485760)) + }).annotate({ "title": "Compaction item", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("image_generation_call").annotate({ + "description": "The type of the image generation call. Always `image_generation_call`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the image generation call.\n" }), + "status": Schema.Literals(["in_progress", "completed", "generating", "failed"]).annotate({ + "description": "The status of the image generation call.\n" + }), + "result": Schema.Union([ + Schema.String.annotate({ "description": "The generated image encoded in base64.\n" }), + Schema.Null + ]) + }).annotate({ "title": "Image generation call", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("code_interpreter_call").annotate({ + "description": "The type of the code interpreter tool call. Always `code_interpreter_call`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the code interpreter tool call.\n" }), + "status": Schema.Literals(["in_progress", "completed", "incomplete", "interpreting", "failed"]).annotate({ + "description": + "The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`.\n" + }), + "container_id": Schema.String.annotate({ "description": "The ID of the container used to run the code.\n" }), + "code": Schema.Union([ + Schema.String.annotate({ "description": "The code to run, or null if not available.\n" }), + Schema.Null + ]), + "outputs": Schema.Union([ + Schema.Array(Schema.Union([CodeInterpreterOutputLogs, CodeInterpreterOutputImage], { mode: "oneOf" })).annotate( + { + "description": + "The outputs generated by the code interpreter, such as logs or images.\nCan be null if no outputs are available.\n" + } + ), + Schema.Null + ]) + }).annotate({ + "title": "Code interpreter tool call", + "description": "Content item used to generate a response.\n" + }), + Schema.Struct({ + "type": Schema.Literal("local_shell_call").annotate({ + "description": "The type of the local shell call. Always `local_shell_call`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the local shell call.\n" }), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the local shell tool call generated by the model.\n" + }), + "action": LocalShellExecAction, + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the local shell call.\n" + }) + }).annotate({ "title": "Local shell call", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("local_shell_call_output").annotate({ + "description": "The type of the local shell tool call output. Always `local_shell_call_output`.\n" + }), + "id": Schema.String.annotate({ + "description": "The unique ID of the local shell tool call generated by the model.\n" + }), + "output": Schema.String.annotate({ + "description": "A JSON string of the output of the local shell tool call.\n" + }), + "status": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the item. One of `in_progress`, `completed`, or `incomplete`.\n" + }), + Schema.Null + ]) + ), + "call_id": Schema.Unknown + }).annotate({ "title": "Local shell call output", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "The unique ID of the shell tool call. Populated when this item is returned via API." + }), + Schema.Null + ]) + ), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the shell tool call generated by the model." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)), + "type": Schema.Literal("shell_call").annotate({ "description": "The type of the item. Always `shell_call`." }), + "action": Schema.Struct({ + "commands": Schema.Array(Schema.String).annotate({ + "description": "Ordered shell commands for the execution environment to run." + }), + "timeout_ms": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "Maximum wall-clock time in milliseconds to allow the shell commands to run." + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "max_output_length": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "Maximum number of UTF-8 characters to capture from combined stdout and stderr output." + }).check(Schema.isInt()), + Schema.Null + ]) + ) + }).annotate({ + "title": "Shell action", + "description": "The shell commands and limits that describe how to run the tool call." + }), + "status": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "title": "Shell call status", + "description": "The status of the shell call. One of `in_progress`, `completed`, or `incomplete`." + }), + Schema.Null + ]) + ), + "environment": Schema.optionalKey( + Schema.Union([ + Schema.Union([LocalEnvironmentParam, ContainerReferenceParam], { mode: "oneOf" }).annotate({ + "description": "The environment to execute the shell commands in." + }), + Schema.Null + ]) + ) + }).annotate({ "title": "Shell tool call", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "The unique ID of the shell tool call output. Populated when this item is returned via API." + }), + Schema.Null + ]) + ), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the shell tool call generated by the model." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)), + "type": Schema.Literal("shell_call_output").annotate({ + "description": "The type of the item. Always `shell_call_output`." + }), + "output": Schema.Array(FunctionShellCallOutputContentParam).annotate({ + "description": "Captured chunks of stdout and stderr output, along with their associated outcomes." + }), + "status": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "title": "Shell call status", + "description": "The status of the shell call output." + }), + Schema.Null + ]) + ), + "max_output_length": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The maximum number of UTF-8 characters captured for this shell call's combined output." + }).check(Schema.isInt()), + Schema.Null + ]) + ) + }).annotate({ "title": "Shell tool call output", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("apply_patch_call").annotate({ + "description": "The type of the item. Always `apply_patch_call`." + }), + "id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "The unique ID of the apply patch tool call. Populated when this item is returned via API." + }), + Schema.Null + ]) + ), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the apply patch tool call generated by the model." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)), + "status": Schema.Literals(["in_progress", "completed"]).annotate({ + "title": "Apply patch call status", + "description": "The status of the apply patch tool call. One of `in_progress` or `completed`." + }), + "operation": Schema.Union([ + ApplyPatchCreateFileOperationParam, + ApplyPatchDeleteFileOperationParam, + ApplyPatchUpdateFileOperationParam + ], { mode: "oneOf" }).annotate({ + "title": "Apply patch operation", + "description": "The specific create, delete, or update instruction for the apply_patch tool call." + }) + }).annotate({ "title": "Apply patch tool call", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("apply_patch_call_output").annotate({ + "description": "The type of the item. Always `apply_patch_call_output`." + }), + "id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the apply patch tool call output. Populated when this item is returned via API." + }), + Schema.Null + ]) + ), + "call_id": Schema.String.annotate({ + "description": "The unique ID of the apply patch tool call generated by the model." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(64)), + "status": Schema.Literals(["completed", "failed"]).annotate({ + "title": "Apply patch call output status", + "description": "The status of the apply patch tool call output. One of `completed` or `failed`." + }), + "output": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": "Optional human-readable log text from the apply patch tool (e.g., patch results or errors)." + }).check(Schema.isMaxLength(10485760)), + Schema.Null + ]) + ) + }).annotate({ + "title": "Apply patch tool call output", + "description": "Content item used to generate a response.\n" + }), + Schema.Struct({ + "type": Schema.Literal("mcp_list_tools").annotate({ + "description": "The type of the item. Always `mcp_list_tools`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the list.\n" }), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server.\n" }), + "tools": Schema.Array(MCPListToolsTool).annotate({ "description": "The tools available on the server.\n" }), + "error": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "Error message if the server could not list tools.\n" }), + Schema.Null + ]) + ) + }).annotate({ "title": "MCP list tools", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("mcp_approval_request").annotate({ + "description": "The type of the item. Always `mcp_approval_request`.\n" + }), + "id": Schema.String.annotate({ "description": "The unique ID of the approval request.\n" }), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server making the request.\n" }), + "name": Schema.String.annotate({ "description": "The name of the tool to run.\n" }), + "arguments": Schema.String.annotate({ "description": "A JSON string of arguments for the tool.\n" }) + }).annotate({ "title": "MCP approval request", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("mcp_approval_response").annotate({ + "description": "The type of the item. Always `mcp_approval_response`.\n" + }), + "id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The unique ID of the approval response\n" }), + Schema.Null + ]) + ), + "approval_request_id": Schema.String.annotate({ + "description": "The ID of the approval request being answered.\n" + }), + "approve": Schema.Boolean.annotate({ "description": "Whether the request was approved.\n" }), + "reason": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "Optional reason for the decision.\n" }), Schema.Null]) + ), + "request_id": Schema.Unknown + }).annotate({ "title": "MCP approval response", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("mcp_call").annotate({ "description": "The type of the item. Always `mcp_call`.\n" }), + "id": Schema.String.annotate({ "description": "The unique ID of the tool call.\n" }), + "server_label": Schema.String.annotate({ "description": "The label of the MCP server running the tool.\n" }), + "name": Schema.String.annotate({ "description": "The name of the tool that was run.\n" }), + "arguments": Schema.String.annotate({ "description": "A JSON string of the arguments passed to the tool.\n" }), + "output": Schema.optionalKey( + Schema.Union([Schema.String.annotate({ "description": "The output from the tool call.\n" }), Schema.Null]) + ), + "error": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "The error from the tool call, if any.\n" }), + Schema.Null + ]) + ), + "status": Schema.optionalKey( + Schema.Literals(["in_progress", "completed", "incomplete", "calling", "failed"]).annotate({ + "description": + "The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or `failed`.\n" + }) + ), + "approval_request_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "Unique identifier for the MCP tool call approval request.\nInclude this value in a subsequent `mcp_approval_response` input to approve or reject the corresponding tool call.\n" + }), + Schema.Null + ]) + ) + }).annotate({ "title": "MCP tool call", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("custom_tool_call_output").annotate({ + "description": "The type of the custom tool call output. Always `custom_tool_call_output`.\n" + }), + "id": Schema.optionalKey( + Schema.String.annotate({ + "description": "The unique ID of the custom tool call output in the OpenAI platform.\n" + }) + ), + "call_id": Schema.String.annotate({ + "description": "The call ID, used to map this custom tool call output to a custom tool call.\n" + }), + "output": Schema.Union([ + Schema.String.annotate({ + "title": "string output", + "description": "A string of the output of the custom tool call.\n" + }), + Schema.Array(FunctionAndCustomToolCallOutput).annotate({ + "title": "output content list", + "description": "Text, image, or file output of the custom tool call.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "The output from the custom tool call generated by your code.\nCan be a string or an list of output content.\n" + }) + }).annotate({ "title": "Custom tool call output", "description": "Content item used to generate a response.\n" }), + Schema.Struct({ + "type": Schema.Literal("custom_tool_call").annotate({ + "description": "The type of the custom tool call. Always `custom_tool_call`.\n" + }), + "id": Schema.optionalKey( + Schema.String.annotate({ "description": "The unique ID of the custom tool call in the OpenAI platform.\n" }) + ), + "call_id": Schema.String.annotate({ + "description": "An identifier used to map this custom tool call to a tool call output.\n" + }), + "namespace": Schema.optionalKey( + Schema.String.annotate({ "description": "The namespace of the custom tool being called.\n" }) + ), + "name": Schema.String.annotate({ "description": "The name of the custom tool being called.\n" }), + "input": Schema.String.annotate({ "description": "The input for the custom tool call generated by the model.\n" }) + }).annotate({ "title": "Custom tool call", "description": "Content item used to generate a response.\n" }) + ], { mode: "oneOf" }).annotate({ + "title": "Item", + "description": + "An item representing part of the context for the response to be\ngenerated by the model. Can contain text, images, and audio inputs,\nas well as previous assistant responses and tool call outputs.\n" + }), + CompactionTriggerItemParam, + ItemReferenceParam +], { mode: "oneOf" }) +export type ToolsArray = ReadonlyArray +export const ToolsArray = Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" +}) +export type ToolSearchOutput = { + readonly "type": "tool_search_output" + readonly "id": string + readonly "call_id": string | null + readonly "execution": "server" | "client" + readonly "tools": ReadonlyArray + readonly "status": "in_progress" | "completed" | "incomplete" + readonly "created_by"?: string +} +export const ToolSearchOutput = Schema.Struct({ + "type": Schema.Literal("tool_search_output").annotate({ + "description": "The type of the item. Always `tool_search_output`." + }), + "id": Schema.String.annotate({ "description": "The unique ID of the tool search output item." }), + "call_id": Schema.Union([ + Schema.String.annotate({ "description": "The unique ID of the tool search call generated by the model." }), + Schema.Null + ]), + "execution": Schema.Literals(["server", "client"]).annotate({ + "description": "Whether tool search was executed by the server or by the client." + }), + "tools": Schema.Array(Tool).annotate({ "description": "The loaded tool definitions returned by tool search." }), + "status": Schema.Literals(["in_progress", "completed", "incomplete"]).annotate({ + "description": "The status of the tool search output item that was recorded." + }), + "created_by": Schema.optionalKey( + Schema.String.annotate({ "description": "The identifier of the actor that created the item." }) + ) +}) +export type CreateEvalLabelModelGrader = { + readonly "type": "label_model" + readonly "name": string + readonly "model": string + readonly "input": ReadonlyArray + readonly "labels": ReadonlyArray + readonly "passing_labels": ReadonlyArray +} +export const CreateEvalLabelModelGrader = Schema.Struct({ + "type": Schema.Literal("label_model").annotate({ "description": "The object type, which is always `label_model`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "model": Schema.String.annotate({ + "description": "The model to use for the evaluation. Must support structured outputs." + }), + "input": Schema.Array(CreateEvalItem).annotate({ + "description": + "A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}." + }), + "labels": Schema.Array(Schema.String).annotate({ + "description": "The labels to classify to each item in the evaluation." + }), + "passing_labels": Schema.Array(Schema.String).annotate({ + "description": "The labels that indicate a passing result. Must be a subset of labels." + }) +}).annotate({ + "title": "LabelModelGrader", + "description": "A LabelModelGrader object which uses a model to assign labels to each item\nin the evaluation.\n" +}) +export type CreateEvalRunRequest = { + readonly "name"?: string + readonly "metadata"?: Metadata + readonly "data_source": { + readonly "type": "jsonl" + readonly "source": EvalJsonlFileContentSource | EvalJsonlFileIdSource + } | { + readonly "type": "completions" + readonly "input_messages"?: { + readonly "type": "template" + readonly "template": ReadonlyArray + } | { readonly "type": "item_reference"; readonly "item_reference": string } + readonly "sampling_params"?: { + readonly "reasoning_effort"?: ReasoningEffort + readonly "temperature"?: number + readonly "max_completion_tokens"?: number + readonly "top_p"?: number + readonly "seed"?: number + readonly "response_format"?: ResponseFormatText | ResponseFormatJsonSchema | ResponseFormatJsonObject + readonly "tools"?: ReadonlyArray + } + readonly "model"?: string + readonly "source": EvalJsonlFileContentSource | EvalJsonlFileIdSource | EvalStoredCompletionsSource + } | { + readonly "type": "responses" + readonly "input_messages"?: { + readonly "type": "template" + readonly "template": ReadonlyArray<{ readonly "role": string; readonly "content": string } | EvalItem> + } | { readonly "type": "item_reference"; readonly "item_reference": string } + readonly "sampling_params"?: { + readonly "reasoning_effort"?: ReasoningEffort + readonly "temperature"?: number + readonly "max_completion_tokens"?: number + readonly "top_p"?: number + readonly "seed"?: number + readonly "tools"?: ReadonlyArray + readonly "text"?: { readonly "format"?: TextResponseFormatConfiguration } + } + readonly "model"?: string + readonly "source": EvalJsonlFileContentSource | EvalJsonlFileIdSource | EvalResponsesSource + } +} +export const CreateEvalRunRequest = Schema.Struct({ + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the run." })), + "metadata": Schema.optionalKey(Metadata), + "data_source": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("jsonl").annotate({ "description": "The type of data source. Always `jsonl`." }), + "source": Schema.Union([EvalJsonlFileContentSource, EvalJsonlFileIdSource], { mode: "oneOf" }).annotate({ + "description": "Determines what populates the `item` namespace in the data source." + }) + }).annotate({ "title": "JsonlRunDataSource", "description": "Details about the run's data source." }), + Schema.Struct({ + "type": Schema.Literal("completions").annotate({ + "description": "The type of run data source. Always `completions`." + }), + "input_messages": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("template").annotate({ + "description": "The type of input messages. Always `template`." + }), + "template": Schema.Array(Schema.Union([EasyInputMessage, EvalItem], { mode: "oneOf" })).annotate({ + "description": + "A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}." + }) + }).annotate({ "title": "TemplateInputMessages" }), + Schema.Struct({ + "type": Schema.Literal("item_reference").annotate({ + "description": "The type of input messages. Always `item_reference`." + }), + "item_reference": Schema.String.annotate({ + "description": "A reference to a variable in the `item` namespace. Ie, \"item.input_trajectory\"" + }) + }).annotate({ "title": "ItemReferenceInputMessages" }) + ], { mode: "oneOf" }).annotate({ + "description": + "Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace." + }) + ), + "sampling_params": Schema.optionalKey(Schema.Struct({ + "reasoning_effort": Schema.optionalKey(ReasoningEffort), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs." }).check( + Schema.isFinite() + ) + ), + "max_completion_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum number of tokens in the generated output." }).check( + Schema.isInt() + ) + ), + "top_p": Schema.optionalKey( + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens." + }).check(Schema.isFinite()) + ), + "seed": Schema.optionalKey( + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling." }) + .check(Schema.isInt()) + ), + "response_format": Schema.optionalKey( + Schema.Union([ResponseFormatText, ResponseFormatJsonSchema, ResponseFormatJsonObject], { mode: "oneOf" }) + .annotate({ + "description": + "An object specifying the format that the model must output.\n\nSetting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables\nStructured Outputs which ensures the model will match your supplied JSON\nschema. Learn more in the [Structured Outputs\nguide](/docs/guides/structured-outputs).\n\nSetting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n" + }) + ), + "tools": Schema.optionalKey( + Schema.Array(ChatCompletionTool).annotate({ + "description": + "A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.\n" + }) + ) + })), + "model": Schema.optionalKey( + Schema.String.annotate({ + "description": "The name of the model to use for generating completions (e.g. \"o3-mini\")." + }) + ), + "source": Schema.Union([EvalJsonlFileContentSource, EvalJsonlFileIdSource, EvalStoredCompletionsSource], { + mode: "oneOf" + }).annotate({ "description": "Determines what populates the `item` namespace in this run's data source." }) + }).annotate({ "title": "CompletionsRunDataSource", "description": "Details about the run's data source." }), + Schema.Struct({ + "type": Schema.Literal("responses").annotate({ + "description": "The type of run data source. Always `responses`." + }), + "input_messages": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("template").annotate({ + "description": "The type of input messages. Always `template`." + }), + "template": Schema.Array( + Schema.Union([ + Schema.Struct({ + "role": Schema.String.annotate({ + "description": "The role of the message (e.g. \"system\", \"assistant\", \"user\")." + }), + "content": Schema.String.annotate({ "description": "The content of the message." }) + }).annotate({ "title": "ChatMessage" }), + EvalItem + ], { mode: "oneOf" }) + ).annotate({ + "description": + "A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}." + }) + }).annotate({ "title": "InputMessagesTemplate" }), + Schema.Struct({ + "type": Schema.Literal("item_reference").annotate({ + "description": "The type of input messages. Always `item_reference`." + }), + "item_reference": Schema.String.annotate({ + "description": "A reference to a variable in the `item` namespace. Ie, \"item.name\"" + }) + }).annotate({ "title": "InputMessagesItemReference" }) + ], { mode: "oneOf" }).annotate({ + "description": + "Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace." + }) + ), + "sampling_params": Schema.optionalKey(Schema.Struct({ + "reasoning_effort": Schema.optionalKey(ReasoningEffort), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs." }).check( + Schema.isFinite() + ) + ), + "max_completion_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum number of tokens in the generated output." }).check( + Schema.isInt() + ) + ), + "top_p": Schema.optionalKey( + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens." + }).check(Schema.isFinite()) + ), + "seed": Schema.optionalKey( + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling." }) + .check(Schema.isInt()) + ), + "tools": Schema.optionalKey( + Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nThe two categories of tools you can provide the model are:\n\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code. Learn more about\n [function calling](/docs/guides/function-calling).\n" + }) + ), + "text": Schema.optionalKey( + Schema.Struct({ "format": Schema.optionalKey(TextResponseFormatConfiguration) }).annotate({ + "description": + "Configuration options for a text response from the model. Can be plain\ntext or structured JSON data. Learn more:\n- [Text inputs and outputs](/docs/guides/text)\n- [Structured Outputs](/docs/guides/structured-outputs)\n" + }) + ) + })), + "model": Schema.optionalKey( + Schema.String.annotate({ + "description": "The name of the model to use for generating completions (e.g. \"o3-mini\")." + }) + ), + "source": Schema.Union([EvalJsonlFileContentSource, EvalJsonlFileIdSource, EvalResponsesSource], { + mode: "oneOf" + }).annotate({ "description": "Determines what populates the `item` namespace in this run's data source." }) + }).annotate({ "title": "ResponsesRunDataSource", "description": "Details about the run's data source." }) + ], { mode: "oneOf" }) +}).annotate({ "title": "CreateEvalRunRequest" }) +export type EvalGraderLabelModel = { + readonly "type": "label_model" + readonly "name": string + readonly "model": string + readonly "input": ReadonlyArray + readonly "labels": ReadonlyArray + readonly "passing_labels": ReadonlyArray +} +export const EvalGraderLabelModel = Schema.Struct({ + "type": Schema.Literal("label_model").annotate({ "description": "The object type, which is always `label_model`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "model": Schema.String.annotate({ + "description": "The model to use for the evaluation. Must support structured outputs." + }), + "input": Schema.Array(EvalItem), + "labels": Schema.Array(Schema.String).annotate({ + "description": "The labels to assign to each item in the evaluation." + }), + "passing_labels": Schema.Array(Schema.String).annotate({ + "description": "The labels that indicate a passing result. Must be a subset of labels." + }) +}).annotate({ + "title": "LabelModelGrader", + "description": "A LabelModelGrader object which uses a model to assign labels to each item\nin the evaluation.\n" +}) +export type EvalGraderScoreModel = { + readonly "type": "score_model" + readonly "name": string + readonly "model": string + readonly "sampling_params"?: { + readonly "seed"?: number | null + readonly "top_p"?: number | null + readonly "temperature"?: number | null + readonly "max_completions_tokens"?: number | null + readonly "reasoning_effort"?: ReasoningEffort + } + readonly "input": ReadonlyArray + readonly "range"?: ReadonlyArray + readonly "pass_threshold"?: number +} +export const EvalGraderScoreModel = Schema.Struct({ + "type": Schema.Literal("score_model").annotate({ "description": "The object type, which is always `score_model`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "model": Schema.String.annotate({ "description": "The model to use for the evaluation." }), + "sampling_params": Schema.optionalKey( + Schema.Struct({ + "seed": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling.\n" }) + .check(Schema.isInt()), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs.\n" }) + .check(Schema.isFinite()), + Schema.Null + ]) + ), + "max_completions_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The maximum number of tokens the grader model may generate in its response.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null + ]) + ), + "reasoning_effort": Schema.optionalKey(ReasoningEffort) + }).annotate({ "description": "The sampling parameters for the model." }) + ), + "input": Schema.Array(EvalItem).annotate({ + "description": + "The input messages evaluated by the grader. Supports text, output text, input image, and input audio content blocks, and may include template strings.\n" + }), + "range": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isFinite())).annotate({ + "description": "The range of the score. Defaults to `[0, 1]`." + }) + ), + "pass_threshold": Schema.optionalKey( + Schema.Number.annotate({ "description": "The threshold for the score." }).check(Schema.isFinite()) + ) +}).annotate({ + "title": "ScoreModelGrader", + "description": "A ScoreModelGrader object that uses a model to assign a score to the input.\n" +}) +export type EvalRun = { + readonly "object": "eval.run" + readonly "id": string + readonly "eval_id": string + readonly "status": string + readonly "model": string + readonly "name": string + readonly "created_at": number + readonly "report_url": string + readonly "result_counts": { + readonly "total": number + readonly "errored": number + readonly "failed": number + readonly "passed": number + } + readonly "per_model_usage": ReadonlyArray< + { + readonly "model_name": string + readonly "invocation_count": number + readonly "prompt_tokens": number + readonly "completion_tokens": number + readonly "total_tokens": number + readonly "cached_tokens": number + } + > + readonly "per_testing_criteria_results": ReadonlyArray< + { readonly "testing_criteria": string; readonly "passed": number; readonly "failed": number } + > + readonly "data_source": { + readonly "type": "jsonl" + readonly "source": EvalJsonlFileContentSource | EvalJsonlFileIdSource + } | { + readonly "type": "completions" + readonly "input_messages"?: { + readonly "type": "template" + readonly "template": ReadonlyArray + } | { readonly "type": "item_reference"; readonly "item_reference": string } + readonly "sampling_params"?: { + readonly "reasoning_effort"?: ReasoningEffort + readonly "temperature"?: number + readonly "max_completion_tokens"?: number + readonly "top_p"?: number + readonly "seed"?: number + readonly "response_format"?: ResponseFormatText | ResponseFormatJsonSchema | ResponseFormatJsonObject + readonly "tools"?: ReadonlyArray + } + readonly "model"?: string + readonly "source": EvalJsonlFileContentSource | EvalJsonlFileIdSource | EvalStoredCompletionsSource + } | { + readonly "type": "responses" + readonly "input_messages"?: { + readonly "type": "template" + readonly "template": ReadonlyArray<{ readonly "role": string; readonly "content": string } | EvalItem> + } | { readonly "type": "item_reference"; readonly "item_reference": string } + readonly "sampling_params"?: { + readonly "reasoning_effort"?: ReasoningEffort + readonly "temperature"?: number + readonly "max_completion_tokens"?: number + readonly "top_p"?: number + readonly "seed"?: number + readonly "tools"?: ReadonlyArray + readonly "text"?: { readonly "format"?: TextResponseFormatConfiguration } + } + readonly "model"?: string + readonly "source": EvalJsonlFileContentSource | EvalJsonlFileIdSource | EvalResponsesSource + } + readonly "metadata": Metadata + readonly "error": EvalApiError +} +export const EvalRun = Schema.Struct({ + "object": Schema.Literal("eval.run").annotate({ "description": "The type of the object. Always \"eval.run\"." }), + "id": Schema.String.annotate({ "description": "Unique identifier for the evaluation run." }), + "eval_id": Schema.String.annotate({ "description": "The identifier of the associated evaluation." }), + "status": Schema.String.annotate({ "description": "The status of the evaluation run." }), + "model": Schema.String.annotate({ "description": "The model that is evaluated, if applicable." }), + "name": Schema.String.annotate({ "description": "The name of the evaluation run." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the evaluation run was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "report_url": Schema.String.annotate({ + "description": "The URL to the rendered evaluation run report on the UI dashboard.", + "format": "uri" + }), + "result_counts": Schema.Struct({ + "total": Schema.Number.annotate({ "description": "Total number of executed output items." }).check(Schema.isInt()), + "errored": Schema.Number.annotate({ "description": "Number of output items that resulted in an error." }).check( + Schema.isInt() + ), + "failed": Schema.Number.annotate({ "description": "Number of output items that failed to pass the evaluation." }) + .check(Schema.isInt()), + "passed": Schema.Number.annotate({ "description": "Number of output items that passed the evaluation." }).check( + Schema.isInt() + ) + }).annotate({ "description": "Counters summarizing the outcomes of the evaluation run." }), + "per_model_usage": Schema.Array(Schema.Struct({ + "model_name": Schema.String.annotate({ "description": "The name of the model." }), + "invocation_count": Schema.Number.annotate({ "description": "The number of invocations." }).check(Schema.isInt()), + "prompt_tokens": Schema.Number.annotate({ "description": "The number of prompt tokens used." }).check( + Schema.isInt() + ), + "completion_tokens": Schema.Number.annotate({ "description": "The number of completion tokens generated." }).check( + Schema.isInt() + ), + "total_tokens": Schema.Number.annotate({ "description": "The total number of tokens used." }).check(Schema.isInt()), + "cached_tokens": Schema.Number.annotate({ "description": "The number of tokens retrieved from cache." }).check( + Schema.isInt() + ) + })).annotate({ "description": "Usage statistics for each model during the evaluation run." }), + "per_testing_criteria_results": Schema.Array(Schema.Struct({ + "testing_criteria": Schema.String.annotate({ "description": "A description of the testing criteria." }), + "passed": Schema.Number.annotate({ "description": "Number of tests passed for this criteria." }).check( + Schema.isInt() + ), + "failed": Schema.Number.annotate({ "description": "Number of tests failed for this criteria." }).check( + Schema.isInt() + ) + })).annotate({ "description": "Results per testing criteria applied during the evaluation run." }), + "data_source": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("jsonl").annotate({ "description": "The type of data source. Always `jsonl`." }), + "source": Schema.Union([EvalJsonlFileContentSource, EvalJsonlFileIdSource], { mode: "oneOf" }).annotate({ + "description": "Determines what populates the `item` namespace in the data source." + }) + }).annotate({ "title": "JsonlRunDataSource", "description": "Information about the run's data source." }), + Schema.Struct({ + "type": Schema.Literal("completions").annotate({ + "description": "The type of run data source. Always `completions`." + }), + "input_messages": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("template").annotate({ + "description": "The type of input messages. Always `template`." + }), + "template": Schema.Array(Schema.Union([EasyInputMessage, EvalItem], { mode: "oneOf" })).annotate({ + "description": + "A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}." + }) + }).annotate({ "title": "TemplateInputMessages" }), + Schema.Struct({ + "type": Schema.Literal("item_reference").annotate({ + "description": "The type of input messages. Always `item_reference`." + }), + "item_reference": Schema.String.annotate({ + "description": "A reference to a variable in the `item` namespace. Ie, \"item.input_trajectory\"" + }) + }).annotate({ "title": "ItemReferenceInputMessages" }) + ], { mode: "oneOf" }).annotate({ + "description": + "Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace." + }) + ), + "sampling_params": Schema.optionalKey(Schema.Struct({ + "reasoning_effort": Schema.optionalKey(ReasoningEffort), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs." }).check( + Schema.isFinite() + ) + ), + "max_completion_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum number of tokens in the generated output." }).check( + Schema.isInt() + ) + ), + "top_p": Schema.optionalKey( + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens." + }).check(Schema.isFinite()) + ), + "seed": Schema.optionalKey( + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling." }) + .check(Schema.isInt()) + ), + "response_format": Schema.optionalKey( + Schema.Union([ResponseFormatText, ResponseFormatJsonSchema, ResponseFormatJsonObject], { mode: "oneOf" }) + .annotate({ + "description": + "An object specifying the format that the model must output.\n\nSetting to `{ \"type\": \"json_schema\", \"json_schema\": {...} }` enables\nStructured Outputs which ensures the model will match your supplied JSON\nschema. Learn more in the [Structured Outputs\nguide](/docs/guides/structured-outputs).\n\nSetting to `{ \"type\": \"json_object\" }` enables the older JSON mode, which\nensures the message the model generates is valid JSON. Using `json_schema`\nis preferred for models that support it.\n" + }) + ), + "tools": Schema.optionalKey( + Schema.Array(ChatCompletionTool).annotate({ + "description": + "A list of tools the model may call. Currently, only functions are supported as a tool. Use this to provide a list of functions the model may generate JSON inputs for. A max of 128 functions are supported.\n" + }) + ) + })), + "model": Schema.optionalKey( + Schema.String.annotate({ + "description": "The name of the model to use for generating completions (e.g. \"o3-mini\")." + }) + ), + "source": Schema.Union([EvalJsonlFileContentSource, EvalJsonlFileIdSource, EvalStoredCompletionsSource], { + mode: "oneOf" + }).annotate({ "description": "Determines what populates the `item` namespace in this run's data source." }) + }).annotate({ "title": "CompletionsRunDataSource", "description": "Information about the run's data source." }), + Schema.Struct({ + "type": Schema.Literal("responses").annotate({ + "description": "The type of run data source. Always `responses`." + }), + "input_messages": Schema.optionalKey( + Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("template").annotate({ + "description": "The type of input messages. Always `template`." + }), + "template": Schema.Array( + Schema.Union([ + Schema.Struct({ + "role": Schema.String.annotate({ + "description": "The role of the message (e.g. \"system\", \"assistant\", \"user\")." + }), + "content": Schema.String.annotate({ "description": "The content of the message." }) + }).annotate({ "title": "ChatMessage" }), + EvalItem + ], { mode: "oneOf" }) + ).annotate({ + "description": + "A list of chat messages forming the prompt or context. May include variable references to the `item` namespace, ie {{item.name}}." + }) + }).annotate({ "title": "InputMessagesTemplate" }), + Schema.Struct({ + "type": Schema.Literal("item_reference").annotate({ + "description": "The type of input messages. Always `item_reference`." + }), + "item_reference": Schema.String.annotate({ + "description": "A reference to a variable in the `item` namespace. Ie, \"item.name\"" + }) + }).annotate({ "title": "InputMessagesItemReference" }) + ], { mode: "oneOf" }).annotate({ + "description": + "Used when sampling from a model. Dictates the structure of the messages passed into the model. Can either be a reference to a prebuilt trajectory (ie, `item.input_trajectory`), or a template with variable references to the `item` namespace." + }) + ), + "sampling_params": Schema.optionalKey(Schema.Struct({ + "reasoning_effort": Schema.optionalKey(ReasoningEffort), + "temperature": Schema.optionalKey( + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs." }).check( + Schema.isFinite() + ) + ), + "max_completion_tokens": Schema.optionalKey( + Schema.Number.annotate({ "description": "The maximum number of tokens in the generated output." }).check( + Schema.isInt() + ) + ), + "top_p": Schema.optionalKey( + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens." + }).check(Schema.isFinite()) + ), + "seed": Schema.optionalKey( + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling." }) + .check(Schema.isInt()) + ), + "tools": Schema.optionalKey( + Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nThe two categories of tools you can provide the model are:\n\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code. Learn more about\n [function calling](/docs/guides/function-calling).\n" + }) + ), + "text": Schema.optionalKey( + Schema.Struct({ "format": Schema.optionalKey(TextResponseFormatConfiguration) }).annotate({ + "description": + "Configuration options for a text response from the model. Can be plain\ntext or structured JSON data. Learn more:\n- [Text inputs and outputs](/docs/guides/text)\n- [Structured Outputs](/docs/guides/structured-outputs)\n" + }) + ) + })), + "model": Schema.optionalKey( + Schema.String.annotate({ + "description": "The name of the model to use for generating completions (e.g. \"o3-mini\")." + }) + ), + "source": Schema.Union([EvalJsonlFileContentSource, EvalJsonlFileIdSource, EvalResponsesSource], { + mode: "oneOf" + }).annotate({ "description": "Determines what populates the `item` namespace in this run's data source." }) + }).annotate({ "title": "ResponsesRunDataSource", "description": "Information about the run's data source." }) + ], { mode: "oneOf" }), + "metadata": Metadata, + "error": EvalApiError +}).annotate({ "title": "EvalRun", "description": "A schema representing an evaluation run.\n" }) +export type GraderLabelModel = { + readonly "type": "label_model" + readonly "name": string + readonly "model": string + readonly "input": ReadonlyArray + readonly "labels": ReadonlyArray + readonly "passing_labels": ReadonlyArray +} +export const GraderLabelModel = Schema.Struct({ + "type": Schema.Literal("label_model").annotate({ "description": "The object type, which is always `label_model`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "model": Schema.String.annotate({ + "description": "The model to use for the evaluation. Must support structured outputs." + }), + "input": Schema.Array(EvalItem), + "labels": Schema.Array(Schema.String).annotate({ + "description": "The labels to assign to each item in the evaluation." + }), + "passing_labels": Schema.Array(Schema.String).annotate({ + "description": "The labels that indicate a passing result. Must be a subset of labels." + }) +}).annotate({ + "title": "LabelModelGrader", + "description": "A LabelModelGrader object which uses a model to assign labels to each item\nin the evaluation.\n" +}) +export type GraderScoreModel = { + readonly "type": "score_model" + readonly "name": string + readonly "model": string + readonly "sampling_params"?: { + readonly "seed"?: number | null + readonly "top_p"?: number | null + readonly "temperature"?: number | null + readonly "max_completions_tokens"?: number | null + readonly "reasoning_effort"?: ReasoningEffort + } + readonly "input": ReadonlyArray + readonly "range"?: ReadonlyArray +} +export const GraderScoreModel = Schema.Struct({ + "type": Schema.Literal("score_model").annotate({ "description": "The object type, which is always `score_model`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "model": Schema.String.annotate({ "description": "The model to use for the evaluation." }), + "sampling_params": Schema.optionalKey( + Schema.Struct({ + "seed": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling.\n" }) + .check(Schema.isInt()), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs.\n" }) + .check(Schema.isFinite()), + Schema.Null + ]) + ), + "max_completions_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The maximum number of tokens the grader model may generate in its response.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null + ]) + ), + "reasoning_effort": Schema.optionalKey(ReasoningEffort) + }).annotate({ "description": "The sampling parameters for the model." }) + ), + "input": Schema.Array(EvalItem).annotate({ + "description": + "The input messages evaluated by the grader. Supports text, output text, input image, and input audio content blocks, and may include template strings.\n" + }), + "range": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isFinite())).annotate({ + "description": "The range of the score. Defaults to `[0, 1]`." + }) + ) +}).annotate({ + "title": "ScoreModelGrader", + "description": "A ScoreModelGrader object that uses a model to assign a score to the input.\n" +}) +export type InputParam = string | ReadonlyArray +export const InputParam = Schema.Union([ + Schema.String.annotate({ + "title": "Text input", + "description": "A text input to the model, equivalent to a text input with the\n`user` role.\n" + }), + Schema.Array(InputItem).annotate({ + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n" + }) +], { mode: "oneOf" }).annotate({ + "description": + "Text, image, or file inputs to the model, used to generate a response.\n\nLearn more:\n- [Text inputs and outputs](/docs/guides/text)\n- [Image inputs](/docs/guides/images)\n- [File inputs](/docs/guides/pdf-files)\n- [Conversation state](/docs/guides/conversation-state)\n- [Function calling](/docs/guides/function-calling)\n" +}) +export type CreateConversationBody = { + readonly "metadata"?: {} | null | null + readonly "items"?: ReadonlyArray | null +} +export const CreateConversationBody = Schema.Struct({ + "metadata": Schema.optionalKey(Schema.Union([ + Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null + ]).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard.\n Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters." + }), + Schema.Null + ])), + "items": Schema.optionalKey( + Schema.Union([ + Schema.Array(InputItem).annotate({ + "description": "Initial items to include in the conversation context. You may add up to 20 items at a time." + }).check(Schema.isMaxLength(20)), + Schema.Null + ]) + ) +}) +export type TokenCountsBody = { + readonly "model"?: string | null + readonly "input"?: string | ReadonlyArray | null + readonly "previous_response_id"?: string | null + readonly "tools"?: ReadonlyArray | null + readonly "text"?: ResponseTextParam | null + readonly "reasoning"?: { + readonly "effort"?: ReasoningEffort + readonly "summary"?: "auto" | "concise" | "detailed" | null + readonly "generate_summary"?: "auto" | "concise" | "detailed" | null + } | null + readonly "truncation"?: "auto" | "disabled" + readonly "instructions"?: string | null + readonly "conversation"?: ConversationParam | null + readonly "tool_choice"?: + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMCP + | ToolChoiceCustom + | SpecificApplyPatchParam + | SpecificFunctionShellParam + | null + readonly "parallel_tool_calls"?: boolean | null +} +export const TokenCountsBody = Schema.Struct({ + "model": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](/docs/models) to browse and compare available models." + }), + Schema.Null + ]) + ), + "input": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.String.annotate({ + "description": "A text input to the model, equivalent to a text input with the `user` role." + }).check(Schema.isMaxLength(10485760)), + Schema.Array(InputItem).annotate({ + "description": "A list of one or many input items to the model, containing different content types." + }) + ], { mode: "oneOf" }).annotate({ + "description": "Text, image, or file inputs to the model, used to generate a response" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to create multi-turn conversations. Learn more about [conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`." + }), + Schema.Null + ]) + ), + "tools": Schema.optionalKey( + Schema.Union([ + Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You can specify which tool to use by setting the `tool_choice` parameter." + }), + Schema.Null + ]) + ), + "text": Schema.optionalKey(Schema.Union([ResponseTextParam, Schema.Null])), + "reasoning": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "effort": Schema.optionalKey(ReasoningEffort), + "summary": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "concise", "detailed"]).annotate({ + "description": + "A summary of the reasoning performed by the model. This can be\nuseful for debugging and understanding the model's reasoning process.\nOne of `auto`, `concise`, or `detailed`.\n\n`concise` is supported for `computer-use-preview` models and all reasoning models after `gpt-5`.\n" + }), + Schema.Null + ])), + "generate_summary": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["auto", "concise", "detailed"]).annotate({ + "description": + "**Deprecated:** use `summary` instead.\n\nA summary of the reasoning performed by the model. This can be\nuseful for debugging and understanding the model's reasoning process.\nOne of `auto`, `concise`, or `detailed`.\n" + }), + Schema.Null + ]) + ) + }).annotate({ + "title": "Reasoning", + "description": + "**gpt-5 and o-series models only** Configuration options for [reasoning models](https://platform.openai.com/docs/guides/reasoning)." + }), + Schema.Null + ])), + "truncation": Schema.optionalKey( + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response. - `auto`: If the input to this Response exceeds the model's context window size, the model will truncate the response to fit the context window by dropping items from the beginning of the conversation. - `disabled` (default): If the input size will exceed the context window size for a model, the request will fail with a 400 error." + }) + ), + "instructions": Schema.optionalKey(Schema.Union([ + Schema.String.annotate({ + "description": + "A system (or developer) message inserted into the model's context.\nWhen used along with `previous_response_id`, the instructions from a previous response will not be carried over to the next response. This makes it simple to swap out system (or developer) messages in new responses." + }), + Schema.Null + ])), + "conversation": Schema.optionalKey(Schema.Union([ConversationParam, Schema.Null])), + "tool_choice": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + ToolChoiceOptions, + ToolChoiceAllowed, + ToolChoiceTypes, + ToolChoiceFunction, + ToolChoiceMCP, + ToolChoiceCustom, + SpecificApplyPatchParam, + SpecificFunctionShellParam + ], { mode: "oneOf" }).annotate({ "description": "Controls which tool the model should use, if any." }), + Schema.Null + ]) + ), + "parallel_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ "description": "Whether to allow the model to run tool calls in parallel." }), + Schema.Null + ]) + ) +}) +export type CompactResponseMethodPublicBody = { + readonly "model": ModelIdsCompaction + readonly "input"?: string | ReadonlyArray | null + readonly "previous_response_id"?: string | null + readonly "instructions"?: string | null + readonly "prompt_cache_key"?: string | null + readonly "prompt_cache_retention"?: "in_memory" | "in-memory" | "24h" | null + readonly "service_tier"?: "auto" | "default" | "flex" | "priority" | null +} +export const CompactResponseMethodPublicBody = Schema.Struct({ + "model": ModelIdsCompaction, + "input": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.String.annotate({ + "description": "A text input to the model, equivalent to a text input with the `user` role." + }).check(Schema.isMaxLength(10485760)), + Schema.Array(InputItem).annotate({ + "description": "A list of one or many input items to the model, containing different content types." + }) + ], { mode: "oneOf" }).annotate({ + "description": "Text, image, or file inputs to the model, used to generate a response" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to create multi-turn conversations. Learn more about [conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`." + }), + Schema.Null + ]) + ), + "instructions": Schema.optionalKey(Schema.Union([ + Schema.String.annotate({ + "description": + "A system (or developer) message inserted into the model's context.\nWhen used along with `previous_response_id`, the instructions from a previous response will not be carried over to the next response. This makes it simple to swap out system (or developer) messages in new responses." + }), + Schema.Null + ])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ "description": "A key to use when reading from or writing to the prompt cache." }).check( + Schema.isMaxLength(64) + ), + Schema.Null + ]) + ), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in-memory", "24h"]).annotate({ + "description": "How long to retain a prompt cache entry created by this request." + }), + Schema.Null + ]) + ), + "service_tier": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["auto", "default", "flex", "priority"]).annotate({ + "description": "The service tier to use for this request." + }), + Schema.Null + ]) + ) +}) +export type ConversationItem = + | Message + | FunctionToolCallResource + | FunctionToolCallOutputResource + | FileSearchToolCall + | WebSearchToolCall + | ImageGenToolCall + | ComputerToolCall + | ComputerToolCallOutputResource + | ToolSearchCall + | ToolSearchOutput + | ReasoningItem + | CompactionBody + | CodeInterpreterToolCall + | LocalShellToolCall + | LocalShellToolCallOutput + | FunctionShellCall + | FunctionShellCallOutput + | ApplyPatchToolCall + | ApplyPatchToolCallOutput + | MCPListTools + | MCPApprovalRequest + | MCPApprovalResponseResource + | MCPToolCall + | CustomToolCall + | CustomToolCallOutput +export const ConversationItem = Schema.Union([ + Message, + FunctionToolCallResource, + FunctionToolCallOutputResource, + FileSearchToolCall, + WebSearchToolCall, + ImageGenToolCall, + ComputerToolCall, + ComputerToolCallOutputResource, + ToolSearchCall, + ToolSearchOutput, + ReasoningItem, + CompactionBody, + CodeInterpreterToolCall, + LocalShellToolCall, + LocalShellToolCallOutput, + FunctionShellCall, + FunctionShellCallOutput, + ApplyPatchToolCall, + ApplyPatchToolCallOutput, + MCPListTools, + MCPApprovalRequest, + MCPApprovalResponseResource, + MCPToolCall, + CustomToolCall, + CustomToolCallOutput +], { mode: "oneOf" }).annotate({ + "title": "Conversation item", + "description": + "A single item within a conversation. The set of possible types are the same as the `output` type of a [Response object](/docs/api-reference/responses/object#responses/object-output)." +}) +export type ItemResource = + | InputMessageResource + | OutputMessage + | FileSearchToolCall + | ComputerToolCall + | ComputerToolCallOutputResource + | WebSearchToolCall + | FunctionToolCallResource + | FunctionToolCallOutputResource + | ToolSearchCall + | ToolSearchOutput + | ReasoningItem + | CompactionBody + | ImageGenToolCall + | CodeInterpreterToolCall + | LocalShellToolCall + | LocalShellToolCallOutput + | FunctionShellCall + | FunctionShellCallOutput + | ApplyPatchToolCall + | ApplyPatchToolCallOutput + | MCPListTools + | MCPApprovalRequest + | MCPApprovalResponseResource + | MCPToolCall + | CustomToolCallResource + | CustomToolCallOutputResource +export const ItemResource = Schema.Union([ + InputMessageResource, + OutputMessage, + FileSearchToolCall, + ComputerToolCall, + ComputerToolCallOutputResource, + WebSearchToolCall, + FunctionToolCallResource, + FunctionToolCallOutputResource, + ToolSearchCall, + ToolSearchOutput, + ReasoningItem, + CompactionBody, + ImageGenToolCall, + CodeInterpreterToolCall, + LocalShellToolCall, + LocalShellToolCallOutput, + FunctionShellCall, + FunctionShellCallOutput, + ApplyPatchToolCall, + ApplyPatchToolCallOutput, + MCPListTools, + MCPApprovalRequest, + MCPApprovalResponseResource, + MCPToolCall, + CustomToolCallResource, + CustomToolCallOutputResource +], { mode: "oneOf" }).annotate({ "description": "Content item used to generate a response.\n" }) +export type OutputItem = + | OutputMessage + | FileSearchToolCall + | FunctionToolCall + | FunctionToolCallOutputResource + | WebSearchToolCall + | ComputerToolCall + | ComputerToolCallOutputResource + | ReasoningItem + | ToolSearchCall + | ToolSearchOutput + | CompactionBody + | ImageGenToolCall + | CodeInterpreterToolCall + | LocalShellToolCall + | LocalShellToolCallOutput + | FunctionShellCall + | FunctionShellCallOutput + | ApplyPatchToolCall + | ApplyPatchToolCallOutput + | MCPToolCall + | MCPListTools + | MCPApprovalRequest + | MCPApprovalResponseResource + | CustomToolCall + | CustomToolCallOutputResource +export const OutputItem = Schema.Union([ + OutputMessage, + FileSearchToolCall, + FunctionToolCall, + FunctionToolCallOutputResource, + WebSearchToolCall, + ComputerToolCall, + ComputerToolCallOutputResource, + ReasoningItem, + ToolSearchCall, + ToolSearchOutput, + CompactionBody, + ImageGenToolCall, + CodeInterpreterToolCall, + LocalShellToolCall, + LocalShellToolCallOutput, + FunctionShellCall, + FunctionShellCallOutput, + ApplyPatchToolCall, + ApplyPatchToolCallOutput, + MCPToolCall, + MCPListTools, + MCPApprovalRequest, + MCPApprovalResponseResource, + CustomToolCall, + CustomToolCallOutputResource +], { mode: "oneOf" }) +export type ResponseOutputItemAddedEvent = { + readonly "type": "response.output_item.added" + readonly "output_index": number + readonly "sequence_number": number + readonly "item": + | OutputMessage + | FileSearchToolCall + | FunctionToolCall + | FunctionToolCallOutputResource + | WebSearchToolCall + | ComputerToolCall + | ComputerToolCallOutputResource + | ReasoningItem + | ToolSearchCall + | ToolSearchOutput + | CompactionBody + | ImageGenToolCall + | CodeInterpreterToolCall + | LocalShellToolCall + | LocalShellToolCallOutput + | FunctionShellCall + | FunctionShellCallOutput + | ApplyPatchToolCall + | ApplyPatchToolCallOutput + | MCPToolCall + | MCPListTools + | MCPApprovalRequest + | MCPApprovalResponseResource + | CustomToolCall + | CustomToolCallOutputResource +} +export const ResponseOutputItemAddedEvent = Schema.Struct({ + "type": Schema.Literal("response.output_item.added").annotate({ + "description": "The type of the event. Always `response.output_item.added`.\n" + }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item that was added.\n" }).check( + Schema.isInt() + ), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ), + "item": Schema.Union([ + OutputMessage, + FileSearchToolCall, + FunctionToolCall, + FunctionToolCallOutputResource, + WebSearchToolCall, + ComputerToolCall, + ComputerToolCallOutputResource, + ReasoningItem, + ToolSearchCall, + ToolSearchOutput, + CompactionBody, + ImageGenToolCall, + CodeInterpreterToolCall, + LocalShellToolCall, + LocalShellToolCallOutput, + FunctionShellCall, + FunctionShellCallOutput, + ApplyPatchToolCall, + ApplyPatchToolCallOutput, + MCPToolCall, + MCPListTools, + MCPApprovalRequest, + MCPApprovalResponseResource, + CustomToolCall, + CustomToolCallOutputResource + ], { mode: "oneOf" }).annotate({ "description": "The output item that was added.\n" }) +}).annotate({ "description": "Emitted when a new output item is added." }) +export type ResponseOutputItemDoneEvent = { + readonly "type": "response.output_item.done" + readonly "output_index": number + readonly "sequence_number": number + readonly "item": + | OutputMessage + | FileSearchToolCall + | FunctionToolCall + | FunctionToolCallOutputResource + | WebSearchToolCall + | ComputerToolCall + | ComputerToolCallOutputResource + | ReasoningItem + | ToolSearchCall + | ToolSearchOutput + | CompactionBody + | ImageGenToolCall + | CodeInterpreterToolCall + | LocalShellToolCall + | LocalShellToolCallOutput + | FunctionShellCall + | FunctionShellCallOutput + | ApplyPatchToolCall + | ApplyPatchToolCallOutput + | MCPToolCall + | MCPListTools + | MCPApprovalRequest + | MCPApprovalResponseResource + | CustomToolCall + | CustomToolCallOutputResource +} +export const ResponseOutputItemDoneEvent = Schema.Struct({ + "type": Schema.Literal("response.output_item.done").annotate({ + "description": "The type of the event. Always `response.output_item.done`.\n" + }), + "output_index": Schema.Number.annotate({ "description": "The index of the output item that was marked done.\n" }) + .check(Schema.isInt()), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event.\n" }).check( + Schema.isInt() + ), + "item": Schema.Union([ + OutputMessage, + FileSearchToolCall, + FunctionToolCall, + FunctionToolCallOutputResource, + WebSearchToolCall, + ComputerToolCall, + ComputerToolCallOutputResource, + ReasoningItem, + ToolSearchCall, + ToolSearchOutput, + CompactionBody, + ImageGenToolCall, + CodeInterpreterToolCall, + LocalShellToolCall, + LocalShellToolCallOutput, + FunctionShellCall, + FunctionShellCallOutput, + ApplyPatchToolCall, + ApplyPatchToolCallOutput, + MCPToolCall, + MCPListTools, + MCPApprovalRequest, + MCPApprovalResponseResource, + CustomToolCall, + CustomToolCallOutputResource + ], { mode: "oneOf" }).annotate({ "description": "The output item that was marked done.\n" }) +}).annotate({ "description": "Emitted when an output item is marked done." }) +export type ItemField = + | Message + | FunctionToolCall + | ToolSearchCall + | ToolSearchOutput + | FunctionToolCallOutput + | FileSearchToolCall + | WebSearchToolCall + | ImageGenToolCall + | ComputerToolCall + | ComputerToolCallOutputResource + | ReasoningItem + | CompactionBody + | CodeInterpreterToolCall + | LocalShellToolCall + | LocalShellToolCallOutput + | FunctionShellCall + | FunctionShellCallOutput + | ApplyPatchToolCall + | ApplyPatchToolCallOutput + | MCPListTools + | MCPApprovalRequest + | MCPApprovalResponseResource + | MCPToolCall + | CustomToolCall + | CustomToolCallOutput +export const ItemField = Schema.Union([ + Message, + FunctionToolCall, + ToolSearchCall, + ToolSearchOutput, + FunctionToolCallOutput, + FileSearchToolCall, + WebSearchToolCall, + ImageGenToolCall, + ComputerToolCall, + ComputerToolCallOutputResource, + ReasoningItem, + CompactionBody, + CodeInterpreterToolCall, + LocalShellToolCall, + LocalShellToolCallOutput, + FunctionShellCall, + FunctionShellCallOutput, + ApplyPatchToolCall, + ApplyPatchToolCallOutput, + MCPListTools, + MCPApprovalRequest, + MCPApprovalResponseResource, + MCPToolCall, + CustomToolCall, + CustomToolCallOutput +], { mode: "oneOf" }).annotate({ + "description": "An item representing a message, tool call, tool output, reasoning, or other response element." +}) +export type CreateEvalRequest = { + readonly "name"?: string + readonly "metadata"?: Metadata + readonly "data_source_config": + | { readonly "type": "custom"; readonly "item_schema": {}; readonly "include_sample_schema"?: boolean } + | { readonly "type": "logs"; readonly "metadata"?: {} } + | { readonly "type": "stored_completions"; readonly "metadata"?: {} } + readonly "testing_criteria": ReadonlyArray< + | CreateEvalLabelModelGrader + | EvalGraderStringCheck + | EvalGraderTextSimilarity + | EvalGraderPython + | EvalGraderScoreModel + > +} +export const CreateEvalRequest = Schema.Struct({ + "name": Schema.optionalKey(Schema.String.annotate({ "description": "The name of the evaluation." })), + "metadata": Schema.optionalKey(Metadata), + "data_source_config": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("custom").annotate({ "description": "The type of data source. Always `custom`." }), + "item_schema": Schema.Struct({}).annotate({ "description": "The json schema for each row in the data source." }), + "include_sample_schema": Schema.optionalKey( + Schema.Boolean.annotate({ + "description": + "Whether the eval should expect you to populate the sample namespace (ie, by generating responses off of your data source)" + }) + ) + }).annotate({ + "title": "CustomDataSourceConfig", + "description": + "The configuration for the data source used for the evaluation runs. Dictates the schema of the data used in the evaluation." + }), + Schema.Struct({ + "type": Schema.Literal("logs").annotate({ "description": "The type of data source. Always `logs`." }), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ "description": "Metadata filters for the logs data source." }) + ) + }).annotate({ + "title": "LogsDataSourceConfig", + "description": + "The configuration for the data source used for the evaluation runs. Dictates the schema of the data used in the evaluation." + }), + Schema.Struct({ + "type": Schema.Literal("stored_completions").annotate({ + "description": "The type of data source. Always `stored_completions`." + }), + "metadata": Schema.optionalKey( + Schema.Struct({}).annotate({ "description": "Metadata filters for the stored completions data source." }) + ) + }).annotate({ + "title": "StoredCompletionsDataSourceConfig", + "description": + "The configuration for the data source used for the evaluation runs. Dictates the schema of the data used in the evaluation." + }) + ], { mode: "oneOf" }), + "testing_criteria": Schema.Array( + Schema.Union([ + CreateEvalLabelModelGrader, + EvalGraderStringCheck, + EvalGraderTextSimilarity, + EvalGraderPython, + EvalGraderScoreModel + ], { mode: "oneOf" }) + ).annotate({ + "description": + "A list of graders for all eval runs in this group. Graders can reference variables in the data source using double curly braces notation, like `{{item.variable_name}}`. To reference the model's output, use the `sample` namespace (ie, `{{sample.output_text}}`)." + }) +}).annotate({ "title": "CreateEvalRequest" }) +export type Eval = { + readonly "object": "eval" + readonly "id": string + readonly "name": string + readonly "data_source_config": { readonly "type": "custom"; readonly "schema": {} } | { + readonly "type": "logs" + readonly "metadata"?: Metadata + readonly "schema": {} + } | { readonly "type": "stored_completions"; readonly "metadata"?: Metadata; readonly "schema": {} } + readonly "testing_criteria": ReadonlyArray< + EvalGraderLabelModel | EvalGraderStringCheck | EvalGraderTextSimilarity | EvalGraderPython | EvalGraderScoreModel + > + readonly "created_at": number + readonly "metadata": Metadata +} +export const Eval = Schema.Struct({ + "object": Schema.Literal("eval").annotate({ "description": "The object type." }), + "id": Schema.String.annotate({ "description": "Unique identifier for the evaluation." }), + "name": Schema.String.annotate({ "description": "The name of the evaluation." }), + "data_source_config": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("custom").annotate({ "description": "The type of data source. Always `custom`." }), + "schema": Schema.Struct({}).annotate({ + "description": + "The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n" + }) + }).annotate({ + "title": "CustomDataSourceConfig", + "description": "Configuration of data sources used in runs of the evaluation." + }), + Schema.Struct({ + "type": Schema.Literal("logs").annotate({ "description": "The type of data source. Always `logs`." }), + "metadata": Schema.optionalKey(Metadata), + "schema": Schema.Struct({}).annotate({ + "description": + "The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n" + }) + }).annotate({ + "title": "LogsDataSourceConfig", + "description": "Configuration of data sources used in runs of the evaluation." + }), + Schema.Struct({ + "type": Schema.Literal("stored_completions").annotate({ + "description": "The type of data source. Always `stored_completions`." + }), + "metadata": Schema.optionalKey(Metadata), + "schema": Schema.Struct({}).annotate({ + "description": + "The json schema for the run data source items.\nLearn how to build JSON schemas [here](https://json-schema.org/).\n" + }) + }).annotate({ + "title": "StoredCompletionsDataSourceConfig", + "description": "Configuration of data sources used in runs of the evaluation." + }) + ], { mode: "oneOf" }), + "testing_criteria": Schema.Array( + Schema.Union([ + EvalGraderLabelModel, + EvalGraderStringCheck, + EvalGraderTextSimilarity, + EvalGraderPython, + EvalGraderScoreModel + ], { mode: "oneOf" }) + ).annotate({ "description": "A list of testing criteria." }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the eval was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "metadata": Metadata +}).annotate({ + "title": "Eval", + "description": + "An Eval object with a data source config and testing criteria.\nAn Eval represents a task to be done for your LLM integration.\nLike:\n - Improve the quality of my chatbot\n - See how well my chatbot handles customer support\n - Check if o4-mini is better at my usecase than gpt-4o\n" +}) +export type EvalRunList = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const EvalRunList = Schema.Struct({ + "object": Schema.Literal("list").annotate({ + "description": "The type of this object. It is always set to \"list\".\n" + }), + "data": Schema.Array(EvalRun).annotate({ "description": "An array of eval run objects.\n" }), + "first_id": Schema.String.annotate({ "description": "The identifier of the first eval run in the data array." }), + "last_id": Schema.String.annotate({ "description": "The identifier of the last eval run in the data array." }), + "has_more": Schema.Boolean.annotate({ "description": "Indicates whether there are more evals available." }) +}).annotate({ "title": "EvalRunList", "description": "An object representing a list of runs for an evaluation.\n" }) +export type FineTuneReinforcementMethod = { + readonly "grader": + | { + readonly "type": "string_check" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "operation": "eq" | "ne" | "like" | "ilike" + } + | { + readonly "type": "text_similarity" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "evaluation_metric": + | "cosine" + | "fuzzy_match" + | "bleu" + | "gleu" + | "meteor" + | "rouge_1" + | "rouge_2" + | "rouge_3" + | "rouge_4" + | "rouge_5" + | "rouge_l" + } + | { readonly "type": "python"; readonly "name": string; readonly "source": string; readonly "image_tag"?: string } + | { + readonly "type": "score_model" + readonly "name": string + readonly "model": string + readonly "sampling_params"?: { + readonly "seed"?: number | null + readonly "top_p"?: number | null + readonly "temperature"?: number | null + readonly "max_completions_tokens"?: number | null + readonly "reasoning_effort"?: ReasoningEffort + } + readonly "input": ReadonlyArray + readonly "range"?: ReadonlyArray + } + | { + readonly "type": "multi" + readonly "name": string + readonly "graders": GraderStringCheck | GraderTextSimilarity | GraderPython | GraderScoreModel | GraderLabelModel + readonly "calculate_output": string + } + readonly "hyperparameters"?: FineTuneReinforcementHyperparameters +} +export const FineTuneReinforcementMethod = Schema.Struct({ + "grader": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("string_check").annotate({ + "description": "The object type, which is always `string_check`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The input text. This may include template strings." }), + "reference": Schema.String.annotate({ "description": "The reference text. This may include template strings." }), + "operation": Schema.Literals(["eq", "ne", "like", "ilike"]).annotate({ + "description": "The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`." + }) + }).annotate({ "title": "StringCheckGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("text_similarity").annotate({ "description": "The type of grader." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The text being graded." }), + "reference": Schema.String.annotate({ "description": "The text being graded against." }), + "evaluation_metric": Schema.Literals([ + "cosine", + "fuzzy_match", + "bleu", + "gleu", + "meteor", + "rouge_1", + "rouge_2", + "rouge_3", + "rouge_4", + "rouge_5", + "rouge_l" + ]).annotate({ + "description": + "The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, \n`gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, \nor `rouge_l`.\n" + }) + }).annotate({ "title": "TextSimilarityGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("python").annotate({ "description": "The object type, which is always `python`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "source": Schema.String.annotate({ "description": "The source code of the python script." }), + "image_tag": Schema.optionalKey( + Schema.String.annotate({ "description": "The image tag to use for the python script." }) + ) + }).annotate({ "title": "PythonGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("score_model").annotate({ + "description": "The object type, which is always `score_model`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "model": Schema.String.annotate({ "description": "The model to use for the evaluation." }), + "sampling_params": Schema.optionalKey( + Schema.Struct({ + "seed": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling.\n" }) + .check(Schema.isInt()), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs.\n" }) + .check(Schema.isFinite()), + Schema.Null + ]) + ), + "max_completions_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The maximum number of tokens the grader model may generate in its response.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null + ]) + ), + "reasoning_effort": Schema.optionalKey(ReasoningEffort) + }).annotate({ "description": "The sampling parameters for the model." }) + ), + "input": Schema.Array(EvalItem).annotate({ + "description": + "The input messages evaluated by the grader. Supports text, output text, input image, and input audio content blocks, and may include template strings.\n" + }), + "range": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isFinite())).annotate({ + "description": "The range of the score. Defaults to `[0, 1]`." + }) + ) + }).annotate({ "title": "ScoreModelGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("multi").annotate({ "description": "The object type, which is always `multi`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "graders": Schema.Union([ + GraderStringCheck, + GraderTextSimilarity, + GraderPython, + GraderScoreModel, + GraderLabelModel + ], { mode: "oneOf" }), + "calculate_output": Schema.String.annotate({ + "description": "A formula to calculate the output based on grader results." + }) + }).annotate({ "title": "MultiGrader", "description": "The grader used for the fine-tuning job." }) + ], { mode: "oneOf" }), + "hyperparameters": Schema.optionalKey(FineTuneReinforcementHyperparameters) +}).annotate({ "description": "Configuration for the reinforcement fine-tuning method." }) +export type RunGraderRequest = { + readonly "grader": + | { + readonly "type": "string_check" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "operation": "eq" | "ne" | "like" | "ilike" + } + | { + readonly "type": "text_similarity" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "evaluation_metric": + | "cosine" + | "fuzzy_match" + | "bleu" + | "gleu" + | "meteor" + | "rouge_1" + | "rouge_2" + | "rouge_3" + | "rouge_4" + | "rouge_5" + | "rouge_l" + } + | { readonly "type": "python"; readonly "name": string; readonly "source": string; readonly "image_tag"?: string } + | { + readonly "type": "score_model" + readonly "name": string + readonly "model": string + readonly "sampling_params"?: { + readonly "seed"?: number | null + readonly "top_p"?: number | null + readonly "temperature"?: number | null + readonly "max_completions_tokens"?: number | null + readonly "reasoning_effort"?: ReasoningEffort + } + readonly "input": ReadonlyArray + readonly "range"?: ReadonlyArray + } + | { + readonly "type": "multi" + readonly "name": string + readonly "graders": GraderStringCheck | GraderTextSimilarity | GraderPython | GraderScoreModel | GraderLabelModel + readonly "calculate_output": string + } + readonly "item"?: {} + readonly "model_sample": string +} +export const RunGraderRequest = Schema.Struct({ + "grader": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("string_check").annotate({ + "description": "The object type, which is always `string_check`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The input text. This may include template strings." }), + "reference": Schema.String.annotate({ "description": "The reference text. This may include template strings." }), + "operation": Schema.Literals(["eq", "ne", "like", "ilike"]).annotate({ + "description": "The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`." + }) + }).annotate({ "title": "StringCheckGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("text_similarity").annotate({ "description": "The type of grader." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The text being graded." }), + "reference": Schema.String.annotate({ "description": "The text being graded against." }), + "evaluation_metric": Schema.Literals([ + "cosine", + "fuzzy_match", + "bleu", + "gleu", + "meteor", + "rouge_1", + "rouge_2", + "rouge_3", + "rouge_4", + "rouge_5", + "rouge_l" + ]).annotate({ + "description": + "The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, \n`gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, \nor `rouge_l`.\n" + }) + }).annotate({ "title": "TextSimilarityGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("python").annotate({ "description": "The object type, which is always `python`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "source": Schema.String.annotate({ "description": "The source code of the python script." }), + "image_tag": Schema.optionalKey( + Schema.String.annotate({ "description": "The image tag to use for the python script." }) + ) + }).annotate({ "title": "PythonGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("score_model").annotate({ + "description": "The object type, which is always `score_model`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "model": Schema.String.annotate({ "description": "The model to use for the evaluation." }), + "sampling_params": Schema.optionalKey( + Schema.Struct({ + "seed": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling.\n" }) + .check(Schema.isInt()), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs.\n" }) + .check(Schema.isFinite()), + Schema.Null + ]) + ), + "max_completions_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The maximum number of tokens the grader model may generate in its response.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null + ]) + ), + "reasoning_effort": Schema.optionalKey(ReasoningEffort) + }).annotate({ "description": "The sampling parameters for the model." }) + ), + "input": Schema.Array(EvalItem).annotate({ + "description": + "The input messages evaluated by the grader. Supports text, output text, input image, and input audio content blocks, and may include template strings.\n" + }), + "range": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isFinite())).annotate({ + "description": "The range of the score. Defaults to `[0, 1]`." + }) + ) + }).annotate({ "title": "ScoreModelGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("multi").annotate({ "description": "The object type, which is always `multi`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "graders": Schema.Union([ + GraderStringCheck, + GraderTextSimilarity, + GraderPython, + GraderScoreModel, + GraderLabelModel + ], { mode: "oneOf" }), + "calculate_output": Schema.String.annotate({ + "description": "A formula to calculate the output based on grader results." + }) + }).annotate({ "title": "MultiGrader", "description": "The grader used for the fine-tuning job." }) + ], { mode: "oneOf" }), + "item": Schema.optionalKey( + Schema.Struct({}).annotate({ + "description": + "The dataset item provided to the grader. This will be used to populate \nthe `item` namespace. See [the guide](/docs/guides/graders) for more details. \n" + }) + ), + "model_sample": Schema.String.annotate({ + "description": + "The model sample to be evaluated. This value will be used to populate \nthe `sample` namespace. See [the guide](/docs/guides/graders) for more details.\nThe `output_json` variable will be populated if the model sample is a \nvalid JSON string.\n \n" + }) +}).annotate({ "title": "RunGraderRequest" }) +export type ValidateGraderRequest = { + readonly "grader": + | { + readonly "type": "string_check" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "operation": "eq" | "ne" | "like" | "ilike" + } + | { + readonly "type": "text_similarity" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "evaluation_metric": + | "cosine" + | "fuzzy_match" + | "bleu" + | "gleu" + | "meteor" + | "rouge_1" + | "rouge_2" + | "rouge_3" + | "rouge_4" + | "rouge_5" + | "rouge_l" + } + | { readonly "type": "python"; readonly "name": string; readonly "source": string; readonly "image_tag"?: string } + | { + readonly "type": "score_model" + readonly "name": string + readonly "model": string + readonly "sampling_params"?: { + readonly "seed"?: number | null + readonly "top_p"?: number | null + readonly "temperature"?: number | null + readonly "max_completions_tokens"?: number | null + readonly "reasoning_effort"?: ReasoningEffort + } + readonly "input": ReadonlyArray + readonly "range"?: ReadonlyArray + } + | { + readonly "type": "multi" + readonly "name": string + readonly "graders": GraderStringCheck | GraderTextSimilarity | GraderPython | GraderScoreModel | GraderLabelModel + readonly "calculate_output": string + } +} +export const ValidateGraderRequest = Schema.Struct({ + "grader": Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("string_check").annotate({ + "description": "The object type, which is always `string_check`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The input text. This may include template strings." }), + "reference": Schema.String.annotate({ "description": "The reference text. This may include template strings." }), + "operation": Schema.Literals(["eq", "ne", "like", "ilike"]).annotate({ + "description": "The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`." + }) + }).annotate({ "title": "StringCheckGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("text_similarity").annotate({ "description": "The type of grader." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The text being graded." }), + "reference": Schema.String.annotate({ "description": "The text being graded against." }), + "evaluation_metric": Schema.Literals([ + "cosine", + "fuzzy_match", + "bleu", + "gleu", + "meteor", + "rouge_1", + "rouge_2", + "rouge_3", + "rouge_4", + "rouge_5", + "rouge_l" + ]).annotate({ + "description": + "The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, \n`gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, \nor `rouge_l`.\n" + }) + }).annotate({ "title": "TextSimilarityGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("python").annotate({ "description": "The object type, which is always `python`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "source": Schema.String.annotate({ "description": "The source code of the python script." }), + "image_tag": Schema.optionalKey( + Schema.String.annotate({ "description": "The image tag to use for the python script." }) + ) + }).annotate({ "title": "PythonGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("score_model").annotate({ + "description": "The object type, which is always `score_model`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "model": Schema.String.annotate({ "description": "The model to use for the evaluation." }), + "sampling_params": Schema.optionalKey( + Schema.Struct({ + "seed": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling.\n" }) + .check(Schema.isInt()), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs.\n" }) + .check(Schema.isFinite()), + Schema.Null + ]) + ), + "max_completions_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The maximum number of tokens the grader model may generate in its response.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null + ]) + ), + "reasoning_effort": Schema.optionalKey(ReasoningEffort) + }).annotate({ "description": "The sampling parameters for the model." }) + ), + "input": Schema.Array(EvalItem).annotate({ + "description": + "The input messages evaluated by the grader. Supports text, output text, input image, and input audio content blocks, and may include template strings.\n" + }), + "range": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isFinite())).annotate({ + "description": "The range of the score. Defaults to `[0, 1]`." + }) + ) + }).annotate({ "title": "ScoreModelGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("multi").annotate({ "description": "The object type, which is always `multi`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "graders": Schema.Union([ + GraderStringCheck, + GraderTextSimilarity, + GraderPython, + GraderScoreModel, + GraderLabelModel + ], { mode: "oneOf" }), + "calculate_output": Schema.String.annotate({ + "description": "A formula to calculate the output based on grader results." + }) + }).annotate({ "title": "MultiGrader", "description": "The grader used for the fine-tuning job." }) + ], { mode: "oneOf" }) +}).annotate({ "title": "ValidateGraderRequest" }) +export type ValidateGraderResponse = { + readonly "grader"?: + | { + readonly "type": "string_check" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "operation": "eq" | "ne" | "like" | "ilike" + } + | { + readonly "type": "text_similarity" + readonly "name": string + readonly "input": string + readonly "reference": string + readonly "evaluation_metric": + | "cosine" + | "fuzzy_match" + | "bleu" + | "gleu" + | "meteor" + | "rouge_1" + | "rouge_2" + | "rouge_3" + | "rouge_4" + | "rouge_5" + | "rouge_l" + } + | { readonly "type": "python"; readonly "name": string; readonly "source": string; readonly "image_tag"?: string } + | { + readonly "type": "score_model" + readonly "name": string + readonly "model": string + readonly "sampling_params"?: { + readonly "seed"?: number | null + readonly "top_p"?: number | null + readonly "temperature"?: number | null + readonly "max_completions_tokens"?: number | null + readonly "reasoning_effort"?: ReasoningEffort + } + readonly "input": ReadonlyArray + readonly "range"?: ReadonlyArray + } + | { + readonly "type": "multi" + readonly "name": string + readonly "graders": GraderStringCheck | GraderTextSimilarity | GraderPython | GraderScoreModel | GraderLabelModel + readonly "calculate_output": string + } +} +export const ValidateGraderResponse = Schema.Struct({ + "grader": Schema.optionalKey(Schema.Union([ + Schema.Struct({ + "type": Schema.Literal("string_check").annotate({ + "description": "The object type, which is always `string_check`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The input text. This may include template strings." }), + "reference": Schema.String.annotate({ "description": "The reference text. This may include template strings." }), + "operation": Schema.Literals(["eq", "ne", "like", "ilike"]).annotate({ + "description": "The string check operation to perform. One of `eq`, `ne`, `like`, or `ilike`." + }) + }).annotate({ "title": "StringCheckGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("text_similarity").annotate({ "description": "The type of grader." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "input": Schema.String.annotate({ "description": "The text being graded." }), + "reference": Schema.String.annotate({ "description": "The text being graded against." }), + "evaluation_metric": Schema.Literals([ + "cosine", + "fuzzy_match", + "bleu", + "gleu", + "meteor", + "rouge_1", + "rouge_2", + "rouge_3", + "rouge_4", + "rouge_5", + "rouge_l" + ]).annotate({ + "description": + "The evaluation metric to use. One of `cosine`, `fuzzy_match`, `bleu`, \n`gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, `rouge_5`, \nor `rouge_l`.\n" + }) + }).annotate({ "title": "TextSimilarityGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("python").annotate({ "description": "The object type, which is always `python`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "source": Schema.String.annotate({ "description": "The source code of the python script." }), + "image_tag": Schema.optionalKey( + Schema.String.annotate({ "description": "The image tag to use for the python script." }) + ) + }).annotate({ "title": "PythonGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("score_model").annotate({ + "description": "The object type, which is always `score_model`." + }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "model": Schema.String.annotate({ "description": "The model to use for the evaluation." }), + "sampling_params": Schema.optionalKey( + Schema.Struct({ + "seed": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A seed value to initialize the randomness, during sampling.\n" }) + .check(Schema.isInt()), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "An alternative to temperature for nucleus sampling; 1.0 includes all tokens.\n" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ "description": "A higher temperature increases randomness in the outputs.\n" }) + .check(Schema.isFinite()), + Schema.Null + ]) + ), + "max_completions_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": "The maximum number of tokens the grader model may generate in its response.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)), + Schema.Null + ]) + ), + "reasoning_effort": Schema.optionalKey(ReasoningEffort) + }).annotate({ "description": "The sampling parameters for the model." }) + ), + "input": Schema.Array(EvalItem).annotate({ + "description": + "The input messages evaluated by the grader. Supports text, output text, input image, and input audio content blocks, and may include template strings.\n" + }), + "range": Schema.optionalKey( + Schema.Array(Schema.Number.check(Schema.isFinite())).annotate({ + "description": "The range of the score. Defaults to `[0, 1]`." + }) + ) + }).annotate({ "title": "ScoreModelGrader", "description": "The grader used for the fine-tuning job." }), + Schema.Struct({ + "type": Schema.Literal("multi").annotate({ "description": "The object type, which is always `multi`." }), + "name": Schema.String.annotate({ "description": "The name of the grader." }), + "graders": Schema.Union([ + GraderStringCheck, + GraderTextSimilarity, + GraderPython, + GraderScoreModel, + GraderLabelModel + ], { mode: "oneOf" }), + "calculate_output": Schema.String.annotate({ + "description": "A formula to calculate the output based on grader results." + }) + }).annotate({ "title": "MultiGrader", "description": "The grader used for the fine-tuning job." }) + ], { mode: "oneOf" })) +}).annotate({ "title": "ValidateGraderResponse" }) +export type CreateResponse = { + readonly "metadata"?: Metadata + readonly "top_logprobs"?: number + readonly "temperature"?: number | null + readonly "top_p"?: number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "previous_response_id"?: string | null + readonly "model"?: + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" + readonly "reasoning"?: Reasoning | null + readonly "background"?: boolean | null + readonly "max_tool_calls"?: number | null + readonly "text"?: ResponseTextParam + readonly "tools"?: ToolsArray + readonly "tool_choice"?: ToolChoiceParam + readonly "prompt"?: Prompt + readonly "truncation"?: "auto" | "disabled" | null + readonly "input"?: InputParam + readonly "include"?: ReadonlyArray | null + readonly "parallel_tool_calls"?: boolean | null + readonly "store"?: boolean | null + readonly "instructions"?: string | null + readonly "stream"?: boolean | null + readonly "stream_options"?: ResponseStreamOptions + readonly "conversation"?: ConversationParam | null + readonly "context_management"?: ReadonlyArray | null + readonly "max_output_tokens"?: number | null +} +export const CreateResponse = Schema.Struct({ + "metadata": Schema.optionalKey(Metadata), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(20)).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(20)], { + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }) + ) + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey(Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ])), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n" + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }) + ), + "reasoning": Schema.optionalKey(Schema.Union([Reasoning, Schema.Null])), + "background": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": "Whether to run the model response in the background.\n[Learn more](/docs/guides/background).\n" + }), + Schema.Null + ]) + ), + "max_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "text": Schema.optionalKey(ResponseTextParam), + "tools": Schema.optionalKey(ToolsArray), + "tool_choice": Schema.optionalKey(ToolChoiceParam), + "prompt": Schema.optionalKey(Prompt), + "truncation": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response.\n- `auto`: If the input to this Response exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping items from the beginning of the conversation.\n- `disabled` (default): If the input size will exceed the context window\n size for a model, the request will fail with a 400 error.\n" + }), + Schema.Null + ])), + "input": Schema.optionalKey(InputParam), + "include": Schema.optionalKey(Schema.Union([ + Schema.Array(IncludeEnum).annotate({ + "description": + "Specify additional output data to include in the model response. Currently supported values are:\n- `web_search_call.action.sources`: Include the sources of the web search tool call.\n- `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items.\n- `computer_call_output.output.image_url`: Include image urls from the computer call output.\n- `file_search_call.results`: Include the search results of the file search tool call.\n- `message.input_image.image_url`: Include image urls from the input message.\n- `message.output_text.logprobs`: Include logprobs with assistant messages.\n- `reasoning.encrypted_content`: Includes an encrypted version of reasoning tokens in reasoning item outputs. This enables reasoning items to be used in multi-turn conversations when using the Responses API statelessly (like when the `store` parameter is set to `false`, or when an organization is enrolled in the zero data retention program)." + }), + Schema.Null + ])), + "parallel_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ "description": "Whether to allow the model to run tool calls in parallel.\n" }), + Schema.Null + ]) + ), + "store": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": "Whether to store the generated model response for later retrieval via\nAPI.\n" + }), + Schema.Null + ]) + ), + "instructions": Schema.optionalKey(Schema.Union([ + Schema.String.annotate({ + "description": + "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }), + Schema.Null + ])), + "stream": Schema.optionalKey(Schema.Union([ + Schema.Boolean.annotate({ + "description": + "If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section below](/docs/api-reference/responses-streaming)\nfor more information.\n" + }), + Schema.Null + ])), + "stream_options": Schema.optionalKey(ResponseStreamOptions), + "conversation": Schema.optionalKey(Schema.Union([ConversationParam, Schema.Null])), + "context_management": Schema.optionalKey( + Schema.Union([ + Schema.Array(ContextManagementParam).annotate({ + "description": "Context management configuration for this request.\n" + }).check(Schema.isMinLength(1)), + Schema.Null + ]) + ), + "max_output_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(16)), + Schema.Null + ]) + ) +}) +export type ResponsesClientEventResponseCreate = { + readonly "type": "response.create" + readonly "metadata"?: Metadata + readonly "top_logprobs"?: number + readonly "temperature"?: number | null + readonly "top_p"?: number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "previous_response_id"?: string | null + readonly "model"?: + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" + readonly "reasoning"?: Reasoning | null + readonly "background"?: boolean | null + readonly "max_tool_calls"?: number | null + readonly "text"?: ResponseTextParam + readonly "tools"?: ToolsArray + readonly "tool_choice"?: ToolChoiceParam + readonly "prompt"?: Prompt + readonly "truncation"?: "auto" | "disabled" | null + readonly "input"?: InputParam + readonly "include"?: ReadonlyArray | null + readonly "parallel_tool_calls"?: boolean | null + readonly "store"?: boolean | null + readonly "instructions"?: string | null + readonly "stream"?: boolean | null + readonly "stream_options"?: ResponseStreamOptions + readonly "conversation"?: ConversationParam | null + readonly "context_management"?: ReadonlyArray | null + readonly "max_output_tokens"?: number | null +} +export const ResponsesClientEventResponseCreate = Schema.Struct({ + "type": Schema.Literal("response.create").annotate({ + "description": "The type of the client event. Always `response.create`.\n" + }), + "metadata": Schema.optionalKey(Metadata), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(20)).check( + Schema.makeFilterGroup([Schema.isGreaterThanOrEqualTo(0), Schema.isLessThanOrEqualTo(20)], { + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }) + ) + ]) + ), + "temperature": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]) + ), + "top_p": Schema.optionalKey(Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ])), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n" + }), + Schema.Null + ]) + ), + "model": Schema.optionalKey( + Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }) + ), + "reasoning": Schema.optionalKey(Schema.Union([Reasoning, Schema.Null])), + "background": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": "Whether to run the model response in the background.\n[Learn more](/docs/guides/background).\n" + }), + Schema.Null + ]) + ), + "max_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "text": Schema.optionalKey(ResponseTextParam), + "tools": Schema.optionalKey(ToolsArray), + "tool_choice": Schema.optionalKey(ToolChoiceParam), + "prompt": Schema.optionalKey(Prompt), + "truncation": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response.\n- `auto`: If the input to this Response exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping items from the beginning of the conversation.\n- `disabled` (default): If the input size will exceed the context window\n size for a model, the request will fail with a 400 error.\n" + }), + Schema.Null + ])), + "input": Schema.optionalKey(InputParam), + "include": Schema.optionalKey(Schema.Union([ + Schema.Array(IncludeEnum).annotate({ + "description": + "Specify additional output data to include in the model response. Currently supported values are:\n- `web_search_call.action.sources`: Include the sources of the web search tool call.\n- `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items.\n- `computer_call_output.output.image_url`: Include image urls from the computer call output.\n- `file_search_call.results`: Include the search results of the file search tool call.\n- `message.input_image.image_url`: Include image urls from the input message.\n- `message.output_text.logprobs`: Include logprobs with assistant messages.\n- `reasoning.encrypted_content`: Includes an encrypted version of reasoning tokens in reasoning item outputs. This enables reasoning items to be used in multi-turn conversations when using the Responses API statelessly (like when the `store` parameter is set to `false`, or when an organization is enrolled in the zero data retention program)." + }), + Schema.Null + ])), + "parallel_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ "description": "Whether to allow the model to run tool calls in parallel.\n" }), + Schema.Null + ]) + ), + "store": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": "Whether to store the generated model response for later retrieval via\nAPI.\n" + }), + Schema.Null + ]) + ), + "instructions": Schema.optionalKey(Schema.Union([ + Schema.String.annotate({ + "description": + "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }), + Schema.Null + ])), + "stream": Schema.optionalKey(Schema.Union([ + Schema.Boolean.annotate({ + "description": + "If set to true, the model response data will be streamed to the client\nas it is generated using [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format).\nSee the [Streaming section below](/docs/api-reference/responses-streaming)\nfor more information.\n" + }), + Schema.Null + ])), + "stream_options": Schema.optionalKey(ResponseStreamOptions), + "conversation": Schema.optionalKey(Schema.Union([ConversationParam, Schema.Null])), + "context_management": Schema.optionalKey( + Schema.Union([ + Schema.Array(ContextManagementParam).annotate({ + "description": "Context management configuration for this request.\n" + }).check(Schema.isMinLength(1)), + Schema.Null + ]) + ), + "max_output_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(16)), + Schema.Null + ]) + ) +}).annotate({ + "description": + "Client event for creating a response over a persistent WebSocket connection.\nThis payload uses the same top-level fields as `POST /v1/responses`.\n\nNotes:\n- `stream` is implicit over WebSocket and should not be sent.\n- `background` is not supported over WebSocket.\n" +}) +export type ConversationItemList = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "first_id": string + readonly "last_id": string +} +export const ConversationItemList = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The type of object returned, must be `list`." }), + "data": Schema.Array(ConversationItem).annotate({ "description": "A list of conversation items." }), + "has_more": Schema.Boolean.annotate({ "description": "Whether there are more items available." }), + "first_id": Schema.String.annotate({ "description": "The ID of the first item in the list." }), + "last_id": Schema.String.annotate({ "description": "The ID of the last item in the list." }) +}).annotate({ "title": "The conversation item list", "description": "A list of Conversation items." }) +export type ResponseItemList = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "first_id": string + readonly "last_id": string +} +export const ResponseItemList = Schema.Struct({ + "object": Schema.Literal("list").annotate({ "description": "The type of object returned, must be `list`." }), + "data": Schema.Array(ItemResource).annotate({ "description": "A list of items used to generate this response." }), + "has_more": Schema.Boolean.annotate({ "description": "Whether there are more items available." }), + "first_id": Schema.String.annotate({ "description": "The ID of the first item in the list." }), + "last_id": Schema.String.annotate({ "description": "The ID of the last item in the list." }) +}).annotate({ "description": "A list of Response items." }) +export type Response = { + readonly "metadata": {} | null + readonly "top_logprobs"?: number | null + readonly "temperature": number | null + readonly "top_p": number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "previous_response_id"?: string | null + readonly "model": + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" + readonly "reasoning"?: Reasoning | null + readonly "background"?: boolean | null + readonly "max_tool_calls"?: number | null + readonly "text"?: ResponseTextParam + readonly "tools": ReadonlyArray + readonly "tool_choice": + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMCP + | ToolChoiceCustom + | SpecificApplyPatchParam + | SpecificFunctionShellParam + readonly "prompt"?: Prompt + readonly "truncation"?: "auto" | "disabled" | null + readonly "id": string + readonly "object": "response" + readonly "status"?: "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete" + readonly "created_at": number + readonly "completed_at"?: number | null + readonly "error": ResponseError + readonly "incomplete_details": { readonly "reason"?: "max_output_tokens" | "content_filter" } | null + readonly "output": ReadonlyArray + readonly "instructions": string | ReadonlyArray | null + readonly "output_text"?: string | null + readonly "usage"?: ResponseUsage | null + readonly "parallel_tool_calls": boolean + readonly "conversation"?: Conversation_2 | null + readonly "max_output_tokens"?: number | null +} +export const Response = Schema.Struct({ + "metadata": Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null + ]), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(20)), + Schema.Null + ]) + ), + "temperature": Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]), + "top_p": Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ]), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n" + }), + Schema.Null + ]) + ), + "model": Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }), + "reasoning": Schema.optionalKey(Schema.Union([Reasoning, Schema.Null])), + "background": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": "Whether to run the model response in the background.\n[Learn more](/docs/guides/background).\n" + }), + Schema.Null + ]) + ), + "max_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "text": Schema.optionalKey(ResponseTextParam), + "tools": Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" + }), + "tool_choice": Schema.Union([ + ToolChoiceOptions, + ToolChoiceAllowed, + ToolChoiceTypes, + ToolChoiceFunction, + ToolChoiceMCP, + ToolChoiceCustom, + SpecificApplyPatchParam, + SpecificFunctionShellParam + ], { mode: "oneOf" }).annotate({ + "description": + "How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n" + }), + "prompt": Schema.optionalKey(Prompt), + "truncation": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response.\n- `auto`: If the input to this Response exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping items from the beginning of the conversation.\n- `disabled` (default): If the input size will exceed the context window\n size for a model, the request will fail with a 400 error.\n" + }), + Schema.Null + ])), + "id": Schema.String.annotate({ "description": "Unique identifier for this Response.\n" }), + "object": Schema.Literal("response").annotate({ + "description": "The object type of this resource - always set to `response`.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]).annotate({ + "description": + "The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n" + }) + ), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) of when this Response was created.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + "completed_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Unix timestamp (in seconds) of when this Response was completed.\nOnly present when the status is `completed`.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "error": ResponseError, + "incomplete_details": Schema.Union([ + Schema.Struct({ + "reason": Schema.optionalKey( + Schema.Literals(["max_output_tokens", "content_filter"]).annotate({ + "description": "The reason why the response is incomplete." + }) + ) + }).annotate({ "description": "Details about why the response is incomplete.\n" }), + Schema.Null + ]), + "output": Schema.Array(OutputItem).annotate({ + "description": + "An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n" + }), + "instructions": Schema.Union([ + Schema.Union([ + Schema.String.annotate({ + "description": "A text input to the model, equivalent to a text input with the\n`developer` role.\n" + }), + Schema.Array(InputItem).annotate({ + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }), + Schema.Null + ]), + "output_text": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "SDK-only convenience property that contains the aggregated text output\nfrom all `output_text` items in the `output` array, if any are present.\nSupported in the Python and JavaScript SDKs.\n" + }), + Schema.Null + ]) + ), + "usage": Schema.optionalKey(Schema.Union([ResponseUsage, Schema.Null])), + "parallel_tool_calls": Schema.Boolean.annotate({ + "description": "Whether to allow the model to run tool calls in parallel.\n" + }), + "conversation": Schema.optionalKey(Schema.Union([Conversation_2, Schema.Null])), + "max_output_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ) +}).annotate({ "title": "The response object" }) +export type ResponseCompletedEvent = { + readonly "type": "response.completed" + readonly "response": { + readonly "metadata": {} | null + readonly "top_logprobs"?: number | null + readonly "temperature": number | null + readonly "top_p": number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "previous_response_id"?: string | null + readonly "model": + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" + readonly "reasoning"?: Reasoning | null + readonly "background"?: boolean | null + readonly "max_tool_calls"?: number | null + readonly "text"?: ResponseTextParam + readonly "tools": ReadonlyArray + readonly "tool_choice": + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMCP + | ToolChoiceCustom + | SpecificApplyPatchParam + | SpecificFunctionShellParam + readonly "prompt"?: Prompt + readonly "truncation"?: "auto" | "disabled" | null + readonly "id": string + readonly "object": "response" + readonly "status"?: "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete" + readonly "created_at": number + readonly "completed_at"?: number | null + readonly "error": ResponseError + readonly "incomplete_details": { readonly "reason"?: "max_output_tokens" | "content_filter" } | null + readonly "output": ReadonlyArray + readonly "instructions": string | ReadonlyArray | null + readonly "output_text"?: string | null + readonly "usage"?: ResponseUsage | null + readonly "parallel_tool_calls": boolean + readonly "conversation"?: Conversation_2 | null + readonly "max_output_tokens"?: number | null + } + readonly "sequence_number": number +} +export const ResponseCompletedEvent = Schema.Struct({ + "type": Schema.Literal("response.completed").annotate({ + "description": "The type of the event. Always `response.completed`.\n" + }), + "response": Schema.Struct({ + "metadata": Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null + ]), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(20)), + Schema.Null + ]) + ), + "temperature": Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]), + "top_p": Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ]), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n" + }), + Schema.Null + ]) + ), + "model": Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }), + "reasoning": Schema.optionalKey(Schema.Union([Reasoning, Schema.Null])), + "background": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Whether to run the model response in the background.\n[Learn more](/docs/guides/background).\n" + }), + Schema.Null + ]) + ), + "max_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "text": Schema.optionalKey(ResponseTextParam), + "tools": Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" + }), + "tool_choice": Schema.Union([ + ToolChoiceOptions, + ToolChoiceAllowed, + ToolChoiceTypes, + ToolChoiceFunction, + ToolChoiceMCP, + ToolChoiceCustom, + SpecificApplyPatchParam, + SpecificFunctionShellParam + ], { mode: "oneOf" }).annotate({ + "description": + "How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n" + }), + "prompt": Schema.optionalKey(Prompt), + "truncation": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response.\n- `auto`: If the input to this Response exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping items from the beginning of the conversation.\n- `disabled` (default): If the input size will exceed the context window\n size for a model, the request will fail with a 400 error.\n" + }), + Schema.Null + ])), + "id": Schema.String.annotate({ "description": "Unique identifier for this Response.\n" }), + "object": Schema.Literal("response").annotate({ + "description": "The object type of this resource - always set to `response`.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]).annotate({ + "description": + "The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n" + }) + ), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) of when this Response was created.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + "completed_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Unix timestamp (in seconds) of when this Response was completed.\nOnly present when the status is `completed`.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "error": ResponseError, + "incomplete_details": Schema.Union([ + Schema.Struct({ + "reason": Schema.optionalKey( + Schema.Literals(["max_output_tokens", "content_filter"]).annotate({ + "description": "The reason why the response is incomplete." + }) + ) + }).annotate({ "description": "Details about why the response is incomplete.\n" }), + Schema.Null + ]), + "output": Schema.Array(OutputItem).annotate({ + "description": + "An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n" + }), + "instructions": Schema.Union([ + Schema.Union([ + Schema.String.annotate({ + "description": "A text input to the model, equivalent to a text input with the\n`developer` role.\n" + }), + Schema.Array(InputItem).annotate({ + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }), + Schema.Null + ]), + "output_text": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "SDK-only convenience property that contains the aggregated text output\nfrom all `output_text` items in the `output` array, if any are present.\nSupported in the Python and JavaScript SDKs.\n" + }), + Schema.Null + ]) + ), + "usage": Schema.optionalKey(Schema.Union([ResponseUsage, Schema.Null])), + "parallel_tool_calls": Schema.Boolean.annotate({ + "description": "Whether to allow the model to run tool calls in parallel.\n" + }), + "conversation": Schema.optionalKey(Schema.Union([Conversation_2, Schema.Null])), + "max_output_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ) + }).annotate({ "title": "The response object", "description": "Properties of the completed response.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number for this event." }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when the model response is complete." }) +export type ResponseCreatedEvent = { + readonly "type": "response.created" + readonly "response": { + readonly "metadata": {} | null + readonly "top_logprobs"?: number | null + readonly "temperature": number | null + readonly "top_p": number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "previous_response_id"?: string | null + readonly "model": + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" + readonly "reasoning"?: Reasoning | null + readonly "background"?: boolean | null + readonly "max_tool_calls"?: number | null + readonly "text"?: ResponseTextParam + readonly "tools": ReadonlyArray + readonly "tool_choice": + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMCP + | ToolChoiceCustom + | SpecificApplyPatchParam + | SpecificFunctionShellParam + readonly "prompt"?: Prompt + readonly "truncation"?: "auto" | "disabled" | null + readonly "id": string + readonly "object": "response" + readonly "status"?: "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete" + readonly "created_at": number + readonly "completed_at"?: number | null + readonly "error": ResponseError + readonly "incomplete_details": { readonly "reason"?: "max_output_tokens" | "content_filter" } | null + readonly "output": ReadonlyArray + readonly "instructions": string | ReadonlyArray | null + readonly "output_text"?: string | null + readonly "usage"?: ResponseUsage | null + readonly "parallel_tool_calls": boolean + readonly "conversation"?: Conversation_2 | null + readonly "max_output_tokens"?: number | null + } + readonly "sequence_number": number +} +export const ResponseCreatedEvent = Schema.Struct({ + "type": Schema.Literal("response.created").annotate({ + "description": "The type of the event. Always `response.created`.\n" + }), + "response": Schema.Struct({ + "metadata": Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null + ]), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(20)), + Schema.Null + ]) + ), + "temperature": Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]), + "top_p": Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ]), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n" + }), + Schema.Null + ]) + ), + "model": Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }), + "reasoning": Schema.optionalKey(Schema.Union([Reasoning, Schema.Null])), + "background": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Whether to run the model response in the background.\n[Learn more](/docs/guides/background).\n" + }), + Schema.Null + ]) + ), + "max_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "text": Schema.optionalKey(ResponseTextParam), + "tools": Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" + }), + "tool_choice": Schema.Union([ + ToolChoiceOptions, + ToolChoiceAllowed, + ToolChoiceTypes, + ToolChoiceFunction, + ToolChoiceMCP, + ToolChoiceCustom, + SpecificApplyPatchParam, + SpecificFunctionShellParam + ], { mode: "oneOf" }).annotate({ + "description": + "How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n" + }), + "prompt": Schema.optionalKey(Prompt), + "truncation": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response.\n- `auto`: If the input to this Response exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping items from the beginning of the conversation.\n- `disabled` (default): If the input size will exceed the context window\n size for a model, the request will fail with a 400 error.\n" + }), + Schema.Null + ])), + "id": Schema.String.annotate({ "description": "Unique identifier for this Response.\n" }), + "object": Schema.Literal("response").annotate({ + "description": "The object type of this resource - always set to `response`.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]).annotate({ + "description": + "The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n" + }) + ), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) of when this Response was created.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + "completed_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Unix timestamp (in seconds) of when this Response was completed.\nOnly present when the status is `completed`.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "error": ResponseError, + "incomplete_details": Schema.Union([ + Schema.Struct({ + "reason": Schema.optionalKey( + Schema.Literals(["max_output_tokens", "content_filter"]).annotate({ + "description": "The reason why the response is incomplete." + }) + ) + }).annotate({ "description": "Details about why the response is incomplete.\n" }), + Schema.Null + ]), + "output": Schema.Array(OutputItem).annotate({ + "description": + "An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n" + }), + "instructions": Schema.Union([ + Schema.Union([ + Schema.String.annotate({ + "description": "A text input to the model, equivalent to a text input with the\n`developer` role.\n" + }), + Schema.Array(InputItem).annotate({ + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }), + Schema.Null + ]), + "output_text": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "SDK-only convenience property that contains the aggregated text output\nfrom all `output_text` items in the `output` array, if any are present.\nSupported in the Python and JavaScript SDKs.\n" + }), + Schema.Null + ]) + ), + "usage": Schema.optionalKey(Schema.Union([ResponseUsage, Schema.Null])), + "parallel_tool_calls": Schema.Boolean.annotate({ + "description": "Whether to allow the model to run tool calls in parallel.\n" + }), + "conversation": Schema.optionalKey(Schema.Union([Conversation_2, Schema.Null])), + "max_output_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ) + }).annotate({ "title": "The response object", "description": "The response that was created.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number for this event." }).check( + Schema.isInt() + ) +}).annotate({ "description": "An event that is emitted when a response is created.\n" }) +export type ResponseFailedEvent = { + readonly "type": "response.failed" + readonly "sequence_number": number + readonly "response": { + readonly "metadata": {} | null + readonly "top_logprobs"?: number | null + readonly "temperature": number | null + readonly "top_p": number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "previous_response_id"?: string | null + readonly "model": + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" + readonly "reasoning"?: Reasoning | null + readonly "background"?: boolean | null + readonly "max_tool_calls"?: number | null + readonly "text"?: ResponseTextParam + readonly "tools": ReadonlyArray + readonly "tool_choice": + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMCP + | ToolChoiceCustom + | SpecificApplyPatchParam + | SpecificFunctionShellParam + readonly "prompt"?: Prompt + readonly "truncation"?: "auto" | "disabled" | null + readonly "id": string + readonly "object": "response" + readonly "status"?: "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete" + readonly "created_at": number + readonly "completed_at"?: number | null + readonly "error": ResponseError + readonly "incomplete_details": { readonly "reason"?: "max_output_tokens" | "content_filter" } | null + readonly "output": ReadonlyArray + readonly "instructions": string | ReadonlyArray | null + readonly "output_text"?: string | null + readonly "usage"?: ResponseUsage | null + readonly "parallel_tool_calls": boolean + readonly "conversation"?: Conversation_2 | null + readonly "max_output_tokens"?: number | null + } +} +export const ResponseFailedEvent = Schema.Struct({ + "type": Schema.Literal("response.failed").annotate({ + "description": "The type of the event. Always `response.failed`.\n" + }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ), + "response": Schema.Struct({ + "metadata": Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null + ]), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(20)), + Schema.Null + ]) + ), + "temperature": Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]), + "top_p": Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ]), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n" + }), + Schema.Null + ]) + ), + "model": Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }), + "reasoning": Schema.optionalKey(Schema.Union([Reasoning, Schema.Null])), + "background": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Whether to run the model response in the background.\n[Learn more](/docs/guides/background).\n" + }), + Schema.Null + ]) + ), + "max_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "text": Schema.optionalKey(ResponseTextParam), + "tools": Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" + }), + "tool_choice": Schema.Union([ + ToolChoiceOptions, + ToolChoiceAllowed, + ToolChoiceTypes, + ToolChoiceFunction, + ToolChoiceMCP, + ToolChoiceCustom, + SpecificApplyPatchParam, + SpecificFunctionShellParam + ], { mode: "oneOf" }).annotate({ + "description": + "How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n" + }), + "prompt": Schema.optionalKey(Prompt), + "truncation": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response.\n- `auto`: If the input to this Response exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping items from the beginning of the conversation.\n- `disabled` (default): If the input size will exceed the context window\n size for a model, the request will fail with a 400 error.\n" + }), + Schema.Null + ])), + "id": Schema.String.annotate({ "description": "Unique identifier for this Response.\n" }), + "object": Schema.Literal("response").annotate({ + "description": "The object type of this resource - always set to `response`.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]).annotate({ + "description": + "The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n" + }) + ), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) of when this Response was created.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + "completed_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Unix timestamp (in seconds) of when this Response was completed.\nOnly present when the status is `completed`.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "error": ResponseError, + "incomplete_details": Schema.Union([ + Schema.Struct({ + "reason": Schema.optionalKey( + Schema.Literals(["max_output_tokens", "content_filter"]).annotate({ + "description": "The reason why the response is incomplete." + }) + ) + }).annotate({ "description": "Details about why the response is incomplete.\n" }), + Schema.Null + ]), + "output": Schema.Array(OutputItem).annotate({ + "description": + "An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n" + }), + "instructions": Schema.Union([ + Schema.Union([ + Schema.String.annotate({ + "description": "A text input to the model, equivalent to a text input with the\n`developer` role.\n" + }), + Schema.Array(InputItem).annotate({ + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }), + Schema.Null + ]), + "output_text": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "SDK-only convenience property that contains the aggregated text output\nfrom all `output_text` items in the `output` array, if any are present.\nSupported in the Python and JavaScript SDKs.\n" + }), + Schema.Null + ]) + ), + "usage": Schema.optionalKey(Schema.Union([ResponseUsage, Schema.Null])), + "parallel_tool_calls": Schema.Boolean.annotate({ + "description": "Whether to allow the model to run tool calls in parallel.\n" + }), + "conversation": Schema.optionalKey(Schema.Union([Conversation_2, Schema.Null])), + "max_output_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ) + }).annotate({ "title": "The response object", "description": "The response that failed.\n" }) +}).annotate({ "description": "An event that is emitted when a response fails.\n" }) +export type ResponseInProgressEvent = { + readonly "type": "response.in_progress" + readonly "response": { + readonly "metadata": {} | null + readonly "top_logprobs"?: number | null + readonly "temperature": number | null + readonly "top_p": number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "previous_response_id"?: string | null + readonly "model": + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" + readonly "reasoning"?: Reasoning | null + readonly "background"?: boolean | null + readonly "max_tool_calls"?: number | null + readonly "text"?: ResponseTextParam + readonly "tools": ReadonlyArray + readonly "tool_choice": + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMCP + | ToolChoiceCustom + | SpecificApplyPatchParam + | SpecificFunctionShellParam + readonly "prompt"?: Prompt + readonly "truncation"?: "auto" | "disabled" | null + readonly "id": string + readonly "object": "response" + readonly "status"?: "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete" + readonly "created_at": number + readonly "completed_at"?: number | null + readonly "error": ResponseError + readonly "incomplete_details": { readonly "reason"?: "max_output_tokens" | "content_filter" } | null + readonly "output": ReadonlyArray + readonly "instructions": string | ReadonlyArray | null + readonly "output_text"?: string | null + readonly "usage"?: ResponseUsage | null + readonly "parallel_tool_calls": boolean + readonly "conversation"?: Conversation_2 | null + readonly "max_output_tokens"?: number | null + } + readonly "sequence_number": number +} +export const ResponseInProgressEvent = Schema.Struct({ + "type": Schema.Literal("response.in_progress").annotate({ + "description": "The type of the event. Always `response.in_progress`.\n" + }), + "response": Schema.Struct({ + "metadata": Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null + ]), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(20)), + Schema.Null + ]) + ), + "temperature": Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]), + "top_p": Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ]), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n" + }), + Schema.Null + ]) + ), + "model": Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }), + "reasoning": Schema.optionalKey(Schema.Union([Reasoning, Schema.Null])), + "background": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Whether to run the model response in the background.\n[Learn more](/docs/guides/background).\n" + }), + Schema.Null + ]) + ), + "max_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "text": Schema.optionalKey(ResponseTextParam), + "tools": Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" + }), + "tool_choice": Schema.Union([ + ToolChoiceOptions, + ToolChoiceAllowed, + ToolChoiceTypes, + ToolChoiceFunction, + ToolChoiceMCP, + ToolChoiceCustom, + SpecificApplyPatchParam, + SpecificFunctionShellParam + ], { mode: "oneOf" }).annotate({ + "description": + "How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n" + }), + "prompt": Schema.optionalKey(Prompt), + "truncation": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response.\n- `auto`: If the input to this Response exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping items from the beginning of the conversation.\n- `disabled` (default): If the input size will exceed the context window\n size for a model, the request will fail with a 400 error.\n" + }), + Schema.Null + ])), + "id": Schema.String.annotate({ "description": "Unique identifier for this Response.\n" }), + "object": Schema.Literal("response").annotate({ + "description": "The object type of this resource - always set to `response`.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]).annotate({ + "description": + "The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n" + }) + ), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) of when this Response was created.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + "completed_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Unix timestamp (in seconds) of when this Response was completed.\nOnly present when the status is `completed`.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "error": ResponseError, + "incomplete_details": Schema.Union([ + Schema.Struct({ + "reason": Schema.optionalKey( + Schema.Literals(["max_output_tokens", "content_filter"]).annotate({ + "description": "The reason why the response is incomplete." + }) + ) + }).annotate({ "description": "Details about why the response is incomplete.\n" }), + Schema.Null + ]), + "output": Schema.Array(OutputItem).annotate({ + "description": + "An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n" + }), + "instructions": Schema.Union([ + Schema.Union([ + Schema.String.annotate({ + "description": "A text input to the model, equivalent to a text input with the\n`developer` role.\n" + }), + Schema.Array(InputItem).annotate({ + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }), + Schema.Null + ]), + "output_text": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "SDK-only convenience property that contains the aggregated text output\nfrom all `output_text` items in the `output` array, if any are present.\nSupported in the Python and JavaScript SDKs.\n" + }), + Schema.Null + ]) + ), + "usage": Schema.optionalKey(Schema.Union([ResponseUsage, Schema.Null])), + "parallel_tool_calls": Schema.Boolean.annotate({ + "description": "Whether to allow the model to run tool calls in parallel.\n" + }), + "conversation": Schema.optionalKey(Schema.Union([Conversation_2, Schema.Null])), + "max_output_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ) + }).annotate({ "title": "The response object", "description": "The response that is in progress.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ "description": "Emitted when the response is in progress." }) +export type ResponseIncompleteEvent = { + readonly "type": "response.incomplete" + readonly "response": { + readonly "metadata": {} | null + readonly "top_logprobs"?: number | null + readonly "temperature": number | null + readonly "top_p": number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "previous_response_id"?: string | null + readonly "model": + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" + readonly "reasoning"?: Reasoning | null + readonly "background"?: boolean | null + readonly "max_tool_calls"?: number | null + readonly "text"?: ResponseTextParam + readonly "tools": ReadonlyArray + readonly "tool_choice": + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMCP + | ToolChoiceCustom + | SpecificApplyPatchParam + | SpecificFunctionShellParam + readonly "prompt"?: Prompt + readonly "truncation"?: "auto" | "disabled" | null + readonly "id": string + readonly "object": "response" + readonly "status"?: "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete" + readonly "created_at": number + readonly "completed_at"?: number | null + readonly "error": ResponseError + readonly "incomplete_details": { readonly "reason"?: "max_output_tokens" | "content_filter" } | null + readonly "output": ReadonlyArray + readonly "instructions": string | ReadonlyArray | null + readonly "output_text"?: string | null + readonly "usage"?: ResponseUsage | null + readonly "parallel_tool_calls": boolean + readonly "conversation"?: Conversation_2 | null + readonly "max_output_tokens"?: number | null + } + readonly "sequence_number": number +} +export const ResponseIncompleteEvent = Schema.Struct({ + "type": Schema.Literal("response.incomplete").annotate({ + "description": "The type of the event. Always `response.incomplete`.\n" + }), + "response": Schema.Struct({ + "metadata": Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null + ]), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(20)), + Schema.Null + ]) + ), + "temperature": Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]), + "top_p": Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ]), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n" + }), + Schema.Null + ]) + ), + "model": Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }), + "reasoning": Schema.optionalKey(Schema.Union([Reasoning, Schema.Null])), + "background": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Whether to run the model response in the background.\n[Learn more](/docs/guides/background).\n" + }), + Schema.Null + ]) + ), + "max_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "text": Schema.optionalKey(ResponseTextParam), + "tools": Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" + }), + "tool_choice": Schema.Union([ + ToolChoiceOptions, + ToolChoiceAllowed, + ToolChoiceTypes, + ToolChoiceFunction, + ToolChoiceMCP, + ToolChoiceCustom, + SpecificApplyPatchParam, + SpecificFunctionShellParam + ], { mode: "oneOf" }).annotate({ + "description": + "How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n" + }), + "prompt": Schema.optionalKey(Prompt), + "truncation": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response.\n- `auto`: If the input to this Response exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping items from the beginning of the conversation.\n- `disabled` (default): If the input size will exceed the context window\n size for a model, the request will fail with a 400 error.\n" + }), + Schema.Null + ])), + "id": Schema.String.annotate({ "description": "Unique identifier for this Response.\n" }), + "object": Schema.Literal("response").annotate({ + "description": "The object type of this resource - always set to `response`.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]).annotate({ + "description": + "The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n" + }) + ), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) of when this Response was created.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + "completed_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Unix timestamp (in seconds) of when this Response was completed.\nOnly present when the status is `completed`.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "error": ResponseError, + "incomplete_details": Schema.Union([ + Schema.Struct({ + "reason": Schema.optionalKey( + Schema.Literals(["max_output_tokens", "content_filter"]).annotate({ + "description": "The reason why the response is incomplete." + }) + ) + }).annotate({ "description": "Details about why the response is incomplete.\n" }), + Schema.Null + ]), + "output": Schema.Array(OutputItem).annotate({ + "description": + "An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n" + }), + "instructions": Schema.Union([ + Schema.Union([ + Schema.String.annotate({ + "description": "A text input to the model, equivalent to a text input with the\n`developer` role.\n" + }), + Schema.Array(InputItem).annotate({ + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }), + Schema.Null + ]), + "output_text": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "SDK-only convenience property that contains the aggregated text output\nfrom all `output_text` items in the `output` array, if any are present.\nSupported in the Python and JavaScript SDKs.\n" + }), + Schema.Null + ]) + ), + "usage": Schema.optionalKey(Schema.Union([ResponseUsage, Schema.Null])), + "parallel_tool_calls": Schema.Boolean.annotate({ + "description": "Whether to allow the model to run tool calls in parallel.\n" + }), + "conversation": Schema.optionalKey(Schema.Union([Conversation_2, Schema.Null])), + "max_output_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ) + }).annotate({ "title": "The response object", "description": "The response that was incomplete.\n" }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number of this event." }).check( + Schema.isInt() + ) +}).annotate({ "description": "An event that is emitted when a response finishes as incomplete.\n" }) +export type ResponseQueuedEvent = { + readonly "type": "response.queued" + readonly "response": { + readonly "metadata": {} | null + readonly "top_logprobs"?: number | null + readonly "temperature": number | null + readonly "top_p": number | null + readonly "user"?: string | null + readonly "safety_identifier"?: string + readonly "prompt_cache_key"?: string | null + readonly "service_tier"?: ServiceTier + readonly "prompt_cache_retention"?: "in_memory" | "in_memory" | "24h" | null + readonly "previous_response_id"?: string | null + readonly "model": + | ModelIdsShared + | "o1-pro" + | "o1-pro-2025-03-19" + | "o3-pro" + | "o3-pro-2025-06-10" + | "o3-deep-research" + | "o3-deep-research-2025-06-26" + | "o4-mini-deep-research" + | "o4-mini-deep-research-2025-06-26" + | "computer-use-preview" + | "computer-use-preview-2025-03-11" + | "gpt-5-codex" + | "gpt-5-pro" + | "gpt-5-pro-2025-10-06" + | "gpt-5.1-codex-max" + readonly "reasoning"?: Reasoning | null + readonly "background"?: boolean | null + readonly "max_tool_calls"?: number | null + readonly "text"?: ResponseTextParam + readonly "tools": ReadonlyArray + readonly "tool_choice": + | ToolChoiceOptions + | ToolChoiceAllowed + | ToolChoiceTypes + | ToolChoiceFunction + | ToolChoiceMCP + | ToolChoiceCustom + | SpecificApplyPatchParam + | SpecificFunctionShellParam + readonly "prompt"?: Prompt + readonly "truncation"?: "auto" | "disabled" | null + readonly "id": string + readonly "object": "response" + readonly "status"?: "completed" | "failed" | "in_progress" | "cancelled" | "queued" | "incomplete" + readonly "created_at": number + readonly "completed_at"?: number | null + readonly "error": ResponseError + readonly "incomplete_details": { readonly "reason"?: "max_output_tokens" | "content_filter" } | null + readonly "output": ReadonlyArray + readonly "instructions": string | ReadonlyArray | null + readonly "output_text"?: string | null + readonly "usage"?: ResponseUsage | null + readonly "parallel_tool_calls": boolean + readonly "conversation"?: Conversation_2 | null + readonly "max_output_tokens"?: number | null + } + readonly "sequence_number": number +} +export const ResponseQueuedEvent = Schema.Struct({ + "type": Schema.Literal("response.queued").annotate({ + "description": "The type of the event. Always 'response.queued'." + }), + "response": Schema.Struct({ + "metadata": Schema.Union([ + Schema.Struct({}).annotate({ + "description": + "Set of 16 key-value pairs that can be attached to an object. This can be\nuseful for storing additional information about the object in a structured\nformat, and querying for objects via API or the dashboard.\n\nKeys are strings with a maximum length of 64 characters. Values are strings\nwith a maximum length of 512 characters.\n" + }), + Schema.Null + ]), + "top_logprobs": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An integer between 0 and 20 specifying the maximum number of most likely\ntokens to return at each token position, each with an associated log\nprobability. In some cases, the number of returned tokens may be fewer than\nrequested.\n" + }).check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(20)), + Schema.Null + ]) + ), + "temperature": Schema.Union([ + Schema.Number.annotate({ + "description": + "What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.\nWe generally recommend altering this or `top_p` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(2)), + Schema.Null + ]), + "top_p": Schema.Union([ + Schema.Number.annotate({ + "description": + "An alternative to sampling with temperature, called nucleus sampling,\nwhere the model considers the results of the tokens with top_p probability\nmass. So 0.1 means only the tokens comprising the top 10% probability mass\nare considered.\n\nWe generally recommend altering this or `temperature` but not both.\n" + }).check(Schema.isFinite()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1)), + Schema.Null + ]), + "user": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations.\nA stable identifier for your end-users.\nUsed to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }) + ), + "safety_identifier": Schema.optionalKey(Schema.Union([Schema.String.check(Schema.isMaxLength(64, { + "description": + "A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies.\nThe IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers).\n" + }))])), + "prompt_cache_key": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the `user` field. [Learn more](/docs/guides/prompt-caching).\n" + }) + ), + "service_tier": Schema.optionalKey(ServiceTier), + "prompt_cache_retention": Schema.optionalKey( + Schema.Union([ + Schema.Literals(["in_memory", "in_memory", "24h"]).annotate({ + "description": + "The retention policy for the prompt cache. Set to `24h` to enable extended prompt caching, which keeps cached prefixes active for longer, up to a maximum of 24 hours. [Learn more](/docs/guides/prompt-caching#prompt-cache-retention).\n" + }), + Schema.Null + ]) + ), + "previous_response_id": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "The unique ID of the previous response to the model. Use this to\ncreate multi-turn conversations. Learn more about\n[conversation state](/docs/guides/conversation-state). Cannot be used in conjunction with `conversation`.\n" + }), + Schema.Null + ]) + ), + "model": Schema.Union([ + ModelIdsShared, + Schema.Literals([ + "o1-pro", + "o1-pro-2025-03-19", + "o3-pro", + "o3-pro-2025-06-10", + "o3-deep-research", + "o3-deep-research-2025-06-26", + "o4-mini-deep-research", + "o4-mini-deep-research-2025-06-26", + "computer-use-preview", + "computer-use-preview-2025-03-11", + "gpt-5-codex", + "gpt-5-pro", + "gpt-5-pro-2025-10-06", + "gpt-5.1-codex-max" + ]).annotate({ "title": "ResponsesOnlyModel" }) + ]).annotate({ + "description": + "Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI\noffers a wide range of models with different capabilities, performance\ncharacteristics, and price points. Refer to the [model guide](/docs/models)\nto browse and compare available models.\n" + }), + "reasoning": Schema.optionalKey(Schema.Union([Reasoning, Schema.Null])), + "background": Schema.optionalKey( + Schema.Union([ + Schema.Boolean.annotate({ + "description": + "Whether to run the model response in the background.\n[Learn more](/docs/guides/background).\n" + }), + Schema.Null + ]) + ), + "max_tool_calls": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The maximum number of total calls to built-in tools that can be processed in a response. This maximum number applies across all built-in tool calls, not per individual tool. Any further attempts to call a tool by the model will be ignored.\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "text": Schema.optionalKey(ResponseTextParam), + "tools": Schema.Array(Tool).annotate({ + "description": + "An array of tools the model may call while generating a response. You\ncan specify which tool to use by setting the `tool_choice` parameter.\n\nWe support the following categories of tools:\n- **Built-in tools**: Tools that are provided by OpenAI that extend the\n model's capabilities, like [web search](/docs/guides/tools-web-search)\n or [file search](/docs/guides/tools-file-search). Learn more about\n [built-in tools](/docs/guides/tools).\n- **MCP Tools**: Integrations with third-party systems via custom MCP servers\n or predefined connectors such as Google Drive and SharePoint. Learn more about\n [MCP Tools](/docs/guides/tools-connectors-mcp).\n- **Function calls (custom tools)**: Functions that are defined by you,\n enabling the model to call your own code with strongly typed arguments\n and outputs. Learn more about\n [function calling](/docs/guides/function-calling). You can also use\n custom tools to call your own code.\n" + }), + "tool_choice": Schema.Union([ + ToolChoiceOptions, + ToolChoiceAllowed, + ToolChoiceTypes, + ToolChoiceFunction, + ToolChoiceMCP, + ToolChoiceCustom, + SpecificApplyPatchParam, + SpecificFunctionShellParam + ], { mode: "oneOf" }).annotate({ + "description": + "How the model should select which tool (or tools) to use when generating\na response. See the `tools` parameter to see how to specify which tools\nthe model can call.\n" + }), + "prompt": Schema.optionalKey(Prompt), + "truncation": Schema.optionalKey(Schema.Union([ + Schema.Literals(["auto", "disabled"]).annotate({ + "description": + "The truncation strategy to use for the model response.\n- `auto`: If the input to this Response exceeds\n the model's context window size, the model will truncate the\n response to fit the context window by dropping items from the beginning of the conversation.\n- `disabled` (default): If the input size will exceed the context window\n size for a model, the request will fail with a 400 error.\n" + }), + Schema.Null + ])), + "id": Schema.String.annotate({ "description": "Unique identifier for this Response.\n" }), + "object": Schema.Literal("response").annotate({ + "description": "The object type of this resource - always set to `response`.\n" + }), + "status": Schema.optionalKey( + Schema.Literals(["completed", "failed", "in_progress", "cancelled", "queued", "incomplete"]).annotate({ + "description": + "The status of the response generation. One of `completed`, `failed`,\n`in_progress`, `cancelled`, `queued`, or `incomplete`.\n" + }) + ), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) of when this Response was created.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + "completed_at": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "Unix timestamp (in seconds) of when this Response was completed.\nOnly present when the status is `completed`.\n", + "format": "unixtime" + }).check(Schema.isFinite()), + Schema.Null + ]) + ), + "error": ResponseError, + "incomplete_details": Schema.Union([ + Schema.Struct({ + "reason": Schema.optionalKey( + Schema.Literals(["max_output_tokens", "content_filter"]).annotate({ + "description": "The reason why the response is incomplete." + }) + ) + }).annotate({ "description": "Details about why the response is incomplete.\n" }), + Schema.Null + ]), + "output": Schema.Array(OutputItem).annotate({ + "description": + "An array of content items generated by the model.\n\n- The length and order of items in the `output` array is dependent\n on the model's response.\n- Rather than accessing the first item in the `output` array and\n assuming it's an `assistant` message with the content generated by\n the model, you might consider using the `output_text` property where\n supported in SDKs.\n" + }), + "instructions": Schema.Union([ + Schema.Union([ + Schema.String.annotate({ + "description": "A text input to the model, equivalent to a text input with the\n`developer` role.\n" + }), + Schema.Array(InputItem).annotate({ + "title": "Input item list", + "description": "A list of one or many input items to the model, containing\ndifferent content types.\n" + }) + ], { mode: "oneOf" }).annotate({ + "description": + "A system (or developer) message inserted into the model's context.\n\nWhen using along with `previous_response_id`, the instructions from a previous\nresponse will not be carried over to the next response. This makes it simple\nto swap out system (or developer) messages in new responses.\n" + }), + Schema.Null + ]), + "output_text": Schema.optionalKey( + Schema.Union([ + Schema.String.annotate({ + "description": + "SDK-only convenience property that contains the aggregated text output\nfrom all `output_text` items in the `output` array, if any are present.\nSupported in the Python and JavaScript SDKs.\n" + }), + Schema.Null + ]) + ), + "usage": Schema.optionalKey(Schema.Union([ResponseUsage, Schema.Null])), + "parallel_tool_calls": Schema.Boolean.annotate({ + "description": "Whether to allow the model to run tool calls in parallel.\n" + }), + "conversation": Schema.optionalKey(Schema.Union([Conversation_2, Schema.Null])), + "max_output_tokens": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](/docs/guides/reasoning).\n" + }).check(Schema.isInt()), + Schema.Null + ]) + ) + }).annotate({ "title": "The response object", "description": "The full response object that is queued." }), + "sequence_number": Schema.Number.annotate({ "description": "The sequence number for this event." }).check( + Schema.isInt() + ) +}).annotate({ + "title": "ResponseQueuedEvent", + "description": "Emitted when a response is queued and waiting to be processed.\n" +}) +export type CompactResource = { + readonly "id": string + readonly "object": "response.compaction" + readonly "output": ReadonlyArray + readonly "created_at": number + readonly "usage": { + readonly "input_tokens": number + readonly "input_tokens_details": { readonly "cached_tokens": number } + readonly "output_tokens": number + readonly "output_tokens_details": { readonly "reasoning_tokens": number } + readonly "total_tokens": number + } +} +export const CompactResource = Schema.Struct({ + "id": Schema.String.annotate({ "description": "The unique identifier for the compacted response." }), + "object": Schema.Literal("response.compaction").annotate({ + "description": "The object type. Always `response.compaction`." + }), + "output": Schema.Array(ItemField).annotate({ "description": "The compacted list of output items." }), + "created_at": Schema.Number.annotate({ + "description": "Unix timestamp (in seconds) when the compacted conversation was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "usage": Schema.Struct({ + "input_tokens": Schema.Number.annotate({ "description": "The number of input tokens." }).check(Schema.isInt()), + "input_tokens_details": Schema.Struct({ + "cached_tokens": Schema.Number.annotate({ + "description": + "The number of tokens that were retrieved from the cache. \n[More on prompt caching](/docs/guides/prompt-caching).\n" + }).check(Schema.isInt()) + }).annotate({ "description": "A detailed breakdown of the input tokens." }), + "output_tokens": Schema.Number.annotate({ "description": "The number of output tokens." }).check(Schema.isInt()), + "output_tokens_details": Schema.Struct({ + "reasoning_tokens": Schema.Number.annotate({ "description": "The number of reasoning tokens." }).check( + Schema.isInt() + ) + }).annotate({ "description": "A detailed breakdown of the output tokens." }), + "total_tokens": Schema.Number.annotate({ "description": "The total number of tokens used." }).check(Schema.isInt()) + }).annotate({ + "description": "Token accounting for the compaction pass, including cached, reasoning, and total tokens." + }) +}).annotate({ "title": "The compacted response object" }) +export type EvalList = { + readonly "object": "list" + readonly "data": ReadonlyArray + readonly "first_id": string + readonly "last_id": string + readonly "has_more": boolean +} +export const EvalList = Schema.Struct({ + "object": Schema.Literal("list").annotate({ + "description": "The type of this object. It is always set to \"list\".\n" + }), + "data": Schema.Array(Eval).annotate({ "description": "An array of eval objects.\n" }), + "first_id": Schema.String.annotate({ "description": "The identifier of the first eval in the data array." }), + "last_id": Schema.String.annotate({ "description": "The identifier of the last eval in the data array." }), + "has_more": Schema.Boolean.annotate({ "description": "Indicates whether there are more evals available." }) +}).annotate({ "title": "EvalList", "description": "An object representing a list of evals.\n" }) +export type FineTuneMethod = { + readonly "type": "supervised" | "dpo" | "reinforcement" + readonly "supervised"?: FineTuneSupervisedMethod + readonly "dpo"?: FineTuneDPOMethod + readonly "reinforcement"?: FineTuneReinforcementMethod +} +export const FineTuneMethod = Schema.Struct({ + "type": Schema.Literals(["supervised", "dpo", "reinforcement"]).annotate({ + "description": "The type of method. Is either `supervised`, `dpo`, or `reinforcement`." + }), + "supervised": Schema.optionalKey(FineTuneSupervisedMethod), + "dpo": Schema.optionalKey(FineTuneDPOMethod), + "reinforcement": Schema.optionalKey(FineTuneReinforcementMethod) +}).annotate({ "description": "The method used for fine-tuning." }) +export type ResponseStreamEvent = + | ResponseAudioDeltaEvent + | ResponseAudioDoneEvent + | ResponseAudioTranscriptDeltaEvent + | ResponseAudioTranscriptDoneEvent + | ResponseCodeInterpreterCallCodeDeltaEvent + | ResponseCodeInterpreterCallCodeDoneEvent + | ResponseCodeInterpreterCallCompletedEvent + | ResponseCodeInterpreterCallInProgressEvent + | ResponseCodeInterpreterCallInterpretingEvent + | ResponseCompletedEvent + | ResponseContentPartAddedEvent + | ResponseContentPartDoneEvent + | ResponseCreatedEvent + | ResponseErrorEvent + | ResponseFileSearchCallCompletedEvent + | ResponseFileSearchCallInProgressEvent + | ResponseFileSearchCallSearchingEvent + | ResponseFunctionCallArgumentsDeltaEvent + | ResponseFunctionCallArgumentsDoneEvent + | ResponseInProgressEvent + | ResponseFailedEvent + | ResponseIncompleteEvent + | ResponseOutputItemAddedEvent + | ResponseOutputItemDoneEvent + | ResponseReasoningSummaryPartAddedEvent + | ResponseReasoningSummaryPartDoneEvent + | ResponseReasoningSummaryTextDeltaEvent + | ResponseReasoningSummaryTextDoneEvent + | ResponseReasoningTextDeltaEvent + | ResponseReasoningTextDoneEvent + | ResponseRefusalDeltaEvent + | ResponseRefusalDoneEvent + | ResponseTextDeltaEvent + | ResponseTextDoneEvent + | ResponseWebSearchCallCompletedEvent + | ResponseWebSearchCallInProgressEvent + | ResponseWebSearchCallSearchingEvent + | ResponseImageGenCallCompletedEvent + | ResponseImageGenCallGeneratingEvent + | ResponseImageGenCallInProgressEvent + | ResponseImageGenCallPartialImageEvent + | ResponseMCPCallArgumentsDeltaEvent + | ResponseMCPCallArgumentsDoneEvent + | ResponseMCPCallCompletedEvent + | ResponseMCPCallFailedEvent + | ResponseMCPCallInProgressEvent + | ResponseMCPListToolsCompletedEvent + | ResponseMCPListToolsFailedEvent + | ResponseMCPListToolsInProgressEvent + | ResponseOutputTextAnnotationAddedEvent + | ResponseQueuedEvent + | ResponseCustomToolCallInputDeltaEvent + | ResponseCustomToolCallInputDoneEvent + | ResponseKeepAliveEvent + | ResponseApplyPatchCallOperationDiffDeltaEvent + | ResponseApplyPatchCallOperationDiffDoneEvent +export const ResponseStreamEvent = Schema.Union([ + ResponseAudioDeltaEvent, + ResponseAudioDoneEvent, + ResponseAudioTranscriptDeltaEvent, + ResponseAudioTranscriptDoneEvent, + ResponseCodeInterpreterCallCodeDeltaEvent, + ResponseCodeInterpreterCallCodeDoneEvent, + ResponseCodeInterpreterCallCompletedEvent, + ResponseCodeInterpreterCallInProgressEvent, + ResponseCodeInterpreterCallInterpretingEvent, + ResponseCompletedEvent, + ResponseContentPartAddedEvent, + ResponseContentPartDoneEvent, + ResponseCreatedEvent, + ResponseErrorEvent, + ResponseFileSearchCallCompletedEvent, + ResponseFileSearchCallInProgressEvent, + ResponseFileSearchCallSearchingEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseInProgressEvent, + ResponseFailedEvent, + ResponseIncompleteEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseReasoningSummaryPartAddedEvent, + ResponseReasoningSummaryPartDoneEvent, + ResponseReasoningSummaryTextDeltaEvent, + ResponseReasoningSummaryTextDoneEvent, + ResponseReasoningTextDeltaEvent, + ResponseReasoningTextDoneEvent, + ResponseRefusalDeltaEvent, + ResponseRefusalDoneEvent, + ResponseTextDeltaEvent, + ResponseTextDoneEvent, + ResponseWebSearchCallCompletedEvent, + ResponseWebSearchCallInProgressEvent, + ResponseWebSearchCallSearchingEvent, + ResponseImageGenCallCompletedEvent, + ResponseImageGenCallGeneratingEvent, + ResponseImageGenCallInProgressEvent, + ResponseImageGenCallPartialImageEvent, + ResponseMCPCallArgumentsDeltaEvent, + ResponseMCPCallArgumentsDoneEvent, + ResponseMCPCallCompletedEvent, + ResponseMCPCallFailedEvent, + ResponseMCPCallInProgressEvent, + ResponseMCPListToolsCompletedEvent, + ResponseMCPListToolsFailedEvent, + ResponseMCPListToolsInProgressEvent, + ResponseOutputTextAnnotationAddedEvent, + ResponseQueuedEvent, + ResponseCustomToolCallInputDeltaEvent, + ResponseCustomToolCallInputDoneEvent, + ResponseKeepAliveEvent, + ResponseApplyPatchCallOperationDiffDeltaEvent, + ResponseApplyPatchCallOperationDiffDoneEvent +]) +export type CreateFineTuningJobRequest = { + readonly "model": string | "babbage-002" | "davinci-002" | "gpt-3.5-turbo" | "gpt-4o-mini" + readonly "training_file": string + readonly "hyperparameters"?: { + readonly "batch_size"?: "auto" | number + readonly "learning_rate_multiplier"?: "auto" | number + readonly "n_epochs"?: "auto" | number + } + readonly "suffix"?: string + readonly "validation_file"?: string | null + readonly "integrations"?: ReadonlyArray< + { + readonly "type": "wandb" + readonly "wandb": { + readonly "project": string + readonly "name"?: string | null + readonly "entity"?: string | null + readonly "tags"?: ReadonlyArray + } + } + > + readonly "seed"?: number + readonly "method"?: FineTuneMethod + readonly "metadata"?: Metadata +} +export const CreateFineTuningJobRequest = Schema.Struct({ + "model": Schema.Union([ + Schema.String, + Schema.Literals(["babbage-002", "davinci-002", "gpt-3.5-turbo", "gpt-4o-mini"]) + ]).annotate({ + "description": + "The name of the model to fine-tune. You can select one of the\n[supported models](/docs/guides/fine-tuning#which-models-can-be-fine-tuned).\n" + }), + "training_file": Schema.String.annotate({ + "description": + "The ID of an uploaded file that contains training data.\n\nSee [upload file](/docs/api-reference/files/create) for how to upload a file.\n\nYour dataset must be formatted as a JSONL file. Additionally, you must upload your file with the purpose `fine-tune`.\n\nThe contents of the file should differ depending on if the model uses the [chat](/docs/api-reference/fine-tuning/chat-input), [completions](/docs/api-reference/fine-tuning/completions-input) format, or if the fine-tuning method uses the [preference](/docs/api-reference/fine-tuning/preference-input) format.\n\nSee the [fine-tuning guide](/docs/guides/model-optimization) for more details.\n" + }), + "hyperparameters": Schema.optionalKey( + Schema.Struct({ + "batch_size": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check( + Schema.isLessThanOrEqualTo(256) + ) + ], { mode: "oneOf" }).annotate({ + "description": + "Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n" + }) + ), + "learning_rate_multiplier": Schema.optionalKey( + Schema.Union([Schema.Literal("auto"), Schema.Number.check(Schema.isFinite()).check(Schema.isGreaterThan(0))], { + mode: "oneOf" + }).annotate({ + "description": + "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n" + }) + ), + "n_epochs": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check( + Schema.isLessThanOrEqualTo(50) + ) + ], { mode: "oneOf" }).annotate({ + "description": + "The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n" + }) + ) + }).annotate({ + "description": + "The hyperparameters used for the fine-tuning job.\nThis value is now deprecated in favor of `method`, and should be passed in under the `method` parameter.\n" + }) + ), + "suffix": Schema.optionalKey( + Schema.Union([ + Schema.String.check( + Schema.makeFilterGroup([Schema.isMinLength(1), Schema.isMaxLength(64)], { + "description": + "A string of up to 64 characters that will be added to your fine-tuned model name.\n\nFor example, a `suffix` of \"custom-model-name\" would produce a model name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`.\n" + }) + ) + ]) + ), + "validation_file": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "The ID of an uploaded file that contains validation data.\n\nIf you provide this file, the data is used to generate validation\nmetrics periodically during fine-tuning. These metrics can be viewed in\nthe fine-tuning results file.\nThe same data should not be present in both train and validation files.\n\nYour dataset must be formatted as a JSONL file. You must upload your file with the purpose `fine-tune`.\n\nSee the [fine-tuning guide](/docs/guides/model-optimization) for more details.\n" + }) + ), + "integrations": Schema.optionalKey(Schema.Union([ + Schema.Array(Schema.Struct({ + "type": Schema.Literal("wandb").annotate({ + "description": + "The type of integration to enable. Currently, only \"wandb\" (Weights and Biases) is supported.\n" + }), + "wandb": Schema.Struct({ + "project": Schema.String.annotate({ + "description": "The name of the project that the new run will be created under.\n" + }), + "name": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "A display name to set for the run. If not set, we will use the Job ID as the name.\n" + }) + ), + "entity": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": + "The entity to use for the run. This allows you to set the team or username of the WandB user that you would\nlike associated with the run. If not set, the default entity for the registered WandB API key is used.\n" + }) + ), + "tags": Schema.optionalKey( + Schema.Array(Schema.String).annotate({ + "description": + "A list of tags to be attached to the newly created run. These tags are passed through directly to WandB. Some\ndefault tags are generated by OpenAI: \"openai/finetune\", \"openai/{base-model}\", \"openai/{ftjob-abcdef}\".\n" + }) + ) + }).annotate({ + "description": + "The settings for your integration with Weights and Biases. This payload specifies the project that\nmetrics will be sent to. Optionally, you can set an explicit display name for your run, add tags\nto your run, and set a default entity (team, username, etc) to be associated with your run.\n" + }) + })).annotate({ "description": "A list of integrations to enable for your fine-tuning job." }) + ])), + "seed": Schema.optionalKey( + Schema.Union([ + Schema.Number.check(Schema.isInt()).check( + Schema.makeFilterGroup([ + Schema.isFinite(), + Schema.isGreaterThanOrEqualTo(0), + Schema.isLessThanOrEqualTo(2147483647) + ], { + "description": + "The seed controls the reproducibility of the job. Passing in the same seed and job parameters should produce the same results, but may differ in rare cases.\nIf a seed is not specified, one will be generated for you.\n" + }) + ) + ]) + ), + "method": Schema.optionalKey(FineTuneMethod), + "metadata": Schema.optionalKey(Metadata) +}) +export type FineTuningJob = { + readonly "id": string + readonly "created_at": number + readonly "error": { readonly "code": string; readonly "message": string; readonly "param": string | null } | null + readonly "fine_tuned_model": string | null + readonly "finished_at": number | null + readonly "hyperparameters": { + readonly "batch_size"?: "auto" | number | null + readonly "learning_rate_multiplier"?: "auto" | number + readonly "n_epochs"?: "auto" | number + } + readonly "model": string + readonly "object": "fine_tuning.job" + readonly "organization_id": string + readonly "result_files": ReadonlyArray + readonly "status": "validating_files" | "queued" | "running" | "succeeded" | "failed" | "cancelled" + readonly "trained_tokens": number | null + readonly "training_file": string + readonly "validation_file": string | null + readonly "integrations"?: ReadonlyArray | null + readonly "seed": number + readonly "estimated_finish"?: number | null + readonly "method"?: FineTuneMethod + readonly "metadata"?: Metadata +} +export const FineTuningJob = Schema.Struct({ + "id": Schema.String.annotate({ + "description": "The object identifier, which can be referenced in the API endpoints." + }), + "created_at": Schema.Number.annotate({ + "description": "The Unix timestamp (in seconds) for when the fine-tuning job was created.", + "format": "unixtime" + }).check(Schema.isInt()), + "error": Schema.Union([ + Schema.Struct({ + "code": Schema.String.annotate({ "description": "A machine-readable error code." }), + "message": Schema.String.annotate({ "description": "A human-readable error message." }), + "param": Schema.Union([ + Schema.String.annotate({ + "description": + "The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific." + }), + Schema.Null + ]) + }).annotate({ + "description": + "For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure." + }), + Schema.Null + ]), + "fine_tuned_model": Schema.Union([ + Schema.String.annotate({ + "description": + "The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running." + }), + Schema.Null + ]), + "finished_at": Schema.Union([ + Schema.Number.annotate({ + "description": + "The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]), + "hyperparameters": Schema.Struct({ + "batch_size": Schema.optionalKey( + Schema.Union([ + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check( + Schema.isLessThanOrEqualTo(256) + ) + ], { mode: "oneOf" }).annotate({ + "description": + "Number of examples in each batch. A larger batch size means that model parameters\nare updated less frequently, but with lower variance.\n" + }), + Schema.Null + ]) + ), + "learning_rate_multiplier": Schema.optionalKey( + Schema.Union([Schema.Literal("auto"), Schema.Number.check(Schema.isFinite()).check(Schema.isGreaterThan(0))], { + mode: "oneOf" + }).annotate({ + "description": + "Scaling factor for the learning rate. A smaller learning rate may be useful to avoid\noverfitting.\n" + }) + ), + "n_epochs": Schema.optionalKey( + Schema.Union([ + Schema.Literal("auto"), + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(1)).check( + Schema.isLessThanOrEqualTo(50) + ) + ], { mode: "oneOf" }).annotate({ + "description": + "The number of epochs to train the model for. An epoch refers to one full cycle\nthrough the training dataset.\n" + }) + ) + }).annotate({ + "description": + "The hyperparameters used for the fine-tuning job. This value will only be returned when running `supervised` jobs." + }), + "model": Schema.String.annotate({ "description": "The base model that is being fine-tuned." }), + "object": Schema.Literal("fine_tuning.job").annotate({ + "description": "The object type, which is always \"fine_tuning.job\"." + }), + "organization_id": Schema.String.annotate({ "description": "The organization that owns the fine-tuning job." }), + "result_files": Schema.Array(Schema.String).annotate({ + "description": + "The compiled results file ID(s) for the fine-tuning job. You can retrieve the results with the [Files API](/docs/api-reference/files/retrieve-contents)." + }), + "status": Schema.Literals(["validating_files", "queued", "running", "succeeded", "failed", "cancelled"]).annotate({ + "description": + "The current status of the fine-tuning job, which can be either `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`." + }), + "trained_tokens": Schema.Union([ + Schema.Number.annotate({ + "description": + "The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running." + }).check(Schema.isInt()), + Schema.Null + ]), + "training_file": Schema.String.annotate({ + "description": + "The file ID used for training. You can retrieve the training data with the [Files API](/docs/api-reference/files/retrieve-contents)." + }), + "validation_file": Schema.Union([ + Schema.String.annotate({ + "description": + "The file ID used for validation. You can retrieve the validation results with the [Files API](/docs/api-reference/files/retrieve-contents)." + }), + Schema.Null + ]), + "integrations": Schema.optionalKey( + Schema.Union([ + Schema.Array(Schema.Union([FineTuningIntegration], { mode: "oneOf" })).annotate({ + "description": "A list of integrations to enable for this fine-tuning job." + }).check(Schema.isMaxLength(5)), + Schema.Null + ]) + ), + "seed": Schema.Number.annotate({ "description": "The seed used for the fine-tuning job." }).check(Schema.isInt()), + "estimated_finish": Schema.optionalKey( + Schema.Union([ + Schema.Number.annotate({ + "description": + "The Unix timestamp (in seconds) for when the fine-tuning job is estimated to finish. The value will be null if the fine-tuning job is not running.", + "format": "unixtime" + }).check(Schema.isInt()), + Schema.Null + ]) + ), + "method": Schema.optionalKey(FineTuneMethod), + "metadata": Schema.optionalKey(Metadata) +}).annotate({ + "title": "FineTuningJob", + "description": "The `fine_tuning.job` object represents a fine-tuning job that has been created through the API.\n" +}) +export type ListPaginatedFineTuningJobsResponse = { + readonly "data": ReadonlyArray + readonly "has_more": boolean + readonly "object": "list" +} +export const ListPaginatedFineTuningJobsResponse = Schema.Struct({ + "data": Schema.Array(FineTuningJob), + "has_more": Schema.Boolean, + "object": Schema.Literal("list") +}) +// schemas +export type ListAssistantsParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "before"?: string +} +export const ListAssistantsParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "before": Schema.optionalKey(Schema.String) +}) +export type ListAssistants200 = ListAssistantsResponse +export const ListAssistants200 = ListAssistantsResponse +export type CreateAssistantRequestJson = CreateAssistantRequest +export const CreateAssistantRequestJson = CreateAssistantRequest +export type CreateAssistant200 = AssistantObject +export const CreateAssistant200 = AssistantObject +export type GetAssistant200 = AssistantObject +export const GetAssistant200 = AssistantObject +export type ModifyAssistantRequestJson = ModifyAssistantRequest +export const ModifyAssistantRequestJson = ModifyAssistantRequest +export type ModifyAssistant200 = AssistantObject +export const ModifyAssistant200 = AssistantObject +export type DeleteAssistant200 = DeleteAssistantResponse +export const DeleteAssistant200 = DeleteAssistantResponse +export type CreateSpeechRequestJson = CreateSpeechRequest +export const CreateSpeechRequestJson = CreateSpeechRequest +export type CreateSpeech200Sse = CreateSpeechResponseStreamEvent +export const CreateSpeech200Sse = CreateSpeechResponseStreamEvent +export type CreateTranscriptionRequestFormData = CreateTranscriptionRequest +export const CreateTranscriptionRequestFormData = CreateTranscriptionRequest +export type CreateTranscription200 = + | CreateTranscriptionResponseJson + | CreateTranscriptionResponseDiarizedJson + | CreateTranscriptionResponseVerboseJson +export const CreateTranscription200 = Schema.Union([ + CreateTranscriptionResponseJson, + CreateTranscriptionResponseDiarizedJson, + CreateTranscriptionResponseVerboseJson +], { mode: "oneOf" }) +export type CreateTranscription200Sse = CreateTranscriptionResponseStreamEvent +export const CreateTranscription200Sse = CreateTranscriptionResponseStreamEvent +export type CreateTranslationRequestFormData = CreateTranslationRequest +export const CreateTranslationRequestFormData = CreateTranslationRequest +export type CreateTranslation200 = CreateTranslationResponseJson | CreateTranslationResponseVerboseJson +export const CreateTranslation200 = Schema.Union( + [CreateTranslationResponseJson, CreateTranslationResponseVerboseJson], + { mode: "oneOf" } +) +export type ListVoiceConsentsParams = { readonly "after"?: string; readonly "limit"?: number } +export const ListVoiceConsentsParams = Schema.Struct({ + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())) +}) +export type ListVoiceConsents200 = VoiceConsentListResource +export const ListVoiceConsents200 = VoiceConsentListResource +export type CreateVoiceConsentRequestFormData = CreateVoiceConsentRequest +export const CreateVoiceConsentRequestFormData = CreateVoiceConsentRequest +export type CreateVoiceConsent200 = VoiceConsentResource +export const CreateVoiceConsent200 = VoiceConsentResource +export type GetVoiceConsent200 = VoiceConsentResource +export const GetVoiceConsent200 = VoiceConsentResource +export type UpdateVoiceConsentRequestJson = UpdateVoiceConsentRequest +export const UpdateVoiceConsentRequestJson = UpdateVoiceConsentRequest +export type UpdateVoiceConsent200 = VoiceConsentResource +export const UpdateVoiceConsent200 = VoiceConsentResource +export type DeleteVoiceConsent200 = VoiceConsentDeletedResource +export const DeleteVoiceConsent200 = VoiceConsentDeletedResource +export type CreateVoiceRequestFormData = CreateVoiceRequest +export const CreateVoiceRequestFormData = CreateVoiceRequest +export type CreateVoice200 = VoiceResource +export const CreateVoice200 = VoiceResource +export type ListBatchesParams = { readonly "after"?: string; readonly "limit"?: number } +export const ListBatchesParams = Schema.Struct({ + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())) +}) +export type ListBatches200 = ListBatchesResponse +export const ListBatches200 = ListBatchesResponse +export type CreateBatchRequestJson = { + readonly "input_file_id": string + readonly "endpoint": + | "/v1/responses" + | "/v1/chat/completions" + | "/v1/embeddings" + | "/v1/completions" + | "/v1/moderations" + | "/v1/images/generations" + | "/v1/images/edits" + | "/v1/videos" + readonly "completion_window": "24h" + readonly "metadata"?: Metadata + readonly "output_expires_after"?: BatchFileExpirationAfter +} +export const CreateBatchRequestJson = Schema.Struct({ + "input_file_id": Schema.String.annotate({ + "description": + "The ID of an uploaded file that contains requests for the new batch.\n\nSee [upload file](/docs/api-reference/files/create) for how to upload a file.\n\nYour input file must be formatted as a [JSONL file](/docs/api-reference/batch/request-input), and must be uploaded with the purpose `batch`. The file can contain up to 50,000 requests, and can be up to 200 MB in size.\n" + }), + "endpoint": Schema.Literals([ + "/v1/responses", + "/v1/chat/completions", + "/v1/embeddings", + "/v1/completions", + "/v1/moderations", + "/v1/images/generations", + "/v1/images/edits", + "/v1/videos" + ]).annotate({ + "description": + "The endpoint to be used for all requests in the batch. Currently `/v1/responses`, `/v1/chat/completions`, `/v1/embeddings`, `/v1/completions`, `/v1/moderations`, `/v1/images/generations`, `/v1/images/edits`, and `/v1/videos` are supported. Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 embedding inputs across all requests in the batch." + }), + "completion_window": Schema.Literal("24h").annotate({ + "description": "The time frame within which the batch should be processed. Currently only `24h` is supported." + }), + "metadata": Schema.optionalKey(Metadata), + "output_expires_after": Schema.optionalKey(BatchFileExpirationAfter) +}) +export type CreateBatch200 = Batch +export const CreateBatch200 = Batch +export type RetrieveBatch200 = Batch +export const RetrieveBatch200 = Batch +export type CancelBatch200 = Batch +export const CancelBatch200 = Batch +export type ListChatCompletionsParams = { + readonly "model"?: string + readonly "metadata"?: Metadata + readonly "after"?: string + readonly "limit"?: number + readonly "order"?: "asc" | "desc" +} +export const ListChatCompletionsParams = Schema.Struct({ + "model": Schema.optionalKey(Schema.String), + "metadata": Schema.optionalKey(Metadata), + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListChatCompletions200 = ChatCompletionList +export const ListChatCompletions200 = ChatCompletionList +export type CreateChatCompletionRequestJson = CreateChatCompletionRequest +export const CreateChatCompletionRequestJson = CreateChatCompletionRequest +export type CreateChatCompletion200 = CreateChatCompletionResponse +export const CreateChatCompletion200 = CreateChatCompletionResponse +export type CreateChatCompletion200Sse = CreateChatCompletionStreamResponse +export const CreateChatCompletion200Sse = CreateChatCompletionStreamResponse +export type GetChatCompletion200 = CreateChatCompletionResponse +export const GetChatCompletion200 = CreateChatCompletionResponse +export type UpdateChatCompletionRequestJson = { readonly "metadata": Metadata } +export const UpdateChatCompletionRequestJson = Schema.Struct({ "metadata": Metadata }) +export type UpdateChatCompletion200 = CreateChatCompletionResponse +export const UpdateChatCompletion200 = CreateChatCompletionResponse +export type DeleteChatCompletion200 = ChatCompletionDeleted +export const DeleteChatCompletion200 = ChatCompletionDeleted +export type GetChatCompletionMessagesParams = { + readonly "after"?: string + readonly "limit"?: number + readonly "order"?: "asc" | "desc" +} +export const GetChatCompletionMessagesParams = Schema.Struct({ + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type GetChatCompletionMessages200 = ChatCompletionMessageList +export const GetChatCompletionMessages200 = ChatCompletionMessageList +export type CreateCompletionRequestJson = CreateCompletionRequest +export const CreateCompletionRequestJson = CreateCompletionRequest +export type CreateCompletion200 = CreateCompletionResponse +export const CreateCompletion200 = CreateCompletionResponse +export type ListContainersParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "name"?: string +} +export const ListContainersParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "name": Schema.optionalKey(Schema.String) +}) +export type ListContainers200 = ContainerListResource +export const ListContainers200 = ContainerListResource +export type CreateContainerRequestJson = CreateContainerBody +export const CreateContainerRequestJson = CreateContainerBody +export type CreateContainer200 = ContainerResource +export const CreateContainer200 = ContainerResource +export type RetrieveContainer200 = ContainerResource +export const RetrieveContainer200 = ContainerResource +export type ListContainerFilesParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string +} +export const ListContainerFilesParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String) +}) +export type ListContainerFiles200 = ContainerFileListResource +export const ListContainerFiles200 = ContainerFileListResource +export type CreateContainerFileRequestJson = CreateContainerFileBody +export const CreateContainerFileRequestJson = CreateContainerFileBody +export type CreateContainerFileRequestFormData = CreateContainerFileBody +export const CreateContainerFileRequestFormData = CreateContainerFileBody +export type CreateContainerFile200 = ContainerFileResource +export const CreateContainerFile200 = ContainerFileResource +export type RetrieveContainerFile200 = ContainerFileResource +export const RetrieveContainerFile200 = ContainerFileResource +export type ListConversationItemsParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "include"?: ReadonlyArray +} +export const ListConversationItemsParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "include": Schema.optionalKey(Schema.Array(IncludeEnum)) +}) +export type ListConversationItems200 = ConversationItemList +export const ListConversationItems200 = ConversationItemList +export type CreateConversationItemsParams = { readonly "include"?: ReadonlyArray } +export const CreateConversationItemsParams = Schema.Struct({ "include": Schema.optionalKey(Schema.Array(IncludeEnum)) }) +export type CreateConversationItemsRequestJson = { + readonly "items": ReadonlyArray + readonly [x: string]: unknown +} +export const CreateConversationItemsRequestJson = Schema.StructWithRest( + Schema.Struct({ + "items": Schema.Array(InputItem).annotate({ + "description": "The items to add to the conversation. You may add up to 20 items at a time.\n" + }).check(Schema.isMaxLength(20)) + }), + [Schema.Record(Schema.String, Schema.Unknown)] +) +export type CreateConversationItems200 = ConversationItemList +export const CreateConversationItems200 = ConversationItemList +export type GetConversationItemParams = { readonly "include"?: ReadonlyArray } +export const GetConversationItemParams = Schema.Struct({ "include": Schema.optionalKey(Schema.Array(IncludeEnum)) }) +export type GetConversationItem200 = ConversationItem +export const GetConversationItem200 = ConversationItem +export type DeleteConversationItem200 = ConversationResource +export const DeleteConversationItem200 = ConversationResource +export type CreateEmbeddingRequestJson = CreateEmbeddingRequest +export const CreateEmbeddingRequestJson = CreateEmbeddingRequest +export type CreateEmbedding200 = CreateEmbeddingResponse +export const CreateEmbedding200 = CreateEmbeddingResponse +export type ListEvalsParams = { + readonly "after"?: string + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "order_by"?: "created_at" | "updated_at" +} +export const ListEvalsParams = Schema.Struct({ + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "order_by": Schema.optionalKey(Schema.Literals(["created_at", "updated_at"])) +}) +export type ListEvals200 = EvalList +export const ListEvals200 = EvalList +export type CreateEvalRequestJson = CreateEvalRequest +export const CreateEvalRequestJson = CreateEvalRequest +export type CreateEval201 = Eval +export const CreateEval201 = Eval +export type GetEval200 = Eval +export const GetEval200 = Eval +export type UpdateEvalRequestJson = { readonly "name"?: string; readonly "metadata"?: Metadata } +export const UpdateEvalRequestJson = Schema.Struct({ + "name": Schema.optionalKey(Schema.String.annotate({ "description": "Rename the evaluation." })), + "metadata": Schema.optionalKey(Metadata) +}) +export type UpdateEval200 = Eval +export const UpdateEval200 = Eval +export type DeleteEval200 = { readonly "object": string; readonly "deleted": boolean; readonly "eval_id": string } +export const DeleteEval200 = Schema.Struct({ + "object": Schema.String, + "deleted": Schema.Boolean, + "eval_id": Schema.String +}) +export type DeleteEval404 = Error +export const DeleteEval404 = Error +export type GetEvalRunsParams = { + readonly "after"?: string + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "status"?: "queued" | "in_progress" | "completed" | "canceled" | "failed" +} +export const GetEvalRunsParams = Schema.Struct({ + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "status": Schema.optionalKey(Schema.Literals(["queued", "in_progress", "completed", "canceled", "failed"])) +}) +export type GetEvalRuns200 = EvalRunList +export const GetEvalRuns200 = EvalRunList +export type CreateEvalRunRequestJson = CreateEvalRunRequest +export const CreateEvalRunRequestJson = CreateEvalRunRequest +export type CreateEvalRun201 = EvalRun +export const CreateEvalRun201 = EvalRun +export type CreateEvalRun400 = Error +export const CreateEvalRun400 = Error +export type GetEvalRun200 = EvalRun +export const GetEvalRun200 = EvalRun +export type CancelEvalRun200 = EvalRun +export const CancelEvalRun200 = EvalRun +export type DeleteEvalRun200 = { readonly "object"?: string; readonly "deleted"?: boolean; readonly "run_id"?: string } +export const DeleteEvalRun200 = Schema.Struct({ + "object": Schema.optionalKey(Schema.String), + "deleted": Schema.optionalKey(Schema.Boolean), + "run_id": Schema.optionalKey(Schema.String) +}) +export type DeleteEvalRun404 = Error +export const DeleteEvalRun404 = Error +export type GetEvalRunOutputItemsParams = { + readonly "after"?: string + readonly "limit"?: number + readonly "status"?: "fail" | "pass" + readonly "order"?: "asc" | "desc" +} +export const GetEvalRunOutputItemsParams = Schema.Struct({ + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "status": Schema.optionalKey(Schema.Literals(["fail", "pass"])), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type GetEvalRunOutputItems200 = EvalRunOutputItemList +export const GetEvalRunOutputItems200 = EvalRunOutputItemList +export type GetEvalRunOutputItem200 = EvalRunOutputItem +export const GetEvalRunOutputItem200 = EvalRunOutputItem +export type ListFilesParams = { + readonly "purpose"?: string + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string +} +export const ListFilesParams = Schema.Struct({ + "purpose": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String) +}) +export type ListFiles200 = ListFilesResponse +export const ListFiles200 = ListFilesResponse +export type CreateFileRequestFormData = CreateFileRequest +export const CreateFileRequestFormData = CreateFileRequest +export type CreateFile200 = OpenAIFile +export const CreateFile200 = OpenAIFile +export type RetrieveFile200 = OpenAIFile +export const RetrieveFile200 = OpenAIFile +export type DeleteFile200 = DeleteFileResponse +export const DeleteFile200 = DeleteFileResponse +export type DownloadFile200 = string +export const DownloadFile200 = Schema.String +export type RunGraderRequestJson = RunGraderRequest +export const RunGraderRequestJson = RunGraderRequest +export type RunGrader200 = RunGraderResponse +export const RunGrader200 = RunGraderResponse +export type ValidateGraderRequestJson = ValidateGraderRequest +export const ValidateGraderRequestJson = ValidateGraderRequest +export type ValidateGrader200 = ValidateGraderResponse +export const ValidateGrader200 = ValidateGraderResponse +export type ListFineTuningCheckpointPermissionsParams = { + readonly "project_id"?: string + readonly "after"?: string + readonly "limit"?: number + readonly "order"?: "ascending" | "descending" +} +export const ListFineTuningCheckpointPermissionsParams = Schema.Struct({ + "project_id": Schema.optionalKey(Schema.String), + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["ascending", "descending"])) +}) +export type ListFineTuningCheckpointPermissions200 = ListFineTuningCheckpointPermissionResponse +export const ListFineTuningCheckpointPermissions200 = ListFineTuningCheckpointPermissionResponse +export type CreateFineTuningCheckpointPermissionRequestJson = CreateFineTuningCheckpointPermissionRequest +export const CreateFineTuningCheckpointPermissionRequestJson = CreateFineTuningCheckpointPermissionRequest +export type CreateFineTuningCheckpointPermission200 = ListFineTuningCheckpointPermissionResponse +export const CreateFineTuningCheckpointPermission200 = ListFineTuningCheckpointPermissionResponse +export type DeleteFineTuningCheckpointPermission200 = DeleteFineTuningCheckpointPermissionResponse +export const DeleteFineTuningCheckpointPermission200 = DeleteFineTuningCheckpointPermissionResponse +export type ListPaginatedFineTuningJobsParams = { + readonly "after"?: string + readonly "limit"?: number + readonly "metadata"?: {} +} +export const ListPaginatedFineTuningJobsParams = Schema.Struct({ + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "metadata": Schema.optionalKey(Schema.Union([Schema.Struct({})])) +}) +export type ListPaginatedFineTuningJobs200 = ListPaginatedFineTuningJobsResponse +export const ListPaginatedFineTuningJobs200 = ListPaginatedFineTuningJobsResponse +export type CreateFineTuningJobRequestJson = CreateFineTuningJobRequest +export const CreateFineTuningJobRequestJson = CreateFineTuningJobRequest +export type CreateFineTuningJob200 = FineTuningJob +export const CreateFineTuningJob200 = FineTuningJob +export type RetrieveFineTuningJob200 = FineTuningJob +export const RetrieveFineTuningJob200 = FineTuningJob +export type CancelFineTuningJob200 = FineTuningJob +export const CancelFineTuningJob200 = FineTuningJob +export type ListFineTuningJobCheckpointsParams = { readonly "after"?: string; readonly "limit"?: number } +export const ListFineTuningJobCheckpointsParams = Schema.Struct({ + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())) +}) +export type ListFineTuningJobCheckpoints200 = ListFineTuningJobCheckpointsResponse +export const ListFineTuningJobCheckpoints200 = ListFineTuningJobCheckpointsResponse +export type ListFineTuningEventsParams = { readonly "after"?: string; readonly "limit"?: number } +export const ListFineTuningEventsParams = Schema.Struct({ + "after": Schema.optionalKey(Schema.String), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())) +}) +export type ListFineTuningEvents200 = ListFineTuningJobEventsResponse +export const ListFineTuningEvents200 = ListFineTuningJobEventsResponse +export type PauseFineTuningJob200 = FineTuningJob +export const PauseFineTuningJob200 = FineTuningJob +export type ResumeFineTuningJob200 = FineTuningJob +export const ResumeFineTuningJob200 = FineTuningJob +export type CreateImageEditRequestJson = EditImageBodyJsonParam +export const CreateImageEditRequestJson = EditImageBodyJsonParam +export type CreateImageEditRequestFormData = CreateImageEditRequest +export const CreateImageEditRequestFormData = CreateImageEditRequest +export type CreateImageEdit200 = ImagesResponse +export const CreateImageEdit200 = ImagesResponse +export type CreateImageEdit200Sse = ImageEditStreamEvent +export const CreateImageEdit200Sse = ImageEditStreamEvent +export type CreateImageRequestJson = CreateImageRequest +export const CreateImageRequestJson = CreateImageRequest +export type CreateImage200 = ImagesResponse +export const CreateImage200 = ImagesResponse +export type CreateImage200Sse = ImageGenStreamEvent +export const CreateImage200Sse = ImageGenStreamEvent +export type CreateImageVariationRequestFormData = CreateImageVariationRequest +export const CreateImageVariationRequestFormData = CreateImageVariationRequest +export type CreateImageVariation200 = ImagesResponse +export const CreateImageVariation200 = ImagesResponse +export type ListModels200 = ListModelsResponse +export const ListModels200 = ListModelsResponse +export type RetrieveModel200 = Model +export const RetrieveModel200 = Model +export type DeleteModel200 = DeleteModelResponse +export const DeleteModel200 = DeleteModelResponse +export type CreateModerationRequestJson = CreateModerationRequest +export const CreateModerationRequestJson = CreateModerationRequest +export type CreateModeration200 = CreateModerationResponse +export const CreateModeration200 = CreateModerationResponse +export type AdminApiKeysListParams = { + readonly "after"?: string | null + readonly "order"?: "asc" | "desc" + readonly "limit"?: number +} +export const AdminApiKeysListParams = Schema.Struct({ + "after": Schema.optionalKey( + Schema.Union([Schema.String, Schema.Null]).annotate({ + "description": "Return keys with IDs that come after this ID in the pagination order." + }) + ), + "order": Schema.optionalKey( + Schema.Literals(["asc", "desc"]).annotate({ + "description": "Order results by creation time, ascending or descending." + }) + ), + "limit": Schema.optionalKey( + Schema.Number.annotate({ "description": "Maximum number of keys to return." }).check(Schema.isInt()) + ) +}) +export type AdminApiKeysList200 = ApiKeyList +export const AdminApiKeysList200 = ApiKeyList +export type AdminApiKeysCreateRequestJson = { readonly "name": string } +export const AdminApiKeysCreateRequestJson = Schema.Struct({ "name": Schema.String }) +export type AdminApiKeysCreate200 = AdminApiKeyCreateResponse +export const AdminApiKeysCreate200 = AdminApiKeyCreateResponse +export type AdminApiKeysGet200 = AdminApiKey +export const AdminApiKeysGet200 = AdminApiKey +export type AdminApiKeysDelete200 = { + readonly "id": string + readonly "object": "organization.admin_api_key.deleted" + readonly "deleted": boolean +} +export const AdminApiKeysDelete200 = Schema.Struct({ + "id": Schema.String, + "object": Schema.Literal("organization.admin_api_key.deleted"), + "deleted": Schema.Boolean +}) +export type ListAuditLogsParams = { + readonly "effective_at[gt]"?: number + readonly "effective_at[gte]"?: number + readonly "effective_at[lt]"?: number + readonly "effective_at[lte]"?: number + readonly "project_ids[]"?: ReadonlyArray + readonly "event_types[]"?: ReadonlyArray + readonly "actor_ids[]"?: ReadonlyArray + readonly "actor_emails[]"?: ReadonlyArray + readonly "resource_ids[]"?: ReadonlyArray + readonly "limit"?: number + readonly "after"?: string + readonly "before"?: string +} +export const ListAuditLogsParams = Schema.Struct({ + "effective_at[gt]": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Return only events whose `effective_at` (Unix seconds) is greater than this value." + }).check(Schema.isInt()) + ), + "effective_at[gte]": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Return only events whose `effective_at` (Unix seconds) is greater than or equal to this value." + }).check(Schema.isInt()) + ), + "effective_at[lt]": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Return only events whose `effective_at` (Unix seconds) is less than this value." + }).check(Schema.isInt()) + ), + "effective_at[lte]": Schema.optionalKey( + Schema.Number.annotate({ + "description": "Return only events whose `effective_at` (Unix seconds) is less than or equal to this value." + }).check(Schema.isInt()) + ), + "project_ids[]": Schema.optionalKey(Schema.Array(Schema.String)), + "event_types[]": Schema.optionalKey(Schema.Array(AuditLogEventType)), + "actor_ids[]": Schema.optionalKey(Schema.Array(Schema.String)), + "actor_emails[]": Schema.optionalKey(Schema.Array(Schema.String)), + "resource_ids[]": Schema.optionalKey(Schema.Array(Schema.String)), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String), + "before": Schema.optionalKey(Schema.String) +}) +export type ListAuditLogs200 = ListAuditLogsResponse +export const ListAuditLogs200 = ListAuditLogsResponse +export type ListOrganizationCertificatesParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListOrganizationCertificatesParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListOrganizationCertificates200 = ListCertificatesResponse +export const ListOrganizationCertificates200 = ListCertificatesResponse +export type UploadCertificateRequestJson = UploadCertificateRequest +export const UploadCertificateRequestJson = UploadCertificateRequest +export type UploadCertificate200 = Certificate +export const UploadCertificate200 = Certificate +export type ActivateOrganizationCertificatesRequestJson = ToggleCertificatesRequest +export const ActivateOrganizationCertificatesRequestJson = ToggleCertificatesRequest +export type ActivateOrganizationCertificates200 = OrganizationCertificateActivationResponse +export const ActivateOrganizationCertificates200 = OrganizationCertificateActivationResponse +export type DeactivateOrganizationCertificatesRequestJson = ToggleCertificatesRequest +export const DeactivateOrganizationCertificatesRequestJson = ToggleCertificatesRequest +export type DeactivateOrganizationCertificates200 = OrganizationCertificateDeactivationResponse +export const DeactivateOrganizationCertificates200 = OrganizationCertificateDeactivationResponse +export type GetCertificateParams = { readonly "include"?: ReadonlyArray<"content"> } +export const GetCertificateParams = Schema.Struct({ + "include": Schema.optionalKey(Schema.Array(Schema.Literal("content"))) +}) +export type GetCertificate200 = Certificate +export const GetCertificate200 = Certificate +export type ModifyCertificateRequestJson = ModifyCertificateRequest +export const ModifyCertificateRequestJson = ModifyCertificateRequest +export type ModifyCertificate200 = Certificate +export const ModifyCertificate200 = Certificate +export type DeleteCertificate200 = DeleteCertificateResponse +export const DeleteCertificate200 = DeleteCertificateResponse +export type UsageCostsParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1d" + readonly "project_ids"?: ReadonlyArray + readonly "api_key_ids"?: ReadonlyArray + readonly "group_by"?: ReadonlyArray<"project_id" | "line_item" | "api_key_id"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageCostsParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literal("1d")), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "api_key_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "group_by": Schema.optionalKey(Schema.Array(Schema.Literals(["project_id", "line_item", "api_key_id"]))), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageCosts200 = UsageResponse +export const UsageCosts200 = UsageResponse +export type ListGroupsParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListGroupsParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListGroups200 = GroupListResource +export const ListGroups200 = GroupListResource +export type CreateGroupRequestJson = CreateGroupBody +export const CreateGroupRequestJson = CreateGroupBody +export type CreateGroup200 = GroupResponse +export const CreateGroup200 = GroupResponse +export type UpdateGroupRequestJson = UpdateGroupBody +export const UpdateGroupRequestJson = UpdateGroupBody +export type UpdateGroup200 = GroupResourceWithSuccess +export const UpdateGroup200 = GroupResourceWithSuccess +export type DeleteGroup200 = GroupDeletedResource +export const DeleteGroup200 = GroupDeletedResource +export type ListGroupRoleAssignmentsParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListGroupRoleAssignmentsParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListGroupRoleAssignments200 = RoleListResource +export const ListGroupRoleAssignments200 = RoleListResource +export type AssignGroupRoleRequestJson = PublicAssignOrganizationGroupRoleBody +export const AssignGroupRoleRequestJson = PublicAssignOrganizationGroupRoleBody +export type AssignGroupRole200 = GroupRoleAssignment +export const AssignGroupRole200 = GroupRoleAssignment +export type UnassignGroupRole200 = DeletedRoleAssignmentResource +export const UnassignGroupRole200 = DeletedRoleAssignmentResource +export type ListGroupUsersParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListGroupUsersParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListGroupUsers200 = UserListResource +export const ListGroupUsers200 = UserListResource +export type AddGroupUserRequestJson = CreateGroupUserBody +export const AddGroupUserRequestJson = CreateGroupUserBody +export type AddGroupUser200 = GroupUserAssignment +export const AddGroupUser200 = GroupUserAssignment +export type RemoveGroupUser200 = GroupUserDeletedResource +export const RemoveGroupUser200 = GroupUserDeletedResource +export type ListInvitesParams = { readonly "limit"?: number; readonly "after"?: string } +export const ListInvitesParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String) +}) +export type ListInvites200 = InviteListResponse +export const ListInvites200 = InviteListResponse +export type InviteUserRequestJson = InviteRequest +export const InviteUserRequestJson = InviteRequest +export type InviteUser200 = Invite +export const InviteUser200 = Invite +export type RetrieveInvite200 = Invite +export const RetrieveInvite200 = Invite +export type DeleteInvite200 = InviteDeleteResponse +export const DeleteInvite200 = InviteDeleteResponse +export type ListProjectsParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "include_archived"?: boolean +} +export const ListProjectsParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String), + "include_archived": Schema.optionalKey(Schema.Boolean) +}) +export type ListProjects200 = ProjectListResponse +export const ListProjects200 = ProjectListResponse +export type CreateProjectRequestJson = ProjectCreateRequest +export const CreateProjectRequestJson = ProjectCreateRequest +export type CreateProject200 = Project +export const CreateProject200 = Project +export type RetrieveProject200 = Project +export const RetrieveProject200 = Project +export type ModifyProjectRequestJson = ProjectUpdateRequest +export const ModifyProjectRequestJson = ProjectUpdateRequest +export type ModifyProject200 = Project +export const ModifyProject200 = Project +export type ModifyProject400 = ErrorResponse +export const ModifyProject400 = ErrorResponse +export type ListProjectApiKeysParams = { readonly "limit"?: number; readonly "after"?: string } +export const ListProjectApiKeysParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String) +}) +export type ListProjectApiKeys200 = ProjectApiKeyListResponse +export const ListProjectApiKeys200 = ProjectApiKeyListResponse +export type RetrieveProjectApiKey200 = ProjectApiKey +export const RetrieveProjectApiKey200 = ProjectApiKey +export type DeleteProjectApiKey200 = ProjectApiKeyDeleteResponse +export const DeleteProjectApiKey200 = ProjectApiKeyDeleteResponse +export type DeleteProjectApiKey400 = ErrorResponse +export const DeleteProjectApiKey400 = ErrorResponse +export type ArchiveProject200 = Project +export const ArchiveProject200 = Project +export type ListProjectCertificatesParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListProjectCertificatesParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListProjectCertificates200 = ListProjectCertificatesResponse +export const ListProjectCertificates200 = ListProjectCertificatesResponse +export type ActivateProjectCertificatesRequestJson = ToggleCertificatesRequest +export const ActivateProjectCertificatesRequestJson = ToggleCertificatesRequest +export type ActivateProjectCertificates200 = OrganizationProjectCertificateActivationResponse +export const ActivateProjectCertificates200 = OrganizationProjectCertificateActivationResponse +export type DeactivateProjectCertificatesRequestJson = ToggleCertificatesRequest +export const DeactivateProjectCertificatesRequestJson = ToggleCertificatesRequest +export type DeactivateProjectCertificates200 = OrganizationProjectCertificateDeactivationResponse +export const DeactivateProjectCertificates200 = OrganizationProjectCertificateDeactivationResponse +export type ListProjectGroupsParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListProjectGroupsParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(100)) + ), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListProjectGroups200 = ProjectGroupListResource +export const ListProjectGroups200 = ProjectGroupListResource +export type AddProjectGroupRequestJson = InviteProjectGroupBody +export const AddProjectGroupRequestJson = InviteProjectGroupBody +export type AddProjectGroup200 = ProjectGroup +export const AddProjectGroup200 = ProjectGroup +export type RemoveProjectGroup200 = ProjectGroupDeletedResource +export const RemoveProjectGroup200 = ProjectGroupDeletedResource +export type RetrieveProjectHostedToolPermissions200 = ProjectHostedToolPermissions +export const RetrieveProjectHostedToolPermissions200 = ProjectHostedToolPermissions +export type UpdateProjectHostedToolPermissionsRequestJson = ProjectHostedToolPermissionsUpdateRequest +export const UpdateProjectHostedToolPermissionsRequestJson = ProjectHostedToolPermissionsUpdateRequest +export type UpdateProjectHostedToolPermissions200 = ProjectHostedToolPermissions +export const UpdateProjectHostedToolPermissions200 = ProjectHostedToolPermissions +export type RetrieveProjectModelPermissions200 = ProjectModelPermissions +export const RetrieveProjectModelPermissions200 = ProjectModelPermissions +export type UpdateProjectModelPermissionsRequestJson = ProjectModelPermissionsUpdateRequest +export const UpdateProjectModelPermissionsRequestJson = ProjectModelPermissionsUpdateRequest +export type UpdateProjectModelPermissions200 = ProjectModelPermissions +export const UpdateProjectModelPermissions200 = ProjectModelPermissions +export type DeleteProjectModelPermissions200 = ProjectModelPermissionsDeleteResponse +export const DeleteProjectModelPermissions200 = ProjectModelPermissionsDeleteResponse +export type ListProjectRateLimitsParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "before"?: string +} +export const ListProjectRateLimitsParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String), + "before": Schema.optionalKey(Schema.String) +}) +export type ListProjectRateLimits200 = ProjectRateLimitListResponse +export const ListProjectRateLimits200 = ProjectRateLimitListResponse +export type UpdateProjectRateLimitsRequestJson = ProjectRateLimitUpdateRequest +export const UpdateProjectRateLimitsRequestJson = ProjectRateLimitUpdateRequest +export type UpdateProjectRateLimits200 = ProjectRateLimit +export const UpdateProjectRateLimits200 = ProjectRateLimit +export type UpdateProjectRateLimits400 = ErrorResponse +export const UpdateProjectRateLimits400 = ErrorResponse +export type ListProjectServiceAccountsParams = { readonly "limit"?: number; readonly "after"?: string } +export const ListProjectServiceAccountsParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String) +}) +export type ListProjectServiceAccounts200 = ProjectServiceAccountListResponse +export const ListProjectServiceAccounts200 = ProjectServiceAccountListResponse +export type ListProjectServiceAccounts400 = ErrorResponse +export const ListProjectServiceAccounts400 = ErrorResponse +export type CreateProjectServiceAccountRequestJson = ProjectServiceAccountCreateRequest +export const CreateProjectServiceAccountRequestJson = ProjectServiceAccountCreateRequest +export type CreateProjectServiceAccount200 = ProjectServiceAccountCreateResponse +export const CreateProjectServiceAccount200 = ProjectServiceAccountCreateResponse +export type CreateProjectServiceAccount400 = ErrorResponse +export const CreateProjectServiceAccount400 = ErrorResponse +export type RetrieveProjectServiceAccount200 = ProjectServiceAccount +export const RetrieveProjectServiceAccount200 = ProjectServiceAccount +export type DeleteProjectServiceAccount200 = ProjectServiceAccountDeleteResponse +export const DeleteProjectServiceAccount200 = ProjectServiceAccountDeleteResponse +export type ListProjectUsersParams = { readonly "limit"?: number; readonly "after"?: string } +export const ListProjectUsersParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String) +}) +export type ListProjectUsers200 = ProjectUserListResponse +export const ListProjectUsers200 = ProjectUserListResponse +export type ListProjectUsers400 = ErrorResponse +export const ListProjectUsers400 = ErrorResponse +export type CreateProjectUserRequestJson = ProjectUserCreateRequest +export const CreateProjectUserRequestJson = ProjectUserCreateRequest +export type CreateProjectUser200 = ProjectUser +export const CreateProjectUser200 = ProjectUser +export type CreateProjectUser400 = ErrorResponse +export const CreateProjectUser400 = ErrorResponse +export type RetrieveProjectUser200 = ProjectUser +export const RetrieveProjectUser200 = ProjectUser +export type ModifyProjectUserRequestJson = ProjectUserUpdateRequest +export const ModifyProjectUserRequestJson = ProjectUserUpdateRequest +export type ModifyProjectUser200 = ProjectUser +export const ModifyProjectUser200 = ProjectUser +export type ModifyProjectUser400 = ErrorResponse +export const ModifyProjectUser400 = ErrorResponse +export type DeleteProjectUser200 = ProjectUserDeleteResponse +export const DeleteProjectUser200 = ProjectUserDeleteResponse +export type DeleteProjectUser400 = ErrorResponse +export const DeleteProjectUser400 = ErrorResponse +export type ListRolesParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListRolesParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListRoles200 = PublicRoleListResource +export const ListRoles200 = PublicRoleListResource +export type CreateRoleRequestJson = PublicCreateOrganizationRoleBody +export const CreateRoleRequestJson = PublicCreateOrganizationRoleBody +export type CreateRole200 = Role +export const CreateRole200 = Role +export type UpdateRoleRequestJson = PublicUpdateOrganizationRoleBody +export const UpdateRoleRequestJson = PublicUpdateOrganizationRoleBody +export type UpdateRole200 = Role +export const UpdateRole200 = Role +export type DeleteRole200 = RoleDeletedResource +export const DeleteRole200 = RoleDeletedResource +export type UsageAudioSpeechesParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "project_ids"?: ReadonlyArray + readonly "user_ids"?: ReadonlyArray + readonly "api_key_ids"?: ReadonlyArray + readonly "models"?: ReadonlyArray + readonly "group_by"?: ReadonlyArray<"project_id" | "user_id" | "api_key_id" | "model"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageAudioSpeechesParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "user_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "api_key_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "models": Schema.optionalKey(Schema.Array(Schema.String)), + "group_by": Schema.optionalKey(Schema.Array(Schema.Literals(["project_id", "user_id", "api_key_id", "model"]))), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageAudioSpeeches200 = UsageResponse +export const UsageAudioSpeeches200 = UsageResponse +export type UsageAudioTranscriptionsParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "project_ids"?: ReadonlyArray + readonly "user_ids"?: ReadonlyArray + readonly "api_key_ids"?: ReadonlyArray + readonly "models"?: ReadonlyArray + readonly "group_by"?: ReadonlyArray<"project_id" | "user_id" | "api_key_id" | "model"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageAudioTranscriptionsParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "user_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "api_key_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "models": Schema.optionalKey(Schema.Array(Schema.String)), + "group_by": Schema.optionalKey(Schema.Array(Schema.Literals(["project_id", "user_id", "api_key_id", "model"]))), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageAudioTranscriptions200 = UsageResponse +export const UsageAudioTranscriptions200 = UsageResponse +export type UsageCodeInterpreterSessionsParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "project_ids"?: ReadonlyArray + readonly "group_by"?: ReadonlyArray<"project_id"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageCodeInterpreterSessionsParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "group_by": Schema.optionalKey(Schema.Array(Schema.Literal("project_id"))), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageCodeInterpreterSessions200 = UsageResponse +export const UsageCodeInterpreterSessions200 = UsageResponse +export type UsageCompletionsParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "project_ids"?: ReadonlyArray + readonly "user_ids"?: ReadonlyArray + readonly "api_key_ids"?: ReadonlyArray + readonly "models"?: ReadonlyArray + readonly "batch"?: boolean + readonly "group_by"?: ReadonlyArray<"project_id" | "user_id" | "api_key_id" | "model" | "batch" | "service_tier"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageCompletionsParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "user_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "api_key_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "models": Schema.optionalKey(Schema.Array(Schema.String)), + "batch": Schema.optionalKey(Schema.Boolean), + "group_by": Schema.optionalKey( + Schema.Array(Schema.Literals(["project_id", "user_id", "api_key_id", "model", "batch", "service_tier"])) + ), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageCompletions200 = UsageResponse +export const UsageCompletions200 = UsageResponse +export type UsageEmbeddingsParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "project_ids"?: ReadonlyArray + readonly "user_ids"?: ReadonlyArray + readonly "api_key_ids"?: ReadonlyArray + readonly "models"?: ReadonlyArray + readonly "group_by"?: ReadonlyArray<"project_id" | "user_id" | "api_key_id" | "model"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageEmbeddingsParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "user_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "api_key_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "models": Schema.optionalKey(Schema.Array(Schema.String)), + "group_by": Schema.optionalKey(Schema.Array(Schema.Literals(["project_id", "user_id", "api_key_id", "model"]))), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageEmbeddings200 = UsageResponse +export const UsageEmbeddings200 = UsageResponse +export type UsageFileSearchCallsParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "project_ids"?: ReadonlyArray + readonly "user_ids"?: ReadonlyArray + readonly "api_key_ids"?: ReadonlyArray + readonly "vector_store_ids"?: ReadonlyArray + readonly "group_by"?: ReadonlyArray<"project_id" | "user_id" | "api_key_id" | "vector_store_id"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageFileSearchCallsParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "user_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "api_key_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "vector_store_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "group_by": Schema.optionalKey( + Schema.Array(Schema.Literals(["project_id", "user_id", "api_key_id", "vector_store_id"])) + ), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageFileSearchCalls200 = UsageResponse +export const UsageFileSearchCalls200 = UsageResponse +export type UsageImagesParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "sources"?: ReadonlyArray<"image.generation" | "image.edit" | "image.variation"> + readonly "sizes"?: ReadonlyArray<"256x256" | "512x512" | "1024x1024" | "1792x1792" | "1024x1792"> + readonly "project_ids"?: ReadonlyArray + readonly "user_ids"?: ReadonlyArray + readonly "api_key_ids"?: ReadonlyArray + readonly "models"?: ReadonlyArray + readonly "group_by"?: ReadonlyArray<"project_id" | "user_id" | "api_key_id" | "model" | "size" | "source"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageImagesParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "sources": Schema.optionalKey(Schema.Array(Schema.Literals(["image.generation", "image.edit", "image.variation"]))), + "sizes": Schema.optionalKey( + Schema.Array(Schema.Literals(["256x256", "512x512", "1024x1024", "1792x1792", "1024x1792"])) + ), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "user_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "api_key_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "models": Schema.optionalKey(Schema.Array(Schema.String)), + "group_by": Schema.optionalKey( + Schema.Array(Schema.Literals(["project_id", "user_id", "api_key_id", "model", "size", "source"])) + ), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageImages200 = UsageResponse +export const UsageImages200 = UsageResponse +export type UsageModerationsParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "project_ids"?: ReadonlyArray + readonly "user_ids"?: ReadonlyArray + readonly "api_key_ids"?: ReadonlyArray + readonly "models"?: ReadonlyArray + readonly "group_by"?: ReadonlyArray<"project_id" | "user_id" | "api_key_id" | "model"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageModerationsParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "user_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "api_key_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "models": Schema.optionalKey(Schema.Array(Schema.String)), + "group_by": Schema.optionalKey(Schema.Array(Schema.Literals(["project_id", "user_id", "api_key_id", "model"]))), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageModerations200 = UsageResponse +export const UsageModerations200 = UsageResponse +export type UsageVectorStoresParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "project_ids"?: ReadonlyArray + readonly "group_by"?: ReadonlyArray<"project_id"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageVectorStoresParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "group_by": Schema.optionalKey(Schema.Array(Schema.Literal("project_id"))), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageVectorStores200 = UsageResponse +export const UsageVectorStores200 = UsageResponse +export type UsageWebSearchCallsParams = { + readonly "start_time": number + readonly "end_time"?: number + readonly "bucket_width"?: "1m" | "1h" | "1d" + readonly "project_ids"?: ReadonlyArray + readonly "user_ids"?: ReadonlyArray + readonly "api_key_ids"?: ReadonlyArray + readonly "models"?: ReadonlyArray + readonly "context_levels"?: ReadonlyArray<"low" | "medium" | "high"> + readonly "group_by"?: ReadonlyArray<"project_id" | "user_id" | "api_key_id" | "model" | "context_level"> + readonly "limit"?: number + readonly "page"?: string +} +export const UsageWebSearchCallsParams = Schema.Struct({ + "start_time": Schema.Number.check(Schema.isInt()), + "end_time": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "bucket_width": Schema.optionalKey(Schema.Literals(["1m", "1h", "1d"])), + "project_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "user_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "api_key_ids": Schema.optionalKey(Schema.Array(Schema.String)), + "models": Schema.optionalKey(Schema.Array(Schema.String)), + "context_levels": Schema.optionalKey(Schema.Array(Schema.Literals(["low", "medium", "high"]))), + "group_by": Schema.optionalKey( + Schema.Array(Schema.Literals(["project_id", "user_id", "api_key_id", "model", "context_level"])) + ), + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "page": Schema.optionalKey(Schema.String) +}) +export type UsageWebSearchCalls200 = UsageResponse +export const UsageWebSearchCalls200 = UsageResponse +export type ListUsersParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "emails"?: ReadonlyArray +} +export const ListUsersParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "after": Schema.optionalKey(Schema.String), + "emails": Schema.optionalKey(Schema.Array(Schema.String)) +}) +export type ListUsers200 = UserListResponse +export const ListUsers200 = UserListResponse +export type RetrieveUser200 = User +export const RetrieveUser200 = User +export type ModifyUserRequestJson = UserRoleUpdateRequest +export const ModifyUserRequestJson = UserRoleUpdateRequest +export type ModifyUser200 = User +export const ModifyUser200 = User +export type DeleteUser200 = UserDeleteResponse +export const DeleteUser200 = UserDeleteResponse +export type ListUserRoleAssignmentsParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListUserRoleAssignmentsParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListUserRoleAssignments200 = RoleListResource +export const ListUserRoleAssignments200 = RoleListResource +export type AssignUserRoleRequestJson = PublicAssignOrganizationGroupRoleBody +export const AssignUserRoleRequestJson = PublicAssignOrganizationGroupRoleBody +export type AssignUserRole200 = UserRoleAssignment +export const AssignUserRole200 = UserRoleAssignment +export type UnassignUserRole200 = DeletedRoleAssignmentResource +export const UnassignUserRole200 = DeletedRoleAssignmentResource +export type ListProjectGroupRoleAssignmentsParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListProjectGroupRoleAssignmentsParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListProjectGroupRoleAssignments200 = RoleListResource +export const ListProjectGroupRoleAssignments200 = RoleListResource +export type AssignProjectGroupRoleRequestJson = PublicAssignOrganizationGroupRoleBody +export const AssignProjectGroupRoleRequestJson = PublicAssignOrganizationGroupRoleBody +export type AssignProjectGroupRole200 = GroupRoleAssignment +export const AssignProjectGroupRole200 = GroupRoleAssignment +export type UnassignProjectGroupRole200 = DeletedRoleAssignmentResource +export const UnassignProjectGroupRole200 = DeletedRoleAssignmentResource +export type ListProjectRolesParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListProjectRolesParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListProjectRoles200 = PublicRoleListResource +export const ListProjectRoles200 = PublicRoleListResource +export type CreateProjectRoleRequestJson = PublicCreateOrganizationRoleBody +export const CreateProjectRoleRequestJson = PublicCreateOrganizationRoleBody +export type CreateProjectRole200 = Role +export const CreateProjectRole200 = Role +export type UpdateProjectRoleRequestJson = PublicUpdateOrganizationRoleBody +export const UpdateProjectRoleRequestJson = PublicUpdateOrganizationRoleBody +export type UpdateProjectRole200 = Role +export const UpdateProjectRole200 = Role +export type DeleteProjectRole200 = RoleDeletedResource +export const DeleteProjectRole200 = RoleDeletedResource +export type ListProjectUserRoleAssignmentsParams = { + readonly "limit"?: number + readonly "after"?: string + readonly "order"?: "asc" | "desc" +} +export const ListProjectUserRoleAssignmentsParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(1000)) + ), + "after": Schema.optionalKey(Schema.String), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])) +}) +export type ListProjectUserRoleAssignments200 = RoleListResource +export const ListProjectUserRoleAssignments200 = RoleListResource +export type AssignProjectUserRoleRequestJson = PublicAssignOrganizationGroupRoleBody +export const AssignProjectUserRoleRequestJson = PublicAssignOrganizationGroupRoleBody +export type AssignProjectUserRole200 = UserRoleAssignment +export const AssignProjectUserRole200 = UserRoleAssignment +export type UnassignProjectUserRole200 = DeletedRoleAssignmentResource +export const UnassignProjectUserRole200 = DeletedRoleAssignmentResource +export type CreateRealtimeCallRequestFormData = RealtimeCallCreateRequest +export const CreateRealtimeCallRequestFormData = RealtimeCallCreateRequest +export type AcceptRealtimeCallRequestJson = RealtimeSessionCreateRequestGA +export const AcceptRealtimeCallRequestJson = RealtimeSessionCreateRequestGA +export type ReferRealtimeCallRequestJson = RealtimeCallReferRequest +export const ReferRealtimeCallRequestJson = RealtimeCallReferRequest +export type RejectRealtimeCallRequestJson = RealtimeCallRejectRequest +export const RejectRealtimeCallRequestJson = RealtimeCallRejectRequest +export type CreateRealtimeClientSecretRequestJson = RealtimeCreateClientSecretRequest +export const CreateRealtimeClientSecretRequestJson = RealtimeCreateClientSecretRequest +export type CreateRealtimeClientSecret200 = RealtimeCreateClientSecretResponse +export const CreateRealtimeClientSecret200 = RealtimeCreateClientSecretResponse +export type CreateRealtimeSessionRequestJson = RealtimeSessionCreateRequest +export const CreateRealtimeSessionRequestJson = RealtimeSessionCreateRequest +export type CreateRealtimeSession200 = RealtimeSessionCreateResponse +export const CreateRealtimeSession200 = RealtimeSessionCreateResponse +export type CreateRealtimeTranscriptionSessionRequestJson = RealtimeTranscriptionSessionCreateRequest +export const CreateRealtimeTranscriptionSessionRequestJson = RealtimeTranscriptionSessionCreateRequest +export type CreateRealtimeTranscriptionSession200 = RealtimeTranscriptionSessionCreateResponse +export const CreateRealtimeTranscriptionSession200 = RealtimeTranscriptionSessionCreateResponse +export type CreateRealtimeTranslationClientSecretRequestJson = RealtimeTranslationClientSecretCreateRequest +export const CreateRealtimeTranslationClientSecretRequestJson = RealtimeTranslationClientSecretCreateRequest +export type CreateRealtimeTranslationClientSecret200 = RealtimeTranslationClientSecretCreateResponse +export const CreateRealtimeTranslationClientSecret200 = RealtimeTranslationClientSecretCreateResponse +export type CreateResponseRequestJson = CreateResponse +export const CreateResponseRequestJson = CreateResponse +export type CreateResponse200 = Response +export const CreateResponse200 = Response +export type CreateResponse200Sse = ResponseStreamEvent +export const CreateResponse200Sse = ResponseStreamEvent +export type GetResponseParams = { + readonly "include"?: ReadonlyArray + readonly "stream"?: boolean + readonly "starting_after"?: number + readonly "include_obfuscation"?: boolean +} +export const GetResponseParams = Schema.Struct({ + "include": Schema.optionalKey(Schema.Array(IncludeEnum)), + "stream": Schema.optionalKey(Schema.Boolean), + "starting_after": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "include_obfuscation": Schema.optionalKey(Schema.Boolean) +}) +export type GetResponse200 = Response +export const GetResponse200 = Response +export type DeleteResponse404 = Error +export const DeleteResponse404 = Error +export type CancelResponse200 = Response +export const CancelResponse200 = Response +export type CancelResponse404 = Error +export const CancelResponse404 = Error +export type ListInputItemsParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "include"?: ReadonlyArray +} +export const ListInputItemsParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "include": Schema.optionalKey(Schema.Array(IncludeEnum)) +}) +export type ListInputItems200 = ResponseItemList +export const ListInputItems200 = ResponseItemList +export type CreateThreadRequestJson = CreateThreadRequest +export const CreateThreadRequestJson = CreateThreadRequest +export type CreateThread200 = ThreadObject +export const CreateThread200 = ThreadObject +export type CreateThreadAndRunRequestJson = CreateThreadAndRunRequest +export const CreateThreadAndRunRequestJson = CreateThreadAndRunRequest +export type CreateThreadAndRun200 = RunObject +export const CreateThreadAndRun200 = RunObject +export type GetThread200 = ThreadObject +export const GetThread200 = ThreadObject +export type ModifyThreadRequestJson = ModifyThreadRequest +export const ModifyThreadRequestJson = ModifyThreadRequest +export type ModifyThread200 = ThreadObject +export const ModifyThread200 = ThreadObject +export type DeleteThread200 = DeleteThreadResponse +export const DeleteThread200 = DeleteThreadResponse +export type ListMessagesParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "before"?: string + readonly "run_id"?: string +} +export const ListMessagesParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "before": Schema.optionalKey(Schema.String), + "run_id": Schema.optionalKey(Schema.String) +}) +export type ListMessages200 = ListMessagesResponse +export const ListMessages200 = ListMessagesResponse +export type CreateMessageRequestJson = CreateMessageRequest +export const CreateMessageRequestJson = CreateMessageRequest +export type CreateMessage200 = MessageObject +export const CreateMessage200 = MessageObject +export type GetMessage200 = MessageObject +export const GetMessage200 = MessageObject +export type ModifyMessageRequestJson = ModifyMessageRequest +export const ModifyMessageRequestJson = ModifyMessageRequest +export type ModifyMessage200 = MessageObject +export const ModifyMessage200 = MessageObject +export type DeleteMessage200 = DeleteMessageResponse +export const DeleteMessage200 = DeleteMessageResponse +export type ListRunsParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "before"?: string +} +export const ListRunsParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "before": Schema.optionalKey(Schema.String) +}) +export type ListRuns200 = ListRunsResponse +export const ListRuns200 = ListRunsResponse +export type CreateRunParams = { + readonly "include[]"?: ReadonlyArray<"step_details.tool_calls[*].file_search.results[*].content"> +} +export const CreateRunParams = Schema.Struct({ + "include[]": Schema.optionalKey( + Schema.Array(Schema.Literal("step_details.tool_calls[*].file_search.results[*].content")) + ) +}) +export type CreateRunRequestJson = CreateRunRequest +export const CreateRunRequestJson = CreateRunRequest +export type CreateRun200 = RunObject +export const CreateRun200 = RunObject +export type GetRun200 = RunObject +export const GetRun200 = RunObject +export type ModifyRunRequestJson = ModifyRunRequest +export const ModifyRunRequestJson = ModifyRunRequest +export type ModifyRun200 = RunObject +export const ModifyRun200 = RunObject +export type CancelRun200 = RunObject +export const CancelRun200 = RunObject +export type ListRunStepsParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "before"?: string + readonly "include[]"?: ReadonlyArray<"step_details.tool_calls[*].file_search.results[*].content"> +} +export const ListRunStepsParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "before": Schema.optionalKey(Schema.String), + "include[]": Schema.optionalKey( + Schema.Array(Schema.Literal("step_details.tool_calls[*].file_search.results[*].content")) + ) +}) +export type ListRunSteps200 = ListRunStepsResponse +export const ListRunSteps200 = ListRunStepsResponse +export type GetRunStepParams = { + readonly "include[]"?: ReadonlyArray<"step_details.tool_calls[*].file_search.results[*].content"> +} +export const GetRunStepParams = Schema.Struct({ + "include[]": Schema.optionalKey( + Schema.Array(Schema.Literal("step_details.tool_calls[*].file_search.results[*].content")) + ) +}) +export type GetRunStep200 = RunStepObject +export const GetRunStep200 = RunStepObject +export type SubmitToolOuputsToRunRequestJson = SubmitToolOutputsRunRequest +export const SubmitToolOuputsToRunRequestJson = SubmitToolOutputsRunRequest +export type SubmitToolOuputsToRun200 = RunObject +export const SubmitToolOuputsToRun200 = RunObject +export type CreateUploadRequestJson = CreateUploadRequest +export const CreateUploadRequestJson = CreateUploadRequest +export type CreateUpload200 = Upload +export const CreateUpload200 = Upload +export type CancelUpload200 = Upload +export const CancelUpload200 = Upload +export type CompleteUploadRequestJson = CompleteUploadRequest +export const CompleteUploadRequestJson = CompleteUploadRequest +export type CompleteUpload200 = Upload +export const CompleteUpload200 = Upload +export type AddUploadPartRequestFormData = AddUploadPartRequest +export const AddUploadPartRequestFormData = AddUploadPartRequest +export type AddUploadPart200 = UploadPart +export const AddUploadPart200 = UploadPart +export type ListVectorStoresParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "before"?: string +} +export const ListVectorStoresParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "before": Schema.optionalKey(Schema.String) +}) +export type ListVectorStores200 = ListVectorStoresResponse +export const ListVectorStores200 = ListVectorStoresResponse +export type CreateVectorStoreRequestJson = CreateVectorStoreRequest +export const CreateVectorStoreRequestJson = CreateVectorStoreRequest +export type CreateVectorStore200 = VectorStoreObject +export const CreateVectorStore200 = VectorStoreObject +export type GetVectorStore200 = VectorStoreObject +export const GetVectorStore200 = VectorStoreObject +export type ModifyVectorStoreRequestJson = UpdateVectorStoreRequest +export const ModifyVectorStoreRequestJson = UpdateVectorStoreRequest +export type ModifyVectorStore200 = VectorStoreObject +export const ModifyVectorStore200 = VectorStoreObject +export type DeleteVectorStore200 = DeleteVectorStoreResponse +export const DeleteVectorStore200 = DeleteVectorStoreResponse +export type CreateVectorStoreFileBatchRequestJson = CreateVectorStoreFileBatchRequest +export const CreateVectorStoreFileBatchRequestJson = CreateVectorStoreFileBatchRequest +export type CreateVectorStoreFileBatch200 = VectorStoreFileBatchObject +export const CreateVectorStoreFileBatch200 = VectorStoreFileBatchObject +export type GetVectorStoreFileBatch200 = VectorStoreFileBatchObject +export const GetVectorStoreFileBatch200 = VectorStoreFileBatchObject +export type CancelVectorStoreFileBatch200 = VectorStoreFileBatchObject +export const CancelVectorStoreFileBatch200 = VectorStoreFileBatchObject +export type ListFilesInVectorStoreBatchParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "before"?: string + readonly "filter"?: "in_progress" | "completed" | "failed" | "cancelled" +} +export const ListFilesInVectorStoreBatchParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "before": Schema.optionalKey(Schema.String), + "filter": Schema.optionalKey(Schema.Literals(["in_progress", "completed", "failed", "cancelled"])) +}) +export type ListFilesInVectorStoreBatch200 = ListVectorStoreFilesResponse +export const ListFilesInVectorStoreBatch200 = ListVectorStoreFilesResponse +export type ListVectorStoreFilesParams = { + readonly "limit"?: number + readonly "order"?: "asc" | "desc" + readonly "after"?: string + readonly "before"?: string + readonly "filter"?: "in_progress" | "completed" | "failed" | "cancelled" +} +export const ListVectorStoreFilesParams = Schema.Struct({ + "limit": Schema.optionalKey(Schema.Number.check(Schema.isInt())), + "order": Schema.optionalKey(Schema.Literals(["asc", "desc"])), + "after": Schema.optionalKey(Schema.String), + "before": Schema.optionalKey(Schema.String), + "filter": Schema.optionalKey(Schema.Literals(["in_progress", "completed", "failed", "cancelled"])) +}) +export type ListVectorStoreFiles200 = ListVectorStoreFilesResponse +export const ListVectorStoreFiles200 = ListVectorStoreFilesResponse +export type CreateVectorStoreFileRequestJson = CreateVectorStoreFileRequest +export const CreateVectorStoreFileRequestJson = CreateVectorStoreFileRequest +export type CreateVectorStoreFile200 = VectorStoreFileObject +export const CreateVectorStoreFile200 = VectorStoreFileObject +export type GetVectorStoreFile200 = VectorStoreFileObject +export const GetVectorStoreFile200 = VectorStoreFileObject +export type UpdateVectorStoreFileAttributesRequestJson = UpdateVectorStoreFileAttributesRequest +export const UpdateVectorStoreFileAttributesRequestJson = UpdateVectorStoreFileAttributesRequest +export type UpdateVectorStoreFileAttributes200 = VectorStoreFileObject +export const UpdateVectorStoreFileAttributes200 = VectorStoreFileObject +export type DeleteVectorStoreFile200 = DeleteVectorStoreFileResponse +export const DeleteVectorStoreFile200 = DeleteVectorStoreFileResponse +export type RetrieveVectorStoreFileContent200 = VectorStoreFileContentResponse +export const RetrieveVectorStoreFileContent200 = VectorStoreFileContentResponse +export type SearchVectorStoreRequestJson = VectorStoreSearchRequest +export const SearchVectorStoreRequestJson = VectorStoreSearchRequest +export type SearchVectorStore200 = VectorStoreSearchResultsPage +export const SearchVectorStore200 = VectorStoreSearchResultsPage +export type CreateConversationRequestJson = CreateConversationBody +export const CreateConversationRequestJson = CreateConversationBody +export type CreateConversation200 = ConversationResource +export const CreateConversation200 = ConversationResource +export type GetConversation200 = ConversationResource +export const GetConversation200 = ConversationResource +export type UpdateConversationRequestJson = UpdateConversationBody +export const UpdateConversationRequestJson = UpdateConversationBody +export type UpdateConversation200 = ConversationResource +export const UpdateConversation200 = ConversationResource +export type DeleteConversation200 = DeletedConversationResource +export const DeleteConversation200 = DeletedConversationResource +export type ListVideosParams = { readonly "limit"?: number; readonly "order"?: OrderEnum; readonly "after"?: string } +export const ListVideosParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(100)) + ), + "order": Schema.optionalKey(OrderEnum), + "after": Schema.optionalKey( + Schema.String.annotate({ "description": "Identifier for the last item from the previous pagination request" }) + ) +}) +export type ListVideos200 = VideoListResource +export const ListVideos200 = VideoListResource +export type CreateVideoRequestJson = CreateVideoJsonBody +export const CreateVideoRequestJson = CreateVideoJsonBody +export type CreateVideoRequestFormData = CreateVideoMultipartBody +export const CreateVideoRequestFormData = CreateVideoMultipartBody +export type CreateVideo200 = VideoResource +export const CreateVideo200 = VideoResource +export type CreateVideoCharacterRequestFormData = CreateVideoCharacterBody +export const CreateVideoCharacterRequestFormData = CreateVideoCharacterBody +export type CreateVideoCharacter200 = VideoCharacterResource +export const CreateVideoCharacter200 = VideoCharacterResource +export type GetVideoCharacter200 = VideoCharacterResource +export const GetVideoCharacter200 = VideoCharacterResource +export type CreateVideoEditRequestJson = CreateVideoEditJsonBody +export const CreateVideoEditRequestJson = CreateVideoEditJsonBody +export type CreateVideoEditRequestFormData = CreateVideoEditMultipartBody +export const CreateVideoEditRequestFormData = CreateVideoEditMultipartBody +export type CreateVideoEdit200 = VideoResource +export const CreateVideoEdit200 = VideoResource +export type CreateVideoExtendRequestJson = CreateVideoExtendJsonBody +export const CreateVideoExtendRequestJson = CreateVideoExtendJsonBody +export type CreateVideoExtendRequestFormData = CreateVideoExtendMultipartBody +export const CreateVideoExtendRequestFormData = CreateVideoExtendMultipartBody +export type CreateVideoExtend200 = VideoResource +export const CreateVideoExtend200 = VideoResource +export type GetVideo200 = VideoResource +export const GetVideo200 = VideoResource +export type DeleteVideo200 = DeletedVideoResource +export const DeleteVideo200 = DeletedVideoResource +export type RetrieveVideoContentParams = { readonly "variant"?: VideoContentVariant } +export const RetrieveVideoContentParams = Schema.Struct({ "variant": Schema.optionalKey(VideoContentVariant) }) +export type RetrieveVideoContent200 = string +export const RetrieveVideoContent200 = Schema.String +export type CreateVideoRemixRequestJson = CreateVideoRemixBody +export const CreateVideoRemixRequestJson = CreateVideoRemixBody +export type CreateVideoRemixRequestFormData = CreateVideoRemixBody +export const CreateVideoRemixRequestFormData = CreateVideoRemixBody +export type CreateVideoRemix200 = VideoResource +export const CreateVideoRemix200 = VideoResource +export type GetinputtokencountsRequestJson = TokenCountsBody +export const GetinputtokencountsRequestJson = TokenCountsBody +export type GetinputtokencountsRequestFormUrlEncoded = TokenCountsBody +export const GetinputtokencountsRequestFormUrlEncoded = TokenCountsBody +export type Getinputtokencounts200 = TokenCountsResource +export const Getinputtokencounts200 = TokenCountsResource +export type CompactconversationRequestJson = CompactResponseMethodPublicBody +export const CompactconversationRequestJson = CompactResponseMethodPublicBody +export type CompactconversationRequestFormUrlEncoded = CompactResponseMethodPublicBody +export const CompactconversationRequestFormUrlEncoded = CompactResponseMethodPublicBody +export type Compactconversation200 = CompactResource +export const Compactconversation200 = CompactResource +export type ListSkillsParams = { readonly "limit"?: number; readonly "order"?: OrderEnum; readonly "after"?: string } +export const ListSkillsParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(100)) + ), + "order": Schema.optionalKey(OrderEnum), + "after": Schema.optionalKey( + Schema.String.annotate({ "description": "Identifier for the last item from the previous pagination request" }) + ) +}) +export type ListSkills200 = SkillListResource +export const ListSkills200 = SkillListResource +export type CreateSkillRequestJson = CreateSkillBody +export const CreateSkillRequestJson = CreateSkillBody +export type CreateSkillRequestFormData = CreateSkillBody +export const CreateSkillRequestFormData = CreateSkillBody +export type CreateSkill200 = SkillResource +export const CreateSkill200 = SkillResource +export type GetSkill200 = SkillResource +export const GetSkill200 = SkillResource +export type UpdateSkillDefaultVersionRequestJson = SetDefaultSkillVersionBody +export const UpdateSkillDefaultVersionRequestJson = SetDefaultSkillVersionBody +export type UpdateSkillDefaultVersionRequestFormUrlEncoded = SetDefaultSkillVersionBody +export const UpdateSkillDefaultVersionRequestFormUrlEncoded = SetDefaultSkillVersionBody +export type UpdateSkillDefaultVersion200 = SkillResource +export const UpdateSkillDefaultVersion200 = SkillResource +export type DeleteSkill200 = DeletedSkillResource +export const DeleteSkill200 = DeletedSkillResource +export type GetSkillContent200 = string +export const GetSkillContent200 = Schema.String +export type ListSkillVersionsParams = { + readonly "limit"?: number + readonly "order"?: OrderEnum + readonly "after"?: string +} +export const ListSkillVersionsParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(100)) + ), + "order": Schema.optionalKey(OrderEnum), + "after": Schema.optionalKey(Schema.String) +}) +export type ListSkillVersions200 = SkillVersionListResource +export const ListSkillVersions200 = SkillVersionListResource +export type CreateSkillVersionRequestJson = CreateSkillVersionBody +export const CreateSkillVersionRequestJson = CreateSkillVersionBody +export type CreateSkillVersionRequestFormData = CreateSkillVersionBody +export const CreateSkillVersionRequestFormData = CreateSkillVersionBody +export type CreateSkillVersion200 = SkillVersionResource +export const CreateSkillVersion200 = SkillVersionResource +export type GetSkillVersion200 = SkillVersionResource +export const GetSkillVersion200 = SkillVersionResource +export type DeleteSkillVersion200 = DeletedSkillVersionResource +export const DeleteSkillVersion200 = DeletedSkillVersionResource +export type GetSkillVersionContent200 = string +export const GetSkillVersionContent200 = Schema.String +export type CancelChatSessionMethod200 = ChatSessionResource +export const CancelChatSessionMethod200 = ChatSessionResource +export type CreateChatSessionMethodRequestJson = CreateChatSessionBody +export const CreateChatSessionMethodRequestJson = CreateChatSessionBody +export type CreateChatSessionMethod200 = ChatSessionResource +export const CreateChatSessionMethod200 = ChatSessionResource +export type ListThreadItemsMethodParams = { + readonly "limit"?: number + readonly "order"?: OrderEnum + readonly "after"?: string + readonly "before"?: string +} +export const ListThreadItemsMethodParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(100)) + ), + "order": Schema.optionalKey(OrderEnum), + "after": Schema.optionalKey( + Schema.String.annotate({ + "description": "List items created after this thread item ID. Defaults to null for the first page." + }) + ), + "before": Schema.optionalKey( + Schema.String.annotate({ + "description": "List items created before this thread item ID. Defaults to null for the newest results." + }) + ) +}) +export type ListThreadItemsMethod200 = ThreadItemListResource +export const ListThreadItemsMethod200 = ThreadItemListResource +export type GetThreadMethod200 = ThreadResource +export const GetThreadMethod200 = ThreadResource +export type DeleteThreadMethod200 = DeletedThreadResource +export const DeleteThreadMethod200 = DeletedThreadResource +export type ListThreadsMethodParams = { + readonly "limit"?: number + readonly "order"?: OrderEnum + readonly "after"?: string + readonly "before"?: string + readonly "user"?: string +} +export const ListThreadsMethodParams = Schema.Struct({ + "limit": Schema.optionalKey( + Schema.Number.check(Schema.isInt()).check(Schema.isGreaterThanOrEqualTo(0)).check(Schema.isLessThanOrEqualTo(100)) + ), + "order": Schema.optionalKey(OrderEnum), + "after": Schema.optionalKey( + Schema.String.annotate({ + "description": "List items created after this thread item ID. Defaults to null for the first page." + }) + ), + "before": Schema.optionalKey( + Schema.String.annotate({ + "description": "List items created before this thread item ID. Defaults to null for the newest results." + }) + ), + "user": Schema.optionalKey( + Schema.String.annotate({ + "description": "Filter threads that belong to this user identifier. Defaults to null to return all users." + }).check(Schema.isMinLength(1)).check(Schema.isMaxLength(512)) + ) +}) +export type ListThreadsMethod200 = ThreadListResource +export const ListThreadsMethod200 = ThreadListResource + +export interface OperationConfig { + /** + * Whether or not the response should be included in the value returned from + * an operation. + * + * If set to `true`, a tuple of `[A, HttpClientResponse]` will be returned, + * where `A` is the success type of the operation. + * + * If set to `false`, only the success type of the operation will be returned. + */ + readonly includeResponse?: boolean | undefined +} + +/** + * A utility type which optionally includes the response in the return result + * of an operation based upon the value of the `includeResponse` configuration + * option. + */ +export type WithOptionalResponse = Config extends { + readonly includeResponse: true +} ? [A, HttpClientResponse.HttpClientResponse] : + A + +export const make = ( + httpClient: HttpClient.HttpClient, + options: { + readonly transformClient?: ((client: HttpClient.HttpClient) => Effect.Effect) | undefined + } = {} +): OpenAiClient => { + const unexpectedStatus = (response: HttpClientResponse.HttpClientResponse) => + Effect.flatMap( + Effect.orElseSucceed(response.json, () => "Unexpected status code"), + (description) => + Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.StatusCodeError({ + request: response.request, + response, + description: typeof description === "string" ? description : JSON.stringify(description) + }) + }) + ) + ) + const withResponse = (config: Config | undefined) => + ( + f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect + ): (request: HttpClientRequest.HttpClientRequest) => Effect.Effect => { + const withOptionalResponse = ( + config?.includeResponse + ? (response: HttpClientResponse.HttpClientResponse) => Effect.map(f(response), (a) => [a, response]) + : (response: HttpClientResponse.HttpClientResponse) => f(response) + ) as any + return options?.transformClient + ? (request) => + Effect.flatMap( + Effect.flatMap(options.transformClient!(httpClient), (client) => client.execute(request)), + withOptionalResponse + ) + : (request) => Effect.flatMap(httpClient.execute(request), withOptionalResponse) + } + const sseRequest = < + Type, + DecodingServices + >( + schema: Schema.ConstraintDecoder + ) => + ( + request: HttpClientRequest.HttpClientRequest + ): Stream.Stream< + { readonly event: string; readonly id: string | undefined; readonly data: Type }, + HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, + DecodingServices + > => + HttpClient.filterStatusOk(httpClient).execute(request).pipe( + Effect.map((response) => response.stream), + Stream.unwrap, + Stream.decodeText(), + Stream.pipeThroughChannel(Sse.decodeDataSchema(schema)) + ) + const binaryRequest = ( + request: HttpClientRequest.HttpClientRequest + ): Stream.Stream => + HttpClient.filterStatusOk(httpClient).execute(request).pipe( + Effect.map((response) => response.stream), + Stream.unwrap + ) + const decodeSuccess = + (schema: Schema) => (response: HttpClientResponse.HttpClientResponse) => + HttpClientResponse.schemaBodyJson(schema)(response) + const decodeError = + (tag: Tag, schema: Schema) => + (response: HttpClientResponse.HttpClientResponse) => + Effect.flatMap( + HttpClientResponse.schemaBodyJson(schema)(response), + (cause) => Effect.fail(OpenAiClientError(tag, cause, response)) + ) + return { + httpClient, + "listAssistants": (options) => + HttpClientRequest.get(`/assistants`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListAssistants200), + orElse: unexpectedStatus + })) + ), + "createAssistant": (options) => + HttpClientRequest.post(`/assistants`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateAssistant200), + orElse: unexpectedStatus + })) + ), + "getAssistant": (assistantId, options) => + HttpClientRequest.get(`/assistants/${assistantId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetAssistant200), + orElse: unexpectedStatus + })) + ), + "modifyAssistant": (assistantId, options) => + HttpClientRequest.post(`/assistants/${assistantId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModifyAssistant200), + orElse: unexpectedStatus + })) + ), + "deleteAssistant": (assistantId, options) => + HttpClientRequest.delete(`/assistants/${assistantId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteAssistant200), + orElse: unexpectedStatus + })) + ), + "createSpeech": (options) => + HttpClientRequest.post(`/audio/speech`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + orElse: unexpectedStatus + })) + ), + "createSpeechSse": (options) => + HttpClientRequest.post(`/audio/speech`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + sseRequest(CreateSpeech200Sse) + ), + "createSpeechStream": (options) => + HttpClientRequest.post(`/audio/speech`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + binaryRequest + ), + "createTranscription": (options) => + HttpClientRequest.post(`/audio/transcriptions`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateTranscription200), + orElse: unexpectedStatus + })) + ), + "createTranscriptionSse": (options) => + HttpClientRequest.post(`/audio/transcriptions`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + sseRequest(CreateTranscription200Sse) + ), + "createTranslation": (options) => + HttpClientRequest.post(`/audio/translations`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateTranslation200), + orElse: unexpectedStatus + })) + ), + "listVoiceConsents": (options) => + HttpClientRequest.get(`/audio/voice_consents`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListVoiceConsents200), + orElse: unexpectedStatus + })) + ), + "createVoiceConsent": (options) => + HttpClientRequest.post(`/audio/voice_consents`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVoiceConsent200), + orElse: unexpectedStatus + })) + ), + "getVoiceConsent": (consentId, options) => + HttpClientRequest.get(`/audio/voice_consents/${consentId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetVoiceConsent200), + orElse: unexpectedStatus + })) + ), + "updateVoiceConsent": (consentId, options) => + HttpClientRequest.post(`/audio/voice_consents/${consentId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateVoiceConsent200), + orElse: unexpectedStatus + })) + ), + "deleteVoiceConsent": (consentId, options) => + HttpClientRequest.delete(`/audio/voice_consents/${consentId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteVoiceConsent200), + orElse: unexpectedStatus + })) + ), + "createVoice": (options) => + HttpClientRequest.post(`/audio/voices`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVoice200), + orElse: unexpectedStatus + })) + ), + "listBatches": (options) => + HttpClientRequest.get(`/batches`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListBatches200), + orElse: unexpectedStatus + })) + ), + "createBatch": (options) => + HttpClientRequest.post(`/batches`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateBatch200), + orElse: unexpectedStatus + })) + ), + "retrieveBatch": (batchId, options) => + HttpClientRequest.get(`/batches/${batchId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveBatch200), + orElse: unexpectedStatus + })) + ), + "cancelBatch": (batchId, options) => + HttpClientRequest.post(`/batches/${batchId}/cancel`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CancelBatch200), + orElse: unexpectedStatus + })) + ), + "listChatCompletions": (options) => + HttpClientRequest.get(`/chat/completions`).pipe( + HttpClientRequest.setUrlParams({ + "model": options?.params?.["model"] as any, + "metadata": options?.params?.["metadata"] as any, + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListChatCompletions200), + orElse: unexpectedStatus + })) + ), + "createChatCompletion": (options) => + HttpClientRequest.post(`/chat/completions`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateChatCompletion200), + orElse: unexpectedStatus + })) + ), + "createChatCompletionSse": (options) => + HttpClientRequest.post(`/chat/completions`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + sseRequest(CreateChatCompletion200Sse) + ), + "getChatCompletion": (completionId, options) => + HttpClientRequest.get(`/chat/completions/${completionId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetChatCompletion200), + orElse: unexpectedStatus + })) + ), + "updateChatCompletion": (completionId, options) => + HttpClientRequest.post(`/chat/completions/${completionId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateChatCompletion200), + orElse: unexpectedStatus + })) + ), + "deleteChatCompletion": (completionId, options) => + HttpClientRequest.delete(`/chat/completions/${completionId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteChatCompletion200), + orElse: unexpectedStatus + })) + ), + "getChatCompletionMessages": (completionId, options) => + HttpClientRequest.get(`/chat/completions/${completionId}/messages`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetChatCompletionMessages200), + orElse: unexpectedStatus + })) + ), + "createCompletion": (options) => + HttpClientRequest.post(`/completions`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateCompletion200), + orElse: unexpectedStatus + })) + ), + "ListContainers": (options) => + HttpClientRequest.get(`/containers`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "name": options?.params?.["name"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListContainers200), + orElse: unexpectedStatus + })) + ), + "CreateContainer": (options) => + HttpClientRequest.post(`/containers`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateContainer200), + orElse: unexpectedStatus + })) + ), + "RetrieveContainer": (containerId, options) => + HttpClientRequest.get(`/containers/${containerId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveContainer200), + orElse: unexpectedStatus + })) + ), + "DeleteContainer": (containerId, options) => + HttpClientRequest.delete(`/containers/${containerId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "200": () => Effect.void, + orElse: unexpectedStatus + })) + ), + "ListContainerFiles": (containerId, options) => + HttpClientRequest.get(`/containers/${containerId}/files`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListContainerFiles200), + orElse: unexpectedStatus + })) + ), + "CreateContainerFile": (containerId, options) => + HttpClientRequest.post(`/containers/${containerId}/files`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateContainerFile200), + orElse: unexpectedStatus + })) + ), + "RetrieveContainerFile": (containerId, fileId, options) => + HttpClientRequest.get(`/containers/${containerId}/files/${fileId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveContainerFile200), + orElse: unexpectedStatus + })) + ), + "DeleteContainerFile": (containerId, fileId, options) => + HttpClientRequest.delete(`/containers/${containerId}/files/${fileId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "200": () => Effect.void, + orElse: unexpectedStatus + })) + ), + "RetrieveContainerFileContent": (containerId, fileId, options) => + HttpClientRequest.get(`/containers/${containerId}/files/${fileId}/content`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "200": () => Effect.void, + orElse: unexpectedStatus + })) + ), + "listConversationItems": (conversationId, options) => + HttpClientRequest.get(`/conversations/${conversationId}/items`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "include": options?.params?.["include"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListConversationItems200), + orElse: unexpectedStatus + })) + ), + "createConversationItems": (conversationId, options) => + HttpClientRequest.post(`/conversations/${conversationId}/items`).pipe( + HttpClientRequest.setUrlParams({ "include": options.params?.["include"] as any }), + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateConversationItems200), + orElse: unexpectedStatus + })) + ), + "getConversationItem": (conversationId, itemId, options) => + HttpClientRequest.get(`/conversations/${conversationId}/items/${itemId}`).pipe( + HttpClientRequest.setUrlParams({ "include": options?.params?.["include"] as any }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetConversationItem200), + orElse: unexpectedStatus + })) + ), + "deleteConversationItem": (conversationId, itemId, options) => + HttpClientRequest.delete(`/conversations/${conversationId}/items/${itemId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteConversationItem200), + orElse: unexpectedStatus + })) + ), + "createEmbedding": (options) => + HttpClientRequest.post(`/embeddings`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateEmbedding200), + orElse: unexpectedStatus + })) + ), + "listEvals": (options) => + HttpClientRequest.get(`/evals`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "order_by": options?.params?.["order_by"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListEvals200), + orElse: unexpectedStatus + })) + ), + "createEval": (options) => + HttpClientRequest.post(`/evals`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateEval201), + orElse: unexpectedStatus + })) + ), + "getEval": (evalId, options) => + HttpClientRequest.get(`/evals/${evalId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetEval200), + orElse: unexpectedStatus + })) + ), + "updateEval": (evalId, options) => + HttpClientRequest.post(`/evals/${evalId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateEval200), + orElse: unexpectedStatus + })) + ), + "deleteEval": (evalId, options) => + HttpClientRequest.delete(`/evals/${evalId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteEval200), + "404": decodeError("DeleteEval404", DeleteEval404), + orElse: unexpectedStatus + })) + ), + "getEvalRuns": (evalId, options) => + HttpClientRequest.get(`/evals/${evalId}/runs`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "status": options?.params?.["status"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetEvalRuns200), + orElse: unexpectedStatus + })) + ), + "createEvalRun": (evalId, options) => + HttpClientRequest.post(`/evals/${evalId}/runs`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateEvalRun201), + "400": decodeError("CreateEvalRun400", CreateEvalRun400), + orElse: unexpectedStatus + })) + ), + "getEvalRun": (evalId, runId, options) => + HttpClientRequest.get(`/evals/${evalId}/runs/${runId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetEvalRun200), + orElse: unexpectedStatus + })) + ), + "cancelEvalRun": (evalId, runId, options) => + HttpClientRequest.post(`/evals/${evalId}/runs/${runId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CancelEvalRun200), + orElse: unexpectedStatus + })) + ), + "deleteEvalRun": (evalId, runId, options) => + HttpClientRequest.delete(`/evals/${evalId}/runs/${runId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteEvalRun200), + "404": decodeError("DeleteEvalRun404", DeleteEvalRun404), + orElse: unexpectedStatus + })) + ), + "getEvalRunOutputItems": (evalId, runId, options) => + HttpClientRequest.get(`/evals/${evalId}/runs/${runId}/output_items`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any, + "status": options?.params?.["status"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetEvalRunOutputItems200), + orElse: unexpectedStatus + })) + ), + "getEvalRunOutputItem": (evalId, runId, outputItemId, options) => + HttpClientRequest.get(`/evals/${evalId}/runs/${runId}/output_items/${outputItemId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetEvalRunOutputItem200), + orElse: unexpectedStatus + })) + ), + "listFiles": (options) => + HttpClientRequest.get(`/files`).pipe( + HttpClientRequest.setUrlParams({ + "purpose": options?.params?.["purpose"] as any, + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListFiles200), + orElse: unexpectedStatus + })) + ), + "createFile": (options) => + HttpClientRequest.post(`/files`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateFile200), + orElse: unexpectedStatus + })) + ), + "retrieveFile": (fileId, options) => + HttpClientRequest.get(`/files/${fileId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveFile200), + orElse: unexpectedStatus + })) + ), + "deleteFile": (fileId, options) => + HttpClientRequest.delete(`/files/${fileId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteFile200), + orElse: unexpectedStatus + })) + ), + "downloadFile": (fileId, options) => + HttpClientRequest.get(`/files/${fileId}/content`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DownloadFile200), + orElse: unexpectedStatus + })) + ), + "runGrader": (options) => + HttpClientRequest.post(`/fine_tuning/alpha/graders/run`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RunGrader200), + orElse: unexpectedStatus + })) + ), + "validateGrader": (options) => + HttpClientRequest.post(`/fine_tuning/alpha/graders/validate`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ValidateGrader200), + orElse: unexpectedStatus + })) + ), + "listFineTuningCheckpointPermissions": (fineTunedModelCheckpoint, options) => + HttpClientRequest.get(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`).pipe( + HttpClientRequest.setUrlParams({ + "project_id": options?.params?.["project_id"] as any, + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListFineTuningCheckpointPermissions200), + orElse: unexpectedStatus + })) + ), + "createFineTuningCheckpointPermission": (fineTunedModelCheckpoint, options) => + HttpClientRequest.post(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateFineTuningCheckpointPermission200), + orElse: unexpectedStatus + })) + ), + "deleteFineTuningCheckpointPermission": (fineTunedModelCheckpoint, permissionId, options) => + HttpClientRequest.delete(`/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions/${permissionId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteFineTuningCheckpointPermission200), + orElse: unexpectedStatus + })) + ), + "listPaginatedFineTuningJobs": (options) => + HttpClientRequest.get(`/fine_tuning/jobs`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any, + "metadata": options?.params?.["metadata"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListPaginatedFineTuningJobs200), + orElse: unexpectedStatus + })) + ), + "createFineTuningJob": (options) => + HttpClientRequest.post(`/fine_tuning/jobs`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateFineTuningJob200), + orElse: unexpectedStatus + })) + ), + "retrieveFineTuningJob": (fineTuningJobId, options) => + HttpClientRequest.get(`/fine_tuning/jobs/${fineTuningJobId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveFineTuningJob200), + orElse: unexpectedStatus + })) + ), + "cancelFineTuningJob": (fineTuningJobId, options) => + HttpClientRequest.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CancelFineTuningJob200), + orElse: unexpectedStatus + })) + ), + "listFineTuningJobCheckpoints": (fineTuningJobId, options) => + HttpClientRequest.get(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListFineTuningJobCheckpoints200), + orElse: unexpectedStatus + })) + ), + "listFineTuningEvents": (fineTuningJobId, options) => + HttpClientRequest.get(`/fine_tuning/jobs/${fineTuningJobId}/events`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "limit": options?.params?.["limit"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListFineTuningEvents200), + orElse: unexpectedStatus + })) + ), + "pauseFineTuningJob": (fineTuningJobId, options) => + HttpClientRequest.post(`/fine_tuning/jobs/${fineTuningJobId}/pause`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(PauseFineTuningJob200), + orElse: unexpectedStatus + })) + ), + "resumeFineTuningJob": (fineTuningJobId, options) => + HttpClientRequest.post(`/fine_tuning/jobs/${fineTuningJobId}/resume`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ResumeFineTuningJob200), + orElse: unexpectedStatus + })) + ), + "createImageEdit": (options) => + HttpClientRequest.post(`/images/edits`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateImageEdit200), + orElse: unexpectedStatus + })) + ), + "createImageEditSse": (options) => + HttpClientRequest.post(`/images/edits`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + sseRequest(CreateImageEdit200Sse) + ), + "createImage": (options) => + HttpClientRequest.post(`/images/generations`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateImage200), + orElse: unexpectedStatus + })) + ), + "createImageSse": (options) => + HttpClientRequest.post(`/images/generations`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + sseRequest(CreateImage200Sse) + ), + "createImageVariation": (options) => + HttpClientRequest.post(`/images/variations`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateImageVariation200), + orElse: unexpectedStatus + })) + ), + "listModels": (options) => + HttpClientRequest.get(`/models`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListModels200), + orElse: unexpectedStatus + })) + ), + "retrieveModel": (model, options) => + HttpClientRequest.get(`/models/${model}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveModel200), + orElse: unexpectedStatus + })) + ), + "deleteModel": (model, options) => + HttpClientRequest.delete(`/models/${model}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteModel200), + orElse: unexpectedStatus + })) + ), + "createModeration": (options) => + HttpClientRequest.post(`/moderations`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateModeration200), + orElse: unexpectedStatus + })) + ), + "adminApiKeysList": (options) => + HttpClientRequest.get(`/organization/admin_api_keys`).pipe( + HttpClientRequest.setUrlParams({ + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any, + "limit": options?.params?.["limit"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AdminApiKeysList200), + orElse: unexpectedStatus + })) + ), + "adminApiKeysCreate": (options) => + HttpClientRequest.post(`/organization/admin_api_keys`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AdminApiKeysCreate200), + orElse: unexpectedStatus + })) + ), + "adminApiKeysGet": (keyId, options) => + HttpClientRequest.get(`/organization/admin_api_keys/${keyId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AdminApiKeysGet200), + orElse: unexpectedStatus + })) + ), + "adminApiKeysDelete": (keyId, options) => + HttpClientRequest.delete(`/organization/admin_api_keys/${keyId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AdminApiKeysDelete200), + orElse: unexpectedStatus + })) + ), + "listAuditLogs": (options) => + HttpClientRequest.get(`/organization/audit_logs`).pipe( + HttpClientRequest.setUrlParams({ + "effective_at[gt]": options?.params?.["effective_at[gt]"] as any, + "effective_at[gte]": options?.params?.["effective_at[gte]"] as any, + "effective_at[lt]": options?.params?.["effective_at[lt]"] as any, + "effective_at[lte]": options?.params?.["effective_at[lte]"] as any, + "project_ids[]": options?.params?.["project_ids[]"] as any, + "event_types[]": options?.params?.["event_types[]"] as any, + "actor_ids[]": options?.params?.["actor_ids[]"] as any, + "actor_emails[]": options?.params?.["actor_emails[]"] as any, + "resource_ids[]": options?.params?.["resource_ids[]"] as any, + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListAuditLogs200), + orElse: unexpectedStatus + })) + ), + "listOrganizationCertificates": (options) => + HttpClientRequest.get(`/organization/certificates`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListOrganizationCertificates200), + orElse: unexpectedStatus + })) + ), + "uploadCertificate": (options) => + HttpClientRequest.post(`/organization/certificates`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UploadCertificate200), + orElse: unexpectedStatus + })) + ), + "activateOrganizationCertificates": (options) => + HttpClientRequest.post(`/organization/certificates/activate`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ActivateOrganizationCertificates200), + orElse: unexpectedStatus + })) + ), + "deactivateOrganizationCertificates": (options) => + HttpClientRequest.post(`/organization/certificates/deactivate`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeactivateOrganizationCertificates200), + orElse: unexpectedStatus + })) + ), + "getCertificate": (certificateId, options) => + HttpClientRequest.get(`/organization/certificates/${certificateId}`).pipe( + HttpClientRequest.setUrlParams({ "include": options?.params?.["include"] as any }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetCertificate200), + orElse: unexpectedStatus + })) + ), + "modifyCertificate": (certificateId, options) => + HttpClientRequest.post(`/organization/certificates/${certificateId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModifyCertificate200), + orElse: unexpectedStatus + })) + ), + "deleteCertificate": (certificateId, options) => + HttpClientRequest.delete(`/organization/certificates/${certificateId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteCertificate200), + orElse: unexpectedStatus + })) + ), + "usageCosts": (options) => + HttpClientRequest.get(`/organization/costs`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "api_key_ids": options.params["api_key_ids"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageCosts200), + orElse: unexpectedStatus + })) + ), + "listGroups": (options) => + HttpClientRequest.get(`/organization/groups`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListGroups200), + orElse: unexpectedStatus + })) + ), + "createGroup": (options) => + HttpClientRequest.post(`/organization/groups`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateGroup200), + orElse: unexpectedStatus + })) + ), + "updateGroup": (groupId, options) => + HttpClientRequest.post(`/organization/groups/${groupId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateGroup200), + orElse: unexpectedStatus + })) + ), + "deleteGroup": (groupId, options) => + HttpClientRequest.delete(`/organization/groups/${groupId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteGroup200), + orElse: unexpectedStatus + })) + ), + "listGroupRoleAssignments": (groupId, options) => + HttpClientRequest.get(`/organization/groups/${groupId}/roles`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListGroupRoleAssignments200), + orElse: unexpectedStatus + })) + ), + "assignGroupRole": (groupId, options) => + HttpClientRequest.post(`/organization/groups/${groupId}/roles`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AssignGroupRole200), + orElse: unexpectedStatus + })) + ), + "unassignGroupRole": (groupId, roleId, options) => + HttpClientRequest.delete(`/organization/groups/${groupId}/roles/${roleId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UnassignGroupRole200), + orElse: unexpectedStatus + })) + ), + "listGroupUsers": (groupId, options) => + HttpClientRequest.get(`/organization/groups/${groupId}/users`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListGroupUsers200), + orElse: unexpectedStatus + })) + ), + "addGroupUser": (groupId, options) => + HttpClientRequest.post(`/organization/groups/${groupId}/users`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AddGroupUser200), + orElse: unexpectedStatus + })) + ), + "removeGroupUser": (groupId, userId, options) => + HttpClientRequest.delete(`/organization/groups/${groupId}/users/${userId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RemoveGroupUser200), + orElse: unexpectedStatus + })) + ), + "listInvites": (options) => + HttpClientRequest.get(`/organization/invites`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListInvites200), + orElse: unexpectedStatus + })) + ), + "inviteUser": (options) => + HttpClientRequest.post(`/organization/invites`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(InviteUser200), + orElse: unexpectedStatus + })) + ), + "retrieveInvite": (inviteId, options) => + HttpClientRequest.get(`/organization/invites/${inviteId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveInvite200), + orElse: unexpectedStatus + })) + ), + "deleteInvite": (inviteId, options) => + HttpClientRequest.delete(`/organization/invites/${inviteId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteInvite200), + orElse: unexpectedStatus + })) + ), + "listProjects": (options) => + HttpClientRequest.get(`/organization/projects`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "include_archived": options?.params?.["include_archived"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjects200), + orElse: unexpectedStatus + })) + ), + "createProject": (options) => + HttpClientRequest.post(`/organization/projects`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateProject200), + orElse: unexpectedStatus + })) + ), + "retrieveProject": (projectId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveProject200), + orElse: unexpectedStatus + })) + ), + "modifyProject": (projectId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModifyProject200), + "400": decodeError("ModifyProject400", ModifyProject400), + orElse: unexpectedStatus + })) + ), + "listProjectApiKeys": (projectId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/api_keys`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjectApiKeys200), + orElse: unexpectedStatus + })) + ), + "retrieveProjectApiKey": (projectId, apiKeyId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/api_keys/${apiKeyId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveProjectApiKey200), + orElse: unexpectedStatus + })) + ), + "deleteProjectApiKey": (projectId, apiKeyId, options) => + HttpClientRequest.delete(`/organization/projects/${projectId}/api_keys/${apiKeyId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteProjectApiKey200), + "400": decodeError("DeleteProjectApiKey400", DeleteProjectApiKey400), + orElse: unexpectedStatus + })) + ), + "archiveProject": (projectId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/archive`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ArchiveProject200), + orElse: unexpectedStatus + })) + ), + "listProjectCertificates": (projectId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/certificates`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjectCertificates200), + orElse: unexpectedStatus + })) + ), + "activateProjectCertificates": (projectId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/certificates/activate`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ActivateProjectCertificates200), + orElse: unexpectedStatus + })) + ), + "deactivateProjectCertificates": (projectId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/certificates/deactivate`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeactivateProjectCertificates200), + orElse: unexpectedStatus + })) + ), + "listProjectGroups": (projectId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/groups`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjectGroups200), + orElse: unexpectedStatus + })) + ), + "addProjectGroup": (projectId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/groups`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AddProjectGroup200), + orElse: unexpectedStatus + })) + ), + "removeProjectGroup": (projectId, groupId, options) => + HttpClientRequest.delete(`/organization/projects/${projectId}/groups/${groupId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RemoveProjectGroup200), + orElse: unexpectedStatus + })) + ), + "retrieveProjectHostedToolPermissions": (projectId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/hosted_tool_permissions`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveProjectHostedToolPermissions200), + orElse: unexpectedStatus + })) + ), + "updateProjectHostedToolPermissions": (projectId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/hosted_tool_permissions`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateProjectHostedToolPermissions200), + orElse: unexpectedStatus + })) + ), + "retrieveProjectModelPermissions": (projectId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/model_permissions`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveProjectModelPermissions200), + orElse: unexpectedStatus + })) + ), + "updateProjectModelPermissions": (projectId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/model_permissions`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateProjectModelPermissions200), + orElse: unexpectedStatus + })) + ), + "deleteProjectModelPermissions": (projectId, options) => + HttpClientRequest.delete(`/organization/projects/${projectId}/model_permissions`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteProjectModelPermissions200), + orElse: unexpectedStatus + })) + ), + "listProjectRateLimits": (projectId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/rate_limits`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjectRateLimits200), + orElse: unexpectedStatus + })) + ), + "updateProjectRateLimits": (projectId, rateLimitId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/rate_limits/${rateLimitId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateProjectRateLimits200), + "400": decodeError("UpdateProjectRateLimits400", UpdateProjectRateLimits400), + orElse: unexpectedStatus + })) + ), + "listProjectServiceAccounts": (projectId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/service_accounts`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjectServiceAccounts200), + "400": decodeError("ListProjectServiceAccounts400", ListProjectServiceAccounts400), + orElse: unexpectedStatus + })) + ), + "createProjectServiceAccount": (projectId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/service_accounts`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateProjectServiceAccount200), + "400": decodeError("CreateProjectServiceAccount400", CreateProjectServiceAccount400), + orElse: unexpectedStatus + })) + ), + "retrieveProjectServiceAccount": (projectId, serviceAccountId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/service_accounts/${serviceAccountId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveProjectServiceAccount200), + orElse: unexpectedStatus + })) + ), + "deleteProjectServiceAccount": (projectId, serviceAccountId, options) => + HttpClientRequest.delete(`/organization/projects/${projectId}/service_accounts/${serviceAccountId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteProjectServiceAccount200), + orElse: unexpectedStatus + })) + ), + "listProjectUsers": (projectId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/users`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjectUsers200), + "400": decodeError("ListProjectUsers400", ListProjectUsers400), + orElse: unexpectedStatus + })) + ), + "createProjectUser": (projectId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/users`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateProjectUser200), + "400": decodeError("CreateProjectUser400", CreateProjectUser400), + orElse: unexpectedStatus + })) + ), + "retrieveProjectUser": (projectId, userId, options) => + HttpClientRequest.get(`/organization/projects/${projectId}/users/${userId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveProjectUser200), + orElse: unexpectedStatus + })) + ), + "modifyProjectUser": (projectId, userId, options) => + HttpClientRequest.post(`/organization/projects/${projectId}/users/${userId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModifyProjectUser200), + "400": decodeError("ModifyProjectUser400", ModifyProjectUser400), + orElse: unexpectedStatus + })) + ), + "deleteProjectUser": (projectId, userId, options) => + HttpClientRequest.delete(`/organization/projects/${projectId}/users/${userId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteProjectUser200), + "400": decodeError("DeleteProjectUser400", DeleteProjectUser400), + orElse: unexpectedStatus + })) + ), + "listRoles": (options) => + HttpClientRequest.get(`/organization/roles`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListRoles200), + orElse: unexpectedStatus + })) + ), + "createRole": (options) => + HttpClientRequest.post(`/organization/roles`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateRole200), + orElse: unexpectedStatus + })) + ), + "updateRole": (roleId, options) => + HttpClientRequest.post(`/organization/roles/${roleId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateRole200), + orElse: unexpectedStatus + })) + ), + "deleteRole": (roleId, options) => + HttpClientRequest.delete(`/organization/roles/${roleId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteRole200), + orElse: unexpectedStatus + })) + ), + "usageAudioSpeeches": (options) => + HttpClientRequest.get(`/organization/usage/audio_speeches`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "user_ids": options.params["user_ids"] as any, + "api_key_ids": options.params["api_key_ids"] as any, + "models": options.params["models"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageAudioSpeeches200), + orElse: unexpectedStatus + })) + ), + "usageAudioTranscriptions": (options) => + HttpClientRequest.get(`/organization/usage/audio_transcriptions`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "user_ids": options.params["user_ids"] as any, + "api_key_ids": options.params["api_key_ids"] as any, + "models": options.params["models"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageAudioTranscriptions200), + orElse: unexpectedStatus + })) + ), + "usageCodeInterpreterSessions": (options) => + HttpClientRequest.get(`/organization/usage/code_interpreter_sessions`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageCodeInterpreterSessions200), + orElse: unexpectedStatus + })) + ), + "usageCompletions": (options) => + HttpClientRequest.get(`/organization/usage/completions`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "user_ids": options.params["user_ids"] as any, + "api_key_ids": options.params["api_key_ids"] as any, + "models": options.params["models"] as any, + "batch": options.params["batch"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageCompletions200), + orElse: unexpectedStatus + })) + ), + "usageEmbeddings": (options) => + HttpClientRequest.get(`/organization/usage/embeddings`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "user_ids": options.params["user_ids"] as any, + "api_key_ids": options.params["api_key_ids"] as any, + "models": options.params["models"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageEmbeddings200), + orElse: unexpectedStatus + })) + ), + "usageFileSearchCalls": (options) => + HttpClientRequest.get(`/organization/usage/file_search_calls`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "user_ids": options.params["user_ids"] as any, + "api_key_ids": options.params["api_key_ids"] as any, + "vector_store_ids": options.params["vector_store_ids"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageFileSearchCalls200), + orElse: unexpectedStatus + })) + ), + "usageImages": (options) => + HttpClientRequest.get(`/organization/usage/images`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "sources": options.params["sources"] as any, + "sizes": options.params["sizes"] as any, + "project_ids": options.params["project_ids"] as any, + "user_ids": options.params["user_ids"] as any, + "api_key_ids": options.params["api_key_ids"] as any, + "models": options.params["models"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageImages200), + orElse: unexpectedStatus + })) + ), + "usageModerations": (options) => + HttpClientRequest.get(`/organization/usage/moderations`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "user_ids": options.params["user_ids"] as any, + "api_key_ids": options.params["api_key_ids"] as any, + "models": options.params["models"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageModerations200), + orElse: unexpectedStatus + })) + ), + "usageVectorStores": (options) => + HttpClientRequest.get(`/organization/usage/vector_stores`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageVectorStores200), + orElse: unexpectedStatus + })) + ), + "usageWebSearchCalls": (options) => + HttpClientRequest.get(`/organization/usage/web_search_calls`).pipe( + HttpClientRequest.setUrlParams({ + "start_time": options.params["start_time"] as any, + "end_time": options.params["end_time"] as any, + "bucket_width": options.params["bucket_width"] as any, + "project_ids": options.params["project_ids"] as any, + "user_ids": options.params["user_ids"] as any, + "api_key_ids": options.params["api_key_ids"] as any, + "models": options.params["models"] as any, + "context_levels": options.params["context_levels"] as any, + "group_by": options.params["group_by"] as any, + "limit": options.params["limit"] as any, + "page": options.params["page"] as any + }), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UsageWebSearchCalls200), + orElse: unexpectedStatus + })) + ), + "listUsers": (options) => + HttpClientRequest.get(`/organization/users`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "emails": options?.params?.["emails"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListUsers200), + orElse: unexpectedStatus + })) + ), + "retrieveUser": (userId, options) => + HttpClientRequest.get(`/organization/users/${userId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveUser200), + orElse: unexpectedStatus + })) + ), + "modifyUser": (userId, options) => + HttpClientRequest.post(`/organization/users/${userId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModifyUser200), + orElse: unexpectedStatus + })) + ), + "deleteUser": (userId, options) => + HttpClientRequest.delete(`/organization/users/${userId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteUser200), + orElse: unexpectedStatus + })) + ), + "listUserRoleAssignments": (userId, options) => + HttpClientRequest.get(`/organization/users/${userId}/roles`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListUserRoleAssignments200), + orElse: unexpectedStatus + })) + ), + "assignUserRole": (userId, options) => + HttpClientRequest.post(`/organization/users/${userId}/roles`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AssignUserRole200), + orElse: unexpectedStatus + })) + ), + "unassignUserRole": (userId, roleId, options) => + HttpClientRequest.delete(`/organization/users/${userId}/roles/${roleId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UnassignUserRole200), + orElse: unexpectedStatus + })) + ), + "listProjectGroupRoleAssignments": (projectId, groupId, options) => + HttpClientRequest.get(`/projects/${projectId}/groups/${groupId}/roles`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjectGroupRoleAssignments200), + orElse: unexpectedStatus + })) + ), + "assignProjectGroupRole": (projectId, groupId, options) => + HttpClientRequest.post(`/projects/${projectId}/groups/${groupId}/roles`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AssignProjectGroupRole200), + orElse: unexpectedStatus + })) + ), + "unassignProjectGroupRole": (projectId, groupId, roleId, options) => + HttpClientRequest.delete(`/projects/${projectId}/groups/${groupId}/roles/${roleId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UnassignProjectGroupRole200), + orElse: unexpectedStatus + })) + ), + "listProjectRoles": (projectId, options) => + HttpClientRequest.get(`/projects/${projectId}/roles`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjectRoles200), + orElse: unexpectedStatus + })) + ), + "createProjectRole": (projectId, options) => + HttpClientRequest.post(`/projects/${projectId}/roles`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateProjectRole200), + orElse: unexpectedStatus + })) + ), + "updateProjectRole": (projectId, roleId, options) => + HttpClientRequest.post(`/projects/${projectId}/roles/${roleId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateProjectRole200), + orElse: unexpectedStatus + })) + ), + "deleteProjectRole": (projectId, roleId, options) => + HttpClientRequest.delete(`/projects/${projectId}/roles/${roleId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteProjectRole200), + orElse: unexpectedStatus + })) + ), + "listProjectUserRoleAssignments": (projectId, userId, options) => + HttpClientRequest.get(`/projects/${projectId}/users/${userId}/roles`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "after": options?.params?.["after"] as any, + "order": options?.params?.["order"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListProjectUserRoleAssignments200), + orElse: unexpectedStatus + })) + ), + "assignProjectUserRole": (projectId, userId, options) => + HttpClientRequest.post(`/projects/${projectId}/users/${userId}/roles`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AssignProjectUserRole200), + orElse: unexpectedStatus + })) + ), + "unassignProjectUserRole": (projectId, userId, roleId, options) => + HttpClientRequest.delete(`/projects/${projectId}/users/${userId}/roles/${roleId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UnassignProjectUserRole200), + orElse: unexpectedStatus + })) + ), + "createRealtimeCall": (options) => + HttpClientRequest.post(`/realtime/calls`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + orElse: unexpectedStatus + })) + ), + "acceptRealtimeCall": (callId, options) => + HttpClientRequest.post(`/realtime/calls/${callId}/accept`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "200": () => Effect.void, + orElse: unexpectedStatus + })) + ), + "hangupRealtimeCall": (callId, options) => + HttpClientRequest.post(`/realtime/calls/${callId}/hangup`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "200": () => Effect.void, + orElse: unexpectedStatus + })) + ), + "referRealtimeCall": (callId, options) => + HttpClientRequest.post(`/realtime/calls/${callId}/refer`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "200": () => Effect.void, + orElse: unexpectedStatus + })) + ), + "rejectRealtimeCall": (callId, options) => + HttpClientRequest.post(`/realtime/calls/${callId}/reject`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "200": () => Effect.void, + orElse: unexpectedStatus + })) + ), + "createRealtimeClientSecret": (options) => + HttpClientRequest.post(`/realtime/client_secrets`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateRealtimeClientSecret200), + orElse: unexpectedStatus + })) + ), + "createRealtimeSession": (options) => + HttpClientRequest.post(`/realtime/sessions`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateRealtimeSession200), + orElse: unexpectedStatus + })) + ), + "createRealtimeTranscriptionSession": (options) => + HttpClientRequest.post(`/realtime/transcription_sessions`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateRealtimeTranscriptionSession200), + orElse: unexpectedStatus + })) + ), + "createRealtimeTranslationClientSecret": (options) => + HttpClientRequest.post(`/realtime/translations/client_secrets`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateRealtimeTranslationClientSecret200), + orElse: unexpectedStatus + })) + ), + "createResponse": (options) => + HttpClientRequest.post(`/responses`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateResponse200), + orElse: unexpectedStatus + })) + ), + "createResponseSse": (options) => + HttpClientRequest.post(`/responses`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + sseRequest(CreateResponse200Sse) + ), + "getResponse": (responseId, options) => + HttpClientRequest.get(`/responses/${responseId}`).pipe( + HttpClientRequest.setUrlParams({ + "include": options?.params?.["include"] as any, + "stream": options?.params?.["stream"] as any, + "starting_after": options?.params?.["starting_after"] as any, + "include_obfuscation": options?.params?.["include_obfuscation"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetResponse200), + orElse: unexpectedStatus + })) + ), + "deleteResponse": (responseId, options) => + HttpClientRequest.delete(`/responses/${responseId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "404": decodeError("DeleteResponse404", DeleteResponse404), + "200": () => Effect.void, + orElse: unexpectedStatus + })) + ), + "cancelResponse": (responseId, options) => + HttpClientRequest.post(`/responses/${responseId}/cancel`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CancelResponse200), + "404": decodeError("CancelResponse404", CancelResponse404), + orElse: unexpectedStatus + })) + ), + "listInputItems": (responseId, options) => + HttpClientRequest.get(`/responses/${responseId}/input_items`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "include": options?.params?.["include"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListInputItems200), + orElse: unexpectedStatus + })) + ), + "createThread": (options) => + HttpClientRequest.post(`/threads`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateThread200), + orElse: unexpectedStatus + })) + ), + "createThreadAndRun": (options) => + HttpClientRequest.post(`/threads/runs`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateThreadAndRun200), + orElse: unexpectedStatus + })) + ), + "getThread": (threadId, options) => + HttpClientRequest.get(`/threads/${threadId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetThread200), + orElse: unexpectedStatus + })) + ), + "modifyThread": (threadId, options) => + HttpClientRequest.post(`/threads/${threadId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModifyThread200), + orElse: unexpectedStatus + })) + ), + "deleteThread": (threadId, options) => + HttpClientRequest.delete(`/threads/${threadId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteThread200), + orElse: unexpectedStatus + })) + ), + "listMessages": (threadId, options) => + HttpClientRequest.get(`/threads/${threadId}/messages`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any, + "run_id": options?.params?.["run_id"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListMessages200), + orElse: unexpectedStatus + })) + ), + "createMessage": (threadId, options) => + HttpClientRequest.post(`/threads/${threadId}/messages`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateMessage200), + orElse: unexpectedStatus + })) + ), + "getMessage": (threadId, messageId, options) => + HttpClientRequest.get(`/threads/${threadId}/messages/${messageId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetMessage200), + orElse: unexpectedStatus + })) + ), + "modifyMessage": (threadId, messageId, options) => + HttpClientRequest.post(`/threads/${threadId}/messages/${messageId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModifyMessage200), + orElse: unexpectedStatus + })) + ), + "deleteMessage": (threadId, messageId, options) => + HttpClientRequest.delete(`/threads/${threadId}/messages/${messageId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteMessage200), + orElse: unexpectedStatus + })) + ), + "listRuns": (threadId, options) => + HttpClientRequest.get(`/threads/${threadId}/runs`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListRuns200), + orElse: unexpectedStatus + })) + ), + "createRun": (threadId, options) => + HttpClientRequest.post(`/threads/${threadId}/runs`).pipe( + HttpClientRequest.setUrlParams({ "include[]": options.params?.["include[]"] as any }), + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateRun200), + orElse: unexpectedStatus + })) + ), + "getRun": (threadId, runId, options) => + HttpClientRequest.get(`/threads/${threadId}/runs/${runId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetRun200), + orElse: unexpectedStatus + })) + ), + "modifyRun": (threadId, runId, options) => + HttpClientRequest.post(`/threads/${threadId}/runs/${runId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModifyRun200), + orElse: unexpectedStatus + })) + ), + "cancelRun": (threadId, runId, options) => + HttpClientRequest.post(`/threads/${threadId}/runs/${runId}/cancel`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CancelRun200), + orElse: unexpectedStatus + })) + ), + "listRunSteps": (threadId, runId, options) => + HttpClientRequest.get(`/threads/${threadId}/runs/${runId}/steps`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any, + "include[]": options?.params?.["include[]"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListRunSteps200), + orElse: unexpectedStatus + })) + ), + "getRunStep": (threadId, runId, stepId, options) => + HttpClientRequest.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`).pipe( + HttpClientRequest.setUrlParams({ "include[]": options?.params?.["include[]"] as any }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetRunStep200), + orElse: unexpectedStatus + })) + ), + "submitToolOuputsToRun": (threadId, runId, options) => + HttpClientRequest.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(SubmitToolOuputsToRun200), + orElse: unexpectedStatus + })) + ), + "createUpload": (options) => + HttpClientRequest.post(`/uploads`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateUpload200), + orElse: unexpectedStatus + })) + ), + "cancelUpload": (uploadId, options) => + HttpClientRequest.post(`/uploads/${uploadId}/cancel`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CancelUpload200), + orElse: unexpectedStatus + })) + ), + "completeUpload": (uploadId, options) => + HttpClientRequest.post(`/uploads/${uploadId}/complete`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CompleteUpload200), + orElse: unexpectedStatus + })) + ), + "addUploadPart": (uploadId, options) => + HttpClientRequest.post(`/uploads/${uploadId}/parts`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(AddUploadPart200), + orElse: unexpectedStatus + })) + ), + "listVectorStores": (options) => + HttpClientRequest.get(`/vector_stores`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListVectorStores200), + orElse: unexpectedStatus + })) + ), + "createVectorStore": (options) => + HttpClientRequest.post(`/vector_stores`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVectorStore200), + orElse: unexpectedStatus + })) + ), + "getVectorStore": (vectorStoreId, options) => + HttpClientRequest.get(`/vector_stores/${vectorStoreId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetVectorStore200), + orElse: unexpectedStatus + })) + ), + "modifyVectorStore": (vectorStoreId, options) => + HttpClientRequest.post(`/vector_stores/${vectorStoreId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ModifyVectorStore200), + orElse: unexpectedStatus + })) + ), + "deleteVectorStore": (vectorStoreId, options) => + HttpClientRequest.delete(`/vector_stores/${vectorStoreId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteVectorStore200), + orElse: unexpectedStatus + })) + ), + "createVectorStoreFileBatch": (vectorStoreId, options) => + HttpClientRequest.post(`/vector_stores/${vectorStoreId}/file_batches`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVectorStoreFileBatch200), + orElse: unexpectedStatus + })) + ), + "getVectorStoreFileBatch": (vectorStoreId, batchId, options) => + HttpClientRequest.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetVectorStoreFileBatch200), + orElse: unexpectedStatus + })) + ), + "cancelVectorStoreFileBatch": (vectorStoreId, batchId, options) => + HttpClientRequest.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CancelVectorStoreFileBatch200), + orElse: unexpectedStatus + })) + ), + "listFilesInVectorStoreBatch": (vectorStoreId, batchId, options) => + HttpClientRequest.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any, + "filter": options?.params?.["filter"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListFilesInVectorStoreBatch200), + orElse: unexpectedStatus + })) + ), + "listVectorStoreFiles": (vectorStoreId, options) => + HttpClientRequest.get(`/vector_stores/${vectorStoreId}/files`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any, + "filter": options?.params?.["filter"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListVectorStoreFiles200), + orElse: unexpectedStatus + })) + ), + "createVectorStoreFile": (vectorStoreId, options) => + HttpClientRequest.post(`/vector_stores/${vectorStoreId}/files`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVectorStoreFile200), + orElse: unexpectedStatus + })) + ), + "getVectorStoreFile": (vectorStoreId, fileId, options) => + HttpClientRequest.get(`/vector_stores/${vectorStoreId}/files/${fileId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetVectorStoreFile200), + orElse: unexpectedStatus + })) + ), + "updateVectorStoreFileAttributes": (vectorStoreId, fileId, options) => + HttpClientRequest.post(`/vector_stores/${vectorStoreId}/files/${fileId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateVectorStoreFileAttributes200), + orElse: unexpectedStatus + })) + ), + "deleteVectorStoreFile": (vectorStoreId, fileId, options) => + HttpClientRequest.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteVectorStoreFile200), + orElse: unexpectedStatus + })) + ), + "retrieveVectorStoreFileContent": (vectorStoreId, fileId, options) => + HttpClientRequest.get(`/vector_stores/${vectorStoreId}/files/${fileId}/content`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveVectorStoreFileContent200), + orElse: unexpectedStatus + })) + ), + "searchVectorStore": (vectorStoreId, options) => + HttpClientRequest.post(`/vector_stores/${vectorStoreId}/search`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(SearchVectorStore200), + orElse: unexpectedStatus + })) + ), + "createConversation": (options) => + HttpClientRequest.post(`/conversations`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateConversation200), + orElse: unexpectedStatus + })) + ), + "getConversation": (conversationId, options) => + HttpClientRequest.get(`/conversations/${conversationId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetConversation200), + orElse: unexpectedStatus + })) + ), + "updateConversation": (conversationId, options) => + HttpClientRequest.post(`/conversations/${conversationId}`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateConversation200), + orElse: unexpectedStatus + })) + ), + "deleteConversation": (conversationId, options) => + HttpClientRequest.delete(`/conversations/${conversationId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteConversation200), + orElse: unexpectedStatus + })) + ), + "ListVideos": (options) => + HttpClientRequest.get(`/videos`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListVideos200), + orElse: unexpectedStatus + })) + ), + "createVideo": (options) => + HttpClientRequest.post(`/videos`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVideo200), + orElse: unexpectedStatus + })) + ), + "CreateVideoCharacter": (options) => + HttpClientRequest.post(`/videos/characters`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVideoCharacter200), + orElse: unexpectedStatus + })) + ), + "GetVideoCharacter": (characterId, options) => + HttpClientRequest.get(`/videos/characters/${characterId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetVideoCharacter200), + orElse: unexpectedStatus + })) + ), + "CreateVideoEdit": (options) => + HttpClientRequest.post(`/videos/edits`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVideoEdit200), + orElse: unexpectedStatus + })) + ), + "CreateVideoExtend": (options) => + HttpClientRequest.post(`/videos/extensions`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVideoExtend200), + orElse: unexpectedStatus + })) + ), + "GetVideo": (videoId, options) => + HttpClientRequest.get(`/videos/${videoId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetVideo200), + orElse: unexpectedStatus + })) + ), + "DeleteVideo": (videoId, options) => + HttpClientRequest.delete(`/videos/${videoId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteVideo200), + orElse: unexpectedStatus + })) + ), + "RetrieveVideoContent": (videoId, options) => + HttpClientRequest.get(`/videos/${videoId}/content`).pipe( + HttpClientRequest.setUrlParams({ "variant": options?.params?.["variant"] as any }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(RetrieveVideoContent200), + orElse: unexpectedStatus + })) + ), + "CreateVideoRemix": (videoId, options) => + HttpClientRequest.post(`/videos/${videoId}/remix`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateVideoRemix200), + orElse: unexpectedStatus + })) + ), + "Getinputtokencounts": (options) => + HttpClientRequest.post(`/responses/input_tokens`).pipe( + HttpClientRequest.bodyUrlParams(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(Getinputtokencounts200), + orElse: unexpectedStatus + })) + ), + "Compactconversation": (options) => + HttpClientRequest.post(`/responses/compact`).pipe( + HttpClientRequest.bodyUrlParams(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(Compactconversation200), + orElse: unexpectedStatus + })) + ), + "ListSkills": (options) => + HttpClientRequest.get(`/skills`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListSkills200), + orElse: unexpectedStatus + })) + ), + "CreateSkill": (options) => + HttpClientRequest.post(`/skills`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateSkill200), + orElse: unexpectedStatus + })) + ), + "GetSkill": (skillId, options) => + HttpClientRequest.get(`/skills/${skillId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetSkill200), + orElse: unexpectedStatus + })) + ), + "UpdateSkillDefaultVersion": (skillId, options) => + HttpClientRequest.post(`/skills/${skillId}`).pipe( + HttpClientRequest.bodyUrlParams(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(UpdateSkillDefaultVersion200), + orElse: unexpectedStatus + })) + ), + "DeleteSkill": (skillId, options) => + HttpClientRequest.delete(`/skills/${skillId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteSkill200), + orElse: unexpectedStatus + })) + ), + "GetSkillContent": (skillId, options) => + HttpClientRequest.get(`/skills/${skillId}/content`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetSkillContent200), + orElse: unexpectedStatus + })) + ), + "ListSkillVersions": (skillId, options) => + HttpClientRequest.get(`/skills/${skillId}/versions`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListSkillVersions200), + orElse: unexpectedStatus + })) + ), + "CreateSkillVersion": (skillId, options) => + HttpClientRequest.post(`/skills/${skillId}/versions`).pipe( + HttpClientRequest.bodyFormData(options.payload as any), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateSkillVersion200), + orElse: unexpectedStatus + })) + ), + "GetSkillVersion": (skillId, version, options) => + HttpClientRequest.get(`/skills/${skillId}/versions/${version}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetSkillVersion200), + orElse: unexpectedStatus + })) + ), + "DeleteSkillVersion": (skillId, version, options) => + HttpClientRequest.delete(`/skills/${skillId}/versions/${version}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteSkillVersion200), + orElse: unexpectedStatus + })) + ), + "GetSkillVersionContent": (skillId, version, options) => + HttpClientRequest.get(`/skills/${skillId}/versions/${version}/content`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetSkillVersionContent200), + orElse: unexpectedStatus + })) + ), + "CancelChatSessionMethod": (sessionId, options) => + HttpClientRequest.post(`/chatkit/sessions/${sessionId}/cancel`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CancelChatSessionMethod200), + orElse: unexpectedStatus + })) + ), + "CreateChatSessionMethod": (options) => + HttpClientRequest.post(`/chatkit/sessions`).pipe( + HttpClientRequest.bodyJsonUnsafe(options.payload), + withResponse(options.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(CreateChatSessionMethod200), + orElse: unexpectedStatus + })) + ), + "ListThreadItemsMethod": (threadId, options) => + HttpClientRequest.get(`/chatkit/threads/${threadId}/items`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListThreadItemsMethod200), + orElse: unexpectedStatus + })) + ), + "GetThreadMethod": (threadId, options) => + HttpClientRequest.get(`/chatkit/threads/${threadId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(GetThreadMethod200), + orElse: unexpectedStatus + })) + ), + "DeleteThreadMethod": (threadId, options) => + HttpClientRequest.delete(`/chatkit/threads/${threadId}`).pipe( + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(DeleteThreadMethod200), + orElse: unexpectedStatus + })) + ), + "ListThreadsMethod": (options) => + HttpClientRequest.get(`/chatkit/threads`).pipe( + HttpClientRequest.setUrlParams({ + "limit": options?.params?.["limit"] as any, + "order": options?.params?.["order"] as any, + "after": options?.params?.["after"] as any, + "before": options?.params?.["before"] as any, + "user": options?.params?.["user"] as any + }), + withResponse(options?.config)(HttpClientResponse.matchStatus({ + "2xx": decodeSuccess(ListThreadsMethod200), + orElse: unexpectedStatus + })) + ) + } +} + +export interface OpenAiClient { + readonly httpClient: HttpClient.HttpClient + /** + * Returns a list of assistants. + */ + readonly "listAssistants": ( + options: + | { readonly params?: typeof ListAssistantsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create an assistant with a model and instructions. + */ + readonly "createAssistant": ( + options: { readonly payload: typeof CreateAssistantRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves an assistant. + */ + readonly "getAssistant": ( + assistantId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Modifies an assistant. + */ + readonly "modifyAssistant": ( + assistantId: string, + options: { readonly payload: typeof ModifyAssistantRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete an assistant. + */ + readonly "deleteAssistant": ( + assistantId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Generates audio from the input text. + * + * Returns the audio file content, or a stream of audio events. + */ + readonly "createSpeech": ( + options: { readonly payload: typeof CreateSpeechRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Generates audio from the input text. + * + * Returns the audio file content, or a stream of audio events. + */ + readonly "createSpeechSse": ( + options: { readonly payload: typeof CreateSpeechRequestJson.Encoded } + ) => Stream.Stream< + { readonly event: string; readonly id: string | undefined; readonly data: typeof CreateSpeech200Sse.Type }, + HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, + typeof CreateSpeech200Sse.DecodingServices + > + /** + * Generates audio from the input text. + * + * Returns the audio file content, or a stream of audio events. + */ + readonly "createSpeechStream": ( + options: { readonly payload: typeof CreateSpeechRequestJson.Encoded } + ) => Stream.Stream + /** + * Transcribes audio into the input language. + * + * Returns a transcription object in `json`, `diarized_json`, or `verbose_json` + * format, or a stream of transcript events. + */ + readonly "createTranscription": ( + options: { + readonly payload: typeof CreateTranscriptionRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Transcribes audio into the input language. + * + * Returns a transcription object in `json`, `diarized_json`, or `verbose_json` + * format, or a stream of transcript events. + */ + readonly "createTranscriptionSse": ( + options: { readonly payload: typeof CreateTranscriptionRequestFormData.Encoded } + ) => Stream.Stream< + { readonly event: string; readonly id: string | undefined; readonly data: typeof CreateTranscription200Sse.Type }, + HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, + typeof CreateTranscription200Sse.DecodingServices + > + /** + * Translates audio into English. + */ + readonly "createTranslation": ( + options: { readonly payload: typeof CreateTranslationRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List consent recordings available to your organization for creating custom voices. + * + * See the [custom voices guide](/docs/guides/text-to-speech#custom-voices). Custom voices are limited to eligible customers. + */ + readonly "listVoiceConsents": ( + options: { + readonly params?: typeof ListVoiceConsentsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Upload a consent recording that authorizes creation of a custom voice. + * + * See the [custom voices guide](/docs/guides/text-to-speech#custom-voices) for requirements and best practices. Custom voices are limited to eligible customers. + */ + readonly "createVoiceConsent": ( + options: { + readonly payload: typeof CreateVoiceConsentRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieve consent recording metadata used for creating custom voices. + * + * See the [custom voices guide](/docs/guides/text-to-speech#custom-voices). Custom voices are limited to eligible customers. + */ + readonly "getVoiceConsent": ( + consentId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Update consent recording metadata used for creating custom voices. This endpoint updates metadata only and does not replace the underlying audio. + * + * See the [custom voices guide](/docs/guides/text-to-speech#custom-voices). Custom voices are limited to eligible customers. + */ + readonly "updateVoiceConsent": ( + consentId: string, + options: { readonly payload: typeof UpdateVoiceConsentRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a consent recording that was uploaded for creating custom voices. + * + * See the [custom voices guide](/docs/guides/text-to-speech#custom-voices). Custom voices are limited to eligible customers. + */ + readonly "deleteVoiceConsent": ( + consentId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a custom voice you can use for audio output (for example, in Text-to-Speech and the Realtime API). This requires an audio sample and a previously uploaded consent recording. + * + * See the [custom voices guide](/docs/guides/text-to-speech#custom-voices) for requirements and best practices. Custom voices are limited to eligible customers. + */ + readonly "createVoice": ( + options: { readonly payload: typeof CreateVoiceRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List your organization's batches. + */ + readonly "listBatches": ( + options: + | { readonly params?: typeof ListBatchesParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates and executes a batch from an uploaded file of requests + */ + readonly "createBatch": ( + options: { readonly payload: typeof CreateBatchRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a batch. + */ + readonly "retrieveBatch": ( + batchId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to 10 minutes, before changing to `cancelled`, where it will have partial results (if any) available in the output file. + */ + readonly "cancelBatch": ( + batchId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List stored Chat Completions. Only Chat Completions that have been stored + * with the `store` parameter set to `true` will be returned. + */ + readonly "listChatCompletions": ( + options: { + readonly params?: typeof ListChatCompletionsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * **Starting a new project?** We recommend trying [Responses](/docs/api-reference/responses) + * to take advantage of the latest OpenAI platform features. Compare + * [Chat Completions with Responses](/docs/guides/responses-vs-chat-completions?api-mode=responses). + * + * --- + * + * Creates a model response for the given chat conversation. Learn more in the + * [text generation](/docs/guides/text-generation), [vision](/docs/guides/vision), + * and [audio](/docs/guides/audio) guides. + * + * Parameter support can differ depending on the model used to generate the + * response, particularly for newer reasoning models. Parameters that are only + * supported for reasoning models are noted below. For the current state of + * unsupported parameters in reasoning models, + * [refer to the reasoning guide](/docs/guides/reasoning). + * + * Returns a chat completion object, or a streamed sequence of chat completion + * chunk objects if the request is streamed. + */ + readonly "createChatCompletion": ( + options: { readonly payload: typeof CreateChatCompletionRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * **Starting a new project?** We recommend trying [Responses](/docs/api-reference/responses) + * to take advantage of the latest OpenAI platform features. Compare + * [Chat Completions with Responses](/docs/guides/responses-vs-chat-completions?api-mode=responses). + * + * --- + * + * Creates a model response for the given chat conversation. Learn more in the + * [text generation](/docs/guides/text-generation), [vision](/docs/guides/vision), + * and [audio](/docs/guides/audio) guides. + * + * Parameter support can differ depending on the model used to generate the + * response, particularly for newer reasoning models. Parameters that are only + * supported for reasoning models are noted below. For the current state of + * unsupported parameters in reasoning models, + * [refer to the reasoning guide](/docs/guides/reasoning). + * + * Returns a chat completion object, or a streamed sequence of chat completion + * chunk objects if the request is streamed. + */ + readonly "createChatCompletionSse": ( + options: { readonly payload: typeof CreateChatCompletionRequestJson.Encoded } + ) => Stream.Stream< + { readonly event: string; readonly id: string | undefined; readonly data: typeof CreateChatCompletion200Sse.Type }, + HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, + typeof CreateChatCompletion200Sse.DecodingServices + > + /** + * Get a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` will be returned. + */ + readonly "getChatCompletion": ( + completionId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Modify a stored chat completion. Only Chat Completions that have been + * created with the `store` parameter set to `true` can be modified. Currently, + * the only supported modification is to update the `metadata` field. + */ + readonly "updateChatCompletion": ( + completionId: string, + options: { readonly payload: typeof UpdateChatCompletionRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a stored chat completion. Only Chat Completions that have been + * created with the `store` parameter set to `true` can be deleted. + */ + readonly "deleteChatCompletion": ( + completionId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get the messages in a stored chat completion. Only Chat Completions that + * have been created with the `store` parameter set to `true` will be + * returned. + */ + readonly "getChatCompletionMessages": ( + completionId: string, + options: { + readonly params?: typeof GetChatCompletionMessagesParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates a completion for the provided prompt and parameters. + * + * Returns a completion object, or a sequence of completion objects if the request is streamed. + */ + readonly "createCompletion": ( + options: { readonly payload: typeof CreateCompletionRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists containers. + */ + readonly "ListContainers": ( + options: + | { readonly params?: typeof ListContainersParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates a container. + */ + readonly "CreateContainer": ( + options: { readonly payload: typeof CreateContainerRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a container. + */ + readonly "RetrieveContainer": ( + containerId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a container. + */ + readonly "DeleteContainer": ( + containerId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Lists container files. + */ + readonly "ListContainerFiles": ( + containerId: string, + options: { + readonly params?: typeof ListContainerFilesParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates a container file. + */ + readonly "CreateContainerFile": ( + containerId: string, + options: { + readonly payload: typeof CreateContainerFileRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a container file. + */ + readonly "RetrieveContainerFile": ( + containerId: string, + fileId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a container file. + */ + readonly "DeleteContainerFile": ( + containerId: string, + fileId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Retrieves a container file content. + */ + readonly "RetrieveContainerFileContent": ( + containerId: string, + fileId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * List all items for a conversation with the given ID. + */ + readonly "listConversationItems": ( + conversationId: string, + options: { + readonly params?: typeof ListConversationItemsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create items in a conversation with the given ID. + */ + readonly "createConversationItems": ( + conversationId: string, + options: { + readonly params?: typeof CreateConversationItemsParams.Encoded | undefined + readonly payload: typeof CreateConversationItemsRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get a single item from a conversation with the given IDs. + */ + readonly "getConversationItem": ( + conversationId: string, + itemId: string, + options: { + readonly params?: typeof GetConversationItemParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete an item from a conversation with the given IDs. + */ + readonly "deleteConversationItem": ( + conversationId: string, + itemId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates an embedding vector representing the input text. + */ + readonly "createEmbedding": ( + options: { readonly payload: typeof CreateEmbeddingRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List evaluations for a project. + */ + readonly "listEvals": ( + options: + | { readonly params?: typeof ListEvalsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create the structure of an evaluation that can be used to test a model's performance. + * An evaluation is a set of testing criteria and the config for a data source, which dictates the schema of the data used in the evaluation. After creating an evaluation, you can run it on different models and model parameters. We support several types of graders and datasources. + * For more information, see the [Evals guide](/docs/guides/evals). + */ + readonly "createEval": ( + options: { readonly payload: typeof CreateEvalRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get an evaluation by ID. + */ + readonly "getEval": ( + evalId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Update certain properties of an evaluation. + */ + readonly "updateEval": ( + evalId: string, + options: { readonly payload: typeof UpdateEvalRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete an evaluation. + */ + readonly "deleteEval": ( + evalId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError | OpenAiClientError<"DeleteEval404", typeof DeleteEval404.Type> + > + /** + * Get a list of runs for an evaluation. + */ + readonly "getEvalRuns": ( + evalId: string, + options: + | { readonly params?: typeof GetEvalRunsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Kicks off a new run for a given evaluation, specifying the data source, and what model configuration to use to test. The datasource will be validated against the schema specified in the config of the evaluation. + */ + readonly "createEvalRun": ( + evalId: string, + options: { readonly payload: typeof CreateEvalRunRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError | OpenAiClientError<"CreateEvalRun400", typeof CreateEvalRun400.Type> + > + /** + * Get an evaluation run by ID. + */ + readonly "getEvalRun": ( + evalId: string, + runId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Cancel an ongoing evaluation run. + */ + readonly "cancelEvalRun": ( + evalId: string, + runId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete an eval run. + */ + readonly "deleteEvalRun": ( + evalId: string, + runId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError | OpenAiClientError<"DeleteEvalRun404", typeof DeleteEvalRun404.Type> + > + /** + * Get a list of output items for an evaluation run. + */ + readonly "getEvalRunOutputItems": ( + evalId: string, + runId: string, + options: { + readonly params?: typeof GetEvalRunOutputItemsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get an evaluation run output item by ID. + */ + readonly "getEvalRunOutputItem": ( + evalId: string, + runId: string, + outputItemId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of files. + */ + readonly "listFiles": ( + options: + | { readonly params?: typeof ListFilesParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Upload a file that can be used across various endpoints. Individual files + * can be up to 512 MB, and each project can store up to 2.5 TB of files in + * total. There is no organization-wide storage limit. Uploads to this + * endpoint are rate-limited to 1,000 requests per minute per authenticated + * user. + * + * - The Assistants API supports files up to 2 million tokens and of specific + * file types. See the [Assistants Tools guide](/docs/assistants/tools) for + * details. + * - The Fine-tuning API only supports `.jsonl` files. The input also has + * certain required formats for fine-tuning + * [chat](/docs/api-reference/fine-tuning/chat-input) or + * [completions](/docs/api-reference/fine-tuning/completions-input) models. + * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input + * also has a specific required + * [format](/docs/api-reference/batch/request-input). + * - For Retrieval or `file_search` ingestion, upload files here first. If + * you need to attach multiple uploaded files to the same vector store, use + * [`/vector_stores/{vector_store_id}/file_batches`](/docs/api-reference/vector-stores-file-batches/createBatch) + * instead of attaching them one by one. Vector store attachment has separate + * limits from file upload, including 2,000 attached files per minute per + * organization. + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + readonly "createFile": ( + options: { readonly payload: typeof CreateFileRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns information about a specific file. + */ + readonly "retrieveFile": ( + fileId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a file and remove it from all vector stores. + */ + readonly "deleteFile": ( + fileId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns the contents of the specified file. + */ + readonly "downloadFile": ( + fileId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Run a grader. + */ + readonly "runGrader": ( + options: { readonly payload: typeof RunGraderRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Validate a grader. + */ + readonly "validateGrader": ( + options: { readonly payload: typeof ValidateGraderRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a fine-tuned model checkpoint. + */ + readonly "listFineTuningCheckpointPermissions": ( + fineTunedModelCheckpoint: string, + options: { + readonly params?: typeof ListFineTuningCheckpointPermissionsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects in their organization. + */ + readonly "createFineTuningCheckpointPermission": ( + fineTunedModelCheckpoint: string, + options: { + readonly payload: typeof CreateFineTuningCheckpointPermissionRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a fine-tuned model checkpoint. + */ + readonly "deleteFineTuningCheckpointPermission": ( + fineTunedModelCheckpoint: string, + permissionId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List your organization's fine-tuning jobs + */ + readonly "listPaginatedFineTuningJobs": ( + options: { + readonly params?: typeof ListPaginatedFineTuningJobsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates a fine-tuning job which begins the process of creating a new model from a given dataset. + * + * Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](/docs/guides/model-optimization) + */ + readonly "createFineTuningJob": ( + options: { readonly payload: typeof CreateFineTuningJobRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](/docs/guides/model-optimization) + */ + readonly "retrieveFineTuningJob": ( + fineTuningJobId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Immediately cancel a fine-tune job. + */ + readonly "cancelFineTuningJob": ( + fineTuningJobId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List checkpoints for a fine-tuning job. + */ + readonly "listFineTuningJobCheckpoints": ( + fineTuningJobId: string, + options: { + readonly params?: typeof ListFineTuningJobCheckpointsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get status updates for a fine-tuning job. + */ + readonly "listFineTuningEvents": ( + fineTuningJobId: string, + options: { + readonly params?: typeof ListFineTuningEventsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Pause a fine-tune job. + */ + readonly "pauseFineTuningJob": ( + fineTuningJobId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Resume a fine-tune job. + */ + readonly "resumeFineTuningJob": ( + fineTuningJobId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * You can call this endpoint with either: + * + * - `multipart/form-data`: use binary uploads via `image` (and optional `mask`). + * - `application/json`: use `images` (and optional `mask`) as references with either `image_url` or `file_id`. + * + * Note that JSON requests use `images` (array) instead of the multipart `image` field. + */ + readonly "createImageEdit": ( + options: { readonly payload: typeof CreateImageEditRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * You can call this endpoint with either: + * + * - `multipart/form-data`: use binary uploads via `image` (and optional `mask`). + * - `application/json`: use `images` (and optional `mask`) as references with either `image_url` or `file_id`. + * + * Note that JSON requests use `images` (array) instead of the multipart `image` field. + */ + readonly "createImageEditSse": ( + options: { readonly payload: typeof CreateImageEditRequestFormData.Encoded } + ) => Stream.Stream< + { readonly event: string; readonly id: string | undefined; readonly data: typeof CreateImageEdit200Sse.Type }, + HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, + typeof CreateImageEdit200Sse.DecodingServices + > + /** + * Creates an image given a prompt. [Learn more](/docs/guides/images). + */ + readonly "createImage": ( + options: { readonly payload: typeof CreateImageRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates an image given a prompt. [Learn more](/docs/guides/images). + */ + readonly "createImageSse": ( + options: { readonly payload: typeof CreateImageRequestJson.Encoded } + ) => Stream.Stream< + { readonly event: string; readonly id: string | undefined; readonly data: typeof CreateImage200Sse.Type }, + HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, + typeof CreateImage200Sse.DecodingServices + > + /** + * Creates a variation of a given image. This endpoint only supports `dall-e-2`. + */ + readonly "createImageVariation": ( + options: { + readonly payload: typeof CreateImageVariationRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists the currently available models, and provides basic information about each one such as the owner and availability. + */ + readonly "listModels": ( + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a model instance, providing basic information about the model such as the owner and permissioning. + */ + readonly "retrieveModel": ( + model: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to delete a model. + */ + readonly "deleteModel": ( + model: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Classifies if text and/or image inputs are potentially harmful. Learn + * more in the [moderation guide](/docs/guides/moderation). + */ + readonly "createModeration": ( + options: { readonly payload: typeof CreateModerationRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieve a paginated list of organization admin API keys. + */ + readonly "adminApiKeysList": ( + options: { + readonly params?: typeof AdminApiKeysListParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a new admin-level API key for the organization. + */ + readonly "adminApiKeysCreate": ( + options: { readonly payload: typeof AdminApiKeysCreateRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get details for a specific organization API key by its ID. + */ + readonly "adminApiKeysGet": ( + keyId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete the specified admin API key. + */ + readonly "adminApiKeysDelete": ( + keyId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List user actions and configuration changes within this organization. + */ + readonly "listAuditLogs": ( + options: + | { readonly params?: typeof ListAuditLogsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List uploaded certificates for this organization. + */ + readonly "listOrganizationCertificates": ( + options: { + readonly params?: typeof ListOrganizationCertificatesParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Upload a certificate to the organization. This does **not** automatically activate the certificate. + * + * Organizations can upload up to 50 certificates. + */ + readonly "uploadCertificate": ( + options: { readonly payload: typeof UploadCertificateRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Activate certificates at the organization level. + * + * You can atomically and idempotently activate up to 10 certificates at a time. + */ + readonly "activateOrganizationCertificates": ( + options: { + readonly payload: typeof ActivateOrganizationCertificatesRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deactivate certificates at the organization level. + * + * You can atomically and idempotently deactivate up to 10 certificates at a time. + */ + readonly "deactivateOrganizationCertificates": ( + options: { + readonly payload: typeof DeactivateOrganizationCertificatesRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get a certificate that has been uploaded to the organization. + * + * You can get a certificate regardless of whether it is active or not. + */ + readonly "getCertificate": ( + certificateId: string, + options: + | { readonly params?: typeof GetCertificateParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Modify a certificate. Note that only the name can be modified. + */ + readonly "modifyCertificate": ( + certificateId: string, + options: { readonly payload: typeof ModifyCertificateRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a certificate from the organization. + * + * The certificate must be inactive for the organization and all projects. + */ + readonly "deleteCertificate": ( + certificateId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get costs details for the organization. + */ + readonly "usageCosts": ( + options: { readonly params: typeof UsageCostsParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists all groups in the organization. + */ + readonly "listGroups": ( + options: + | { readonly params?: typeof ListGroupsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates a new group in the organization. + */ + readonly "createGroup": ( + options: { readonly payload: typeof CreateGroupRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Updates a group's information. + */ + readonly "updateGroup": ( + groupId: string, + options: { readonly payload: typeof UpdateGroupRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deletes a group from the organization. + */ + readonly "deleteGroup": ( + groupId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists the organization roles assigned to a group within the organization. + */ + readonly "listGroupRoleAssignments": ( + groupId: string, + options: { + readonly params?: typeof ListGroupRoleAssignmentsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Assigns an organization role to a group within the organization. + */ + readonly "assignGroupRole": ( + groupId: string, + options: { readonly payload: typeof AssignGroupRoleRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Unassigns an organization role from a group within the organization. + */ + readonly "unassignGroupRole": ( + groupId: string, + roleId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists the users assigned to a group. + */ + readonly "listGroupUsers": ( + groupId: string, + options: + | { readonly params?: typeof ListGroupUsersParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Adds a user to a group. + */ + readonly "addGroupUser": ( + groupId: string, + options: { readonly payload: typeof AddGroupUserRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Removes a user from a group. + */ + readonly "removeGroupUser": ( + groupId: string, + userId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of invites in the organization. + */ + readonly "listInvites": ( + options: + | { readonly params?: typeof ListInvitesParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create an invite for a user to the organization. The invite must be accepted by the user before they have access to the organization. + */ + readonly "inviteUser": ( + options: { readonly payload: typeof InviteUserRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves an invite. + */ + readonly "retrieveInvite": ( + inviteId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete an invite. If the invite has already been accepted, it cannot be deleted. + */ + readonly "deleteInvite": ( + inviteId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of projects. + */ + readonly "listProjects": ( + options: + | { readonly params?: typeof ListProjectsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a new project in the organization. Projects can be created and archived, but cannot be deleted. + */ + readonly "createProject": ( + options: { readonly payload: typeof CreateProjectRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a project. + */ + readonly "retrieveProject": ( + projectId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Modifies a project in the organization. + */ + readonly "modifyProject": ( + projectId: string, + options: { readonly payload: typeof ModifyProjectRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError | OpenAiClientError<"ModifyProject400", typeof ModifyProject400.Type> + > + /** + * Returns a list of API keys in the project. + */ + readonly "listProjectApiKeys": ( + projectId: string, + options: { + readonly params?: typeof ListProjectApiKeysParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves an API key in the project. + */ + readonly "retrieveProjectApiKey": ( + projectId: string, + apiKeyId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deletes an API key from the project. + * + * Returns confirmation of the key deletion, or an error if the key belonged to + * a service account. + */ + readonly "deleteProjectApiKey": ( + projectId: string, + apiKeyId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"DeleteProjectApiKey400", typeof DeleteProjectApiKey400.Type> + > + /** + * Archives a project in the organization. Archived projects cannot be used or updated. + */ + readonly "archiveProject": ( + projectId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List certificates for this project. + */ + readonly "listProjectCertificates": ( + projectId: string, + options: { + readonly params?: typeof ListProjectCertificatesParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Activate certificates at the project level. + * + * You can atomically and idempotently activate up to 10 certificates at a time. + */ + readonly "activateProjectCertificates": ( + projectId: string, + options: { + readonly payload: typeof ActivateProjectCertificatesRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deactivate certificates at the project level. You can atomically and + * idempotently deactivate up to 10 certificates at a time. + */ + readonly "deactivateProjectCertificates": ( + projectId: string, + options: { + readonly payload: typeof DeactivateProjectCertificatesRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists the groups that have access to a project. + */ + readonly "listProjectGroups": ( + projectId: string, + options: { + readonly params?: typeof ListProjectGroupsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Grants a group access to a project. + */ + readonly "addProjectGroup": ( + projectId: string, + options: { readonly payload: typeof AddProjectGroupRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Revokes a group's access to a project. + */ + readonly "removeProjectGroup": ( + projectId: string, + groupId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns hosted tool permissions for a project. + */ + readonly "retrieveProjectHostedToolPermissions": ( + projectId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Updates hosted tool permissions for a project. + */ + readonly "updateProjectHostedToolPermissions": ( + projectId: string, + options: { + readonly payload: typeof UpdateProjectHostedToolPermissionsRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns model permissions for a project. + */ + readonly "retrieveProjectModelPermissions": ( + projectId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Updates model permissions for a project. + */ + readonly "updateProjectModelPermissions": ( + projectId: string, + options: { + readonly payload: typeof UpdateProjectModelPermissionsRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deletes model permissions for a project. + */ + readonly "deleteProjectModelPermissions": ( + projectId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns the rate limits per model for a project. + */ + readonly "listProjectRateLimits": ( + projectId: string, + options: { + readonly params?: typeof ListProjectRateLimitsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Updates a project rate limit. + */ + readonly "updateProjectRateLimits": ( + projectId: string, + rateLimitId: string, + options: { + readonly payload: typeof UpdateProjectRateLimitsRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"UpdateProjectRateLimits400", typeof UpdateProjectRateLimits400.Type> + > + /** + * Returns a list of service accounts in the project. + */ + readonly "listProjectServiceAccounts": ( + projectId: string, + options: { + readonly params?: typeof ListProjectServiceAccountsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"ListProjectServiceAccounts400", typeof ListProjectServiceAccounts400.Type> + > + /** + * Creates a new service account in the project. This also returns an unredacted API key for the service account. + */ + readonly "createProjectServiceAccount": ( + projectId: string, + options: { + readonly payload: typeof CreateProjectServiceAccountRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"CreateProjectServiceAccount400", typeof CreateProjectServiceAccount400.Type> + > + /** + * Retrieves a service account in the project. + */ + readonly "retrieveProjectServiceAccount": ( + projectId: string, + serviceAccountId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deletes a service account from the project. + * + * Returns confirmation of service account deletion, or an error if the project + * is archived (archived projects have no service accounts). + */ + readonly "deleteProjectServiceAccount": ( + projectId: string, + serviceAccountId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of users in the project. + */ + readonly "listProjectUsers": ( + projectId: string, + options: { + readonly params?: typeof ListProjectUsersParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"ListProjectUsers400", typeof ListProjectUsers400.Type> + > + /** + * Adds a user to the project. Users must already be members of the organization to be added to a project. + */ + readonly "createProjectUser": ( + projectId: string, + options: { readonly payload: typeof CreateProjectUserRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"CreateProjectUser400", typeof CreateProjectUser400.Type> + > + /** + * Retrieves a user in the project. + */ + readonly "retrieveProjectUser": ( + projectId: string, + userId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Modifies a user's role in the project. + */ + readonly "modifyProjectUser": ( + projectId: string, + userId: string, + options: { readonly payload: typeof ModifyProjectUserRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"ModifyProjectUser400", typeof ModifyProjectUser400.Type> + > + /** + * Deletes a user from the project. + * + * Returns confirmation of project user deletion, or an error if the project is + * archived (archived projects have no users). + */ + readonly "deleteProjectUser": ( + projectId: string, + userId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"DeleteProjectUser400", typeof DeleteProjectUser400.Type> + > + /** + * Lists the roles configured for the organization. + */ + readonly "listRoles": ( + options: + | { readonly params?: typeof ListRolesParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates a custom role for the organization. + */ + readonly "createRole": ( + options: { readonly payload: typeof CreateRoleRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Updates an existing organization role. + */ + readonly "updateRole": ( + roleId: string, + options: { readonly payload: typeof UpdateRoleRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deletes a custom role from the organization. + */ + readonly "deleteRole": ( + roleId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get audio speeches usage details for the organization. + */ + readonly "usageAudioSpeeches": ( + options: { readonly params: typeof UsageAudioSpeechesParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get audio transcriptions usage details for the organization. + */ + readonly "usageAudioTranscriptions": ( + options: { readonly params: typeof UsageAudioTranscriptionsParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get code interpreter sessions usage details for the organization. + */ + readonly "usageCodeInterpreterSessions": ( + options: { + readonly params: typeof UsageCodeInterpreterSessionsParams.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get completions usage details for the organization. + */ + readonly "usageCompletions": ( + options: { readonly params: typeof UsageCompletionsParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get embeddings usage details for the organization. + */ + readonly "usageEmbeddings": ( + options: { readonly params: typeof UsageEmbeddingsParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get file search calls usage details for the organization. + */ + readonly "usageFileSearchCalls": ( + options: { readonly params: typeof UsageFileSearchCallsParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get images usage details for the organization. + */ + readonly "usageImages": ( + options: { readonly params: typeof UsageImagesParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get moderations usage details for the organization. + */ + readonly "usageModerations": ( + options: { readonly params: typeof UsageModerationsParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get vector stores usage details for the organization. + */ + readonly "usageVectorStores": ( + options: { readonly params: typeof UsageVectorStoresParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get web search calls usage details for the organization. + */ + readonly "usageWebSearchCalls": ( + options: { readonly params: typeof UsageWebSearchCallsParams.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists all of the users in the organization. + */ + readonly "listUsers": ( + options: + | { readonly params?: typeof ListUsersParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a user by their identifier. + */ + readonly "retrieveUser": ( + userId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Modifies a user's role in the organization. + */ + readonly "modifyUser": ( + userId: string, + options: { readonly payload: typeof ModifyUserRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deletes a user from the organization. + */ + readonly "deleteUser": ( + userId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists the organization roles assigned to a user within the organization. + */ + readonly "listUserRoleAssignments": ( + userId: string, + options: { + readonly params?: typeof ListUserRoleAssignmentsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Assigns an organization role to a user within the organization. + */ + readonly "assignUserRole": ( + userId: string, + options: { readonly payload: typeof AssignUserRoleRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Unassigns an organization role from a user within the organization. + */ + readonly "unassignUserRole": ( + userId: string, + roleId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists the project roles assigned to a group within a project. + */ + readonly "listProjectGroupRoleAssignments": ( + projectId: string, + groupId: string, + options: { + readonly params?: typeof ListProjectGroupRoleAssignmentsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Assigns a project role to a group within a project. + */ + readonly "assignProjectGroupRole": ( + projectId: string, + groupId: string, + options: { + readonly payload: typeof AssignProjectGroupRoleRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Unassigns a project role from a group within a project. + */ + readonly "unassignProjectGroupRole": ( + projectId: string, + groupId: string, + roleId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists the roles configured for a project. + */ + readonly "listProjectRoles": ( + projectId: string, + options: { + readonly params?: typeof ListProjectRolesParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates a custom role for a project. + */ + readonly "createProjectRole": ( + projectId: string, + options: { readonly payload: typeof CreateProjectRoleRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Updates an existing project role. + */ + readonly "updateProjectRole": ( + projectId: string, + roleId: string, + options: { readonly payload: typeof UpdateProjectRoleRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deletes a custom role from a project. + */ + readonly "deleteProjectRole": ( + projectId: string, + roleId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Lists the project roles assigned to a user within a project. + */ + readonly "listProjectUserRoleAssignments": ( + projectId: string, + userId: string, + options: { + readonly params?: typeof ListProjectUserRoleAssignmentsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Assigns a project role to a user within a project. + */ + readonly "assignProjectUserRole": ( + projectId: string, + userId: string, + options: { readonly payload: typeof AssignProjectUserRoleRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Unassigns a project role from a user within a project. + */ + readonly "unassignProjectUserRole": ( + projectId: string, + userId: string, + roleId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a new Realtime API call over WebRTC and receive the SDP answer needed + * to complete the peer connection. + */ + readonly "createRealtimeCall": ( + options: { + readonly payload: typeof CreateRealtimeCallRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Accept an incoming SIP call and configure the realtime session that will + * handle it. + */ + readonly "acceptRealtimeCall": ( + callId: string, + options: { readonly payload: typeof AcceptRealtimeCallRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * End an active Realtime API call, whether it was initiated over SIP or + * WebRTC. + */ + readonly "hangupRealtimeCall": ( + callId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Transfer an active SIP call to a new destination using the SIP REFER verb. + */ + readonly "referRealtimeCall": ( + callId: string, + options: { readonly payload: typeof ReferRealtimeCallRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Decline an incoming SIP call by returning a SIP status code to the caller. + */ + readonly "rejectRealtimeCall": ( + callId: string, + options: { readonly payload: typeof RejectRealtimeCallRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Create a Realtime client secret with an associated session configuration. + * + * Client secrets are short-lived tokens that can be passed to a client app, + * such as a web frontend or mobile client, which grants access to the Realtime API without + * leaking your main API key. You can configure a custom TTL for each client secret. + * + * You can also attach session configuration options to the client secret, which will be + * applied to any sessions created using that client secret, but these can also be overridden + * by the client connection. + * + * [Learn more about authentication with client secrets over WebRTC](/docs/guides/realtime-webrtc). + * + * Returns the created client secret and the effective session object. The client secret is a string that looks like `ek_1234`. + */ + readonly "createRealtimeClientSecret": ( + options: { + readonly payload: typeof CreateRealtimeClientSecretRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API. Can be configured with the same session parameters as the + * `session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains + * a usable ephemeral API token that can be used to authenticate browser clients + * for the Realtime API. + * + * Returns the created Realtime session object, plus an ephemeral key. + */ + readonly "createRealtimeSession": ( + options: { readonly payload: typeof CreateRealtimeSessionRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API specifically for realtime transcriptions. + * Can be configured with the same session parameters as the `transcription_session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains + * a usable ephemeral API token that can be used to authenticate browser clients + * for the Realtime API. + * + * Returns the created Realtime transcription session object, plus an ephemeral key. + */ + readonly "createRealtimeTranscriptionSession": ( + options: { + readonly payload: typeof CreateRealtimeTranscriptionSessionRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a Realtime translation client secret with an associated translation session configuration. + * + * Client secrets are short-lived tokens that can be passed to a client app, + * such as a web frontend or mobile client, which grants access to the Realtime + * Translation API without leaking your main API key. You can configure a custom + * TTL for each client secret. + * + * Returns the created client secret and the effective translation session object. + * The client secret is a string that looks like `ek_1234`. + */ + readonly "createRealtimeTranslationClientSecret": ( + options: { + readonly payload: typeof CreateRealtimeTranslationClientSecretRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates a model response. Provide [text](/docs/guides/text) or + * [image](/docs/guides/images) inputs to generate [text](/docs/guides/text) + * or [JSON](/docs/guides/structured-outputs) outputs. Have the model call + * your own [custom code](/docs/guides/function-calling) or use built-in + * [tools](/docs/guides/tools) like [web search](/docs/guides/tools-web-search) + * or [file search](/docs/guides/tools-file-search) to use your own data + * as input for the model's response. + */ + readonly "createResponse": ( + options: { readonly payload: typeof CreateResponseRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates a model response. Provide [text](/docs/guides/text) or + * [image](/docs/guides/images) inputs to generate [text](/docs/guides/text) + * or [JSON](/docs/guides/structured-outputs) outputs. Have the model call + * your own [custom code](/docs/guides/function-calling) or use built-in + * [tools](/docs/guides/tools) like [web search](/docs/guides/tools-web-search) + * or [file search](/docs/guides/tools-file-search) to use your own data + * as input for the model's response. + */ + readonly "createResponseSse": ( + options: { readonly payload: typeof CreateResponseRequestJson.Encoded } + ) => Stream.Stream< + { readonly event: string; readonly id: string | undefined; readonly data: typeof CreateResponse200Sse.Type }, + HttpClientError.HttpClientError | SchemaError | Sse.Retry | Sse.SseError, + typeof CreateResponse200Sse.DecodingServices + > + /** + * Retrieves a model response with the given ID. + */ + readonly "getResponse": ( + responseId: string, + options: + | { readonly params?: typeof GetResponseParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deletes a model response with the given ID. + */ + readonly "deleteResponse": ( + responseId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"DeleteResponse404", typeof DeleteResponse404.Type> + > + /** + * Cancels a model response with the given ID. Only responses created with + * the `background` parameter set to `true` can be cancelled. + * [Learn more](/docs/guides/background). + */ + readonly "cancelResponse": ( + responseId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + | HttpClientError.HttpClientError + | SchemaError + | OpenAiClientError<"CancelResponse404", typeof CancelResponse404.Type> + > + /** + * Returns a list of input items for a given response. + */ + readonly "listInputItems": ( + responseId: string, + options: + | { readonly params?: typeof ListInputItemsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a thread. + */ + readonly "createThread": ( + options: { readonly payload: typeof CreateThreadRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a thread and run it in one request. + */ + readonly "createThreadAndRun": ( + options: { readonly payload: typeof CreateThreadAndRunRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a thread. + */ + readonly "getThread": ( + threadId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Modifies a thread. + */ + readonly "modifyThread": ( + threadId: string, + options: { readonly payload: typeof ModifyThreadRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a thread. + */ + readonly "deleteThread": ( + threadId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of messages for a given thread. + */ + readonly "listMessages": ( + threadId: string, + options: + | { readonly params?: typeof ListMessagesParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a message. + */ + readonly "createMessage": ( + threadId: string, + options: { readonly payload: typeof CreateMessageRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieve a message. + */ + readonly "getMessage": ( + threadId: string, + messageId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Modifies a message. + */ + readonly "modifyMessage": ( + threadId: string, + messageId: string, + options: { readonly payload: typeof ModifyMessageRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Deletes a message. + */ + readonly "deleteMessage": ( + threadId: string, + messageId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of runs belonging to a thread. + */ + readonly "listRuns": ( + threadId: string, + options: + | { readonly params?: typeof ListRunsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a run. + */ + readonly "createRun": ( + threadId: string, + options: { + readonly params?: typeof CreateRunParams.Encoded | undefined + readonly payload: typeof CreateRunRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a run. + */ + readonly "getRun": ( + threadId: string, + runId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect, HttpClientError.HttpClientError | SchemaError> + /** + * Modifies a run. + */ + readonly "modifyRun": ( + threadId: string, + runId: string, + options: { readonly payload: typeof ModifyRunRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Cancels a run that is `in_progress`. + */ + readonly "cancelRun": ( + threadId: string, + runId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of run steps belonging to a run. + */ + readonly "listRunSteps": ( + threadId: string, + runId: string, + options: + | { readonly params?: typeof ListRunStepsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a run step. + */ + readonly "getRunStep": ( + threadId: string, + runId: string, + stepId: string, + options: + | { readonly params?: typeof GetRunStepParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request. + */ + readonly "submitToolOuputsToRun": ( + threadId: string, + runId: string, + options: { readonly payload: typeof SubmitToolOuputsToRunRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Creates an intermediate [Upload](/docs/api-reference/uploads/object) object + * that you can add [Parts](/docs/api-reference/uploads/part-object) to. + * Currently, an Upload can accept at most 8 GB in total and expires after an + * hour after you create it. + * + * Once you complete the Upload, we will create a + * [File](/docs/api-reference/files/object) object that contains all the parts + * you uploaded. This File is usable in the rest of our platform as a regular + * File object. + * + * For certain `purpose` values, the correct `mime_type` must be specified. + * Please refer to documentation for the + * [supported MIME types for your use case](/docs/assistants/tools/file-search#supported-files). + * + * For guidance on the proper filename extensions for each purpose, please + * follow the documentation on [creating a + * File](/docs/api-reference/files/create). + * + * Returns the Upload object with status `pending`. + */ + readonly "createUpload": ( + options: { readonly payload: typeof CreateUploadRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Cancels the Upload. No Parts may be added after an Upload is cancelled. + * + * Returns the Upload object with status `cancelled`. + */ + readonly "cancelUpload": ( + uploadId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Completes the [Upload](/docs/api-reference/uploads/object). + * + * Within the returned Upload object, there is a nested [File](/docs/api-reference/files/object) object that is ready to use in the rest of the platform. + * + * You can specify the order of the Parts by passing in an ordered list of the Part IDs. + * + * The number of bytes uploaded upon completion must match the number of bytes initially specified when creating the Upload object. No Parts may be added after an Upload is completed. + * Returns the Upload object with status `completed`, including an additional `file` property containing the created usable File object. + */ + readonly "completeUpload": ( + uploadId: string, + options: { readonly payload: typeof CompleteUploadRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Adds a [Part](/docs/api-reference/uploads/part-object) to an [Upload](/docs/api-reference/uploads/object) object. A Part represents a chunk of bytes from the file you are trying to upload. + * + * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload maximum of 8 GB. + * + * It is possible to add multiple Parts in parallel. You can decide the intended order of the Parts when you [complete the Upload](/docs/api-reference/uploads/complete). + */ + readonly "addUploadPart": ( + uploadId: string, + options: { readonly payload: typeof AddUploadPartRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of vector stores. + */ + readonly "listVectorStores": ( + options: { + readonly params?: typeof ListVectorStoresParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a vector store. + */ + readonly "createVectorStore": ( + options: { readonly payload: typeof CreateVectorStoreRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a vector store. + */ + readonly "getVectorStore": ( + vectorStoreId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Modifies a vector store. + */ + readonly "modifyVectorStore": ( + vectorStoreId: string, + options: { readonly payload: typeof ModifyVectorStoreRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a vector store. + */ + readonly "deleteVectorStore": ( + vectorStoreId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * The maximum number of files in a single batch request is 2000. + * Vector store file attach requests are rate limited per vector store (300 requests per minute across both this endpoint and `/vector_stores/{vector_store_id}/files`). + * For ingesting multiple files into the same vector store, this batch endpoint is recommended. + */ + readonly "createVectorStoreFileBatch": ( + vectorStoreId: string, + options: { + readonly payload: typeof CreateVectorStoreFileBatchRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a vector store file batch. + */ + readonly "getVectorStoreFileBatch": ( + vectorStoreId: string, + batchId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Cancel a vector store file batch. This attempts to cancel the processing of files in this batch as soon as possible. + */ + readonly "cancelVectorStoreFileBatch": ( + vectorStoreId: string, + batchId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of vector store files in a batch. + */ + readonly "listFilesInVectorStoreBatch": ( + vectorStoreId: string, + batchId: string, + options: { + readonly params?: typeof ListFilesInVectorStoreBatchParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns a list of vector store files. + */ + readonly "listVectorStoreFiles": ( + vectorStoreId: string, + options: { + readonly params?: typeof ListVectorStoreFilesParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * This endpoint is subject to a per-vector-store write rate limit of 300 requests per minute, shared with `/vector_stores/{vector_store_id}/file_batches`. + * For uploading multiple files to the same vector store, use the file batches endpoint to reduce request volume. + */ + readonly "createVectorStoreFile": ( + vectorStoreId: string, + options: { readonly payload: typeof CreateVectorStoreFileRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieves a vector store file. + */ + readonly "getVectorStoreFile": ( + vectorStoreId: string, + fileId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Update attributes on a vector store file. + */ + readonly "updateVectorStoreFileAttributes": ( + vectorStoreId: string, + fileId: string, + options: { + readonly payload: typeof UpdateVectorStoreFileAttributesRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a vector store file. This will remove the file from the vector store but the file itself will not be deleted. To delete the file, use the [delete file](/docs/api-reference/files/delete) endpoint. + */ + readonly "deleteVectorStoreFile": ( + vectorStoreId: string, + fileId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieve the parsed contents of a vector store file. + */ + readonly "retrieveVectorStoreFileContent": ( + vectorStoreId: string, + fileId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Search a vector store for relevant chunks based on a query and file attributes filter. + */ + readonly "searchVectorStore": ( + vectorStoreId: string, + options: { readonly payload: typeof SearchVectorStoreRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a conversation. + */ + readonly "createConversation": ( + options: { readonly payload: typeof CreateConversationRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get a conversation + */ + readonly "getConversation": ( + conversationId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Update a conversation + */ + readonly "updateConversation": ( + conversationId: string, + options: { readonly payload: typeof UpdateConversationRequestJson.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a conversation. Items in the conversation will not be deleted. + */ + readonly "deleteConversation": ( + conversationId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List recently generated videos for the current project. + */ + readonly "ListVideos": ( + options: + | { readonly params?: typeof ListVideosParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a new video generation job from a prompt and optional reference assets. + */ + readonly "createVideo": ( + options: { readonly payload: typeof CreateVideoRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a character from an uploaded video. + */ + readonly "CreateVideoCharacter": ( + options: { + readonly payload: typeof CreateVideoCharacterRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Fetch a character. + */ + readonly "GetVideoCharacter": ( + characterId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a new video generation job by editing a source video or existing generated video. + */ + readonly "CreateVideoEdit": ( + options: { readonly payload: typeof CreateVideoEditRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create an extension of a completed video. + */ + readonly "CreateVideoExtend": ( + options: { readonly payload: typeof CreateVideoExtendRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Fetch the latest metadata for a generated video. + */ + readonly "GetVideo": ( + videoId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Permanently delete a completed or failed video and its stored assets. + */ + readonly "DeleteVideo": ( + videoId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Download the generated video bytes or a derived preview asset. + * + * Streams the rendered video content for the specified video job. + */ + readonly "RetrieveVideoContent": ( + videoId: string, + options: { + readonly params?: typeof RetrieveVideoContentParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a remix of a completed video using a refreshed prompt. + */ + readonly "CreateVideoRemix": ( + videoId: string, + options: { readonly payload: typeof CreateVideoRemixRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Returns input token counts of the request. + * + * Returns an object with `object` set to `response.input_tokens` and an `input_tokens` count. + */ + readonly "Getinputtokencounts": ( + options: { + readonly payload: typeof GetinputtokencountsRequestFormUrlEncoded.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Compact a conversation. Returns a compacted response object. + * + * Learn when and how to compact long-running conversations in the [conversation state guide](/docs/guides/conversation-state#managing-the-context-window). For ZDR-compatible compaction details, see [Compaction (advanced)](/docs/guides/conversation-state#compaction-advanced). + */ + readonly "Compactconversation": ( + options: { + readonly payload: typeof CompactconversationRequestFormUrlEncoded.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List all skills for the current project. + */ + readonly "ListSkills": ( + options: + | { readonly params?: typeof ListSkillsParams.Encoded | undefined; readonly config?: Config | undefined } + | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a new skill. + */ + readonly "CreateSkill": ( + options: { readonly payload: typeof CreateSkillRequestFormData.Encoded; readonly config?: Config | undefined } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get a skill by its ID. + */ + readonly "GetSkill": ( + skillId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Update the default version pointer for a skill. + */ + readonly "UpdateSkillDefaultVersion": ( + skillId: string, + options: { + readonly payload: typeof UpdateSkillDefaultVersionRequestFormUrlEncoded.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a skill by its ID. + */ + readonly "DeleteSkill": ( + skillId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Download a skill zip bundle by its ID. + */ + readonly "GetSkillContent": ( + skillId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List skill versions for a skill. + */ + readonly "ListSkillVersions": ( + skillId: string, + options: { + readonly params?: typeof ListSkillVersionsParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a new immutable skill version. + */ + readonly "CreateSkillVersion": ( + skillId: string, + options: { + readonly payload: typeof CreateSkillVersionRequestFormData.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Get a specific skill version. + */ + readonly "GetSkillVersion": ( + skillId: string, + version: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a skill version. + */ + readonly "DeleteSkillVersion": ( + skillId: string, + version: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Download a skill version zip bundle. + */ + readonly "GetSkillVersionContent": ( + skillId: string, + version: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Cancel an active ChatKit session and return its most recent metadata. + * + * Cancelling prevents new requests from using the issued client secret. + */ + readonly "CancelChatSessionMethod": ( + sessionId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Create a ChatKit session. + */ + readonly "CreateChatSessionMethod": ( + options: { + readonly payload: typeof CreateChatSessionMethodRequestJson.Encoded + readonly config?: Config | undefined + } + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List items that belong to a ChatKit thread. + */ + readonly "ListThreadItemsMethod": ( + threadId: string, + options: { + readonly params?: typeof ListThreadItemsMethodParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Retrieve a ChatKit thread by its identifier. + */ + readonly "GetThreadMethod": ( + threadId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * Delete a ChatKit thread along with its items and stored attachments. + */ + readonly "DeleteThreadMethod": ( + threadId: string, + options: { readonly config?: Config | undefined } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > + /** + * List ChatKit threads with optional pagination and user filters. + */ + readonly "ListThreadsMethod": ( + options: { + readonly params?: typeof ListThreadsMethodParams.Encoded | undefined + readonly config?: Config | undefined + } | undefined + ) => Effect.Effect< + WithOptionalResponse, + HttpClientError.HttpClientError | SchemaError + > +} + +export interface OpenAiClientError { + readonly _tag: Tag + readonly request: HttpClientRequest.HttpClientRequest + readonly response: HttpClientResponse.HttpClientResponse + readonly cause: E +} + +class OpenAiClientErrorImpl extends Data.Error<{ + _tag: string + cause: any + request: HttpClientRequest.HttpClientRequest + response: HttpClientResponse.HttpClientResponse +}> {} + +export const OpenAiClientError = ( + tag: Tag, + cause: E, + response: HttpClientResponse.HttpClientResponse +): OpenAiClientError => + new OpenAiClientErrorImpl({ + _tag: tag, + cause, + response, + request: response.request + }) as any diff --git a/packages/effect-ai-openai/src/OpenAiClient.ts b/packages/effect-ai-openai/src/OpenAiClient.ts new file mode 100644 index 0000000..0570f2c --- /dev/null +++ b/packages/effect-ai-openai/src/OpenAiClient.ts @@ -0,0 +1,744 @@ +/** + * The `OpenAiClient` module defines the low-level Effect service used by the + * OpenAI integration for Responses API and embedding requests. It builds a + * configured HTTP client with authentication and OpenAI organization or project + * headers, exposes helpers for non-streaming responses, SSE response streams, + * WebSocket response streams, and embeddings, and maps transport or decoding + * failures into `AiError`. + * + * @since 4.0.0 + */ +import * as Array from "effect/Array" +import type * as Config from "effect/Config" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { identity } from "effect/Function" +import * as Function from "effect/Function" +import * as Layer from "effect/Layer" +import * as Predicate from "effect/Predicate" +import * as Queue from "effect/Queue" +import * as RcRef from "effect/RcRef" +import * as Redacted from "effect/Redacted" +import * as Schema from "effect/Schema" +import * as Scope from "effect/Scope" +import * as Semaphore from "effect/Semaphore" +import * as Stream from "effect/Stream" +import * as AiError from "effect/unstable/ai/AiError" +import * as ResponseIdTracker from "effect/unstable/ai/ResponseIdTracker" +import * as Sse from "effect/unstable/encoding/Sse" +import * as Headers from "effect/unstable/http/Headers" +import * as HttpBody from "effect/unstable/http/HttpBody" +import * as HttpClient from "effect/unstable/http/HttpClient" +import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import * as Socket from "effect/unstable/socket/Socket" +import * as Errors from "./internal/errors.ts" +import { OpenAiConfig } from "./OpenAiConfig.ts" +import * as OpenAiSchema from "./OpenAiSchema.ts" + +// ============================================================================= +// Service Interface +// ============================================================================= + +/** + * Effect service interface for the handwritten OpenAI client. + * + * **Details** + * + * Provides the configured HTTP client plus helpers for Responses API calls, streaming Responses events, and embeddings. Transport and schema decoding failures are mapped to `AiError`. + * + * @category services + * @since 4.0.0 + */ +export interface Service { + /** + * The transformed HTTP client used by this service. + */ + readonly client: HttpClient.HttpClient + + /** + * Create a response using the OpenAI responses endpoint. + */ + readonly createResponse: ( + options: typeof OpenAiSchema.CreateResponse.Encoded + ) => Effect.Effect< + readonly [body: typeof OpenAiSchema.Response.Type, response: HttpClientResponse.HttpClientResponse], + AiError.AiError + > + + /** + * Create a streaming response using the OpenAI responses endpoint. + */ + readonly createResponseStream: ( + options: Omit + ) => Effect.Effect< + readonly [ + response: HttpClientResponse.HttpClientResponse, + stream: Stream.Stream + ], + AiError.AiError + > + + /** + * Create embeddings using the OpenAI embeddings endpoint. + */ + readonly createEmbedding: ( + options: typeof OpenAiSchema.CreateEmbeddingRequest.Encoded + ) => Effect.Effect +} + +// ============================================================================= +// Service Identifier +// ============================================================================= + +/** + * Service tag for the OpenAI client. + * + * **When to use** + * + * Use when accessing or providing the OpenAI client service through Effect's + * context. + * + * @see {@link make} for constructing an OpenAI client effectfully + * @see {@link layer} for providing a client from explicit options + * @see {@link layerConfig} for providing a client from `Config` + * + * @category services + * @since 4.0.0 + */ +export class OpenAiClient extends Context.Service()( + "@humanlayer/effect-ai-openai/OpenAiClient" +) {} + +// ============================================================================= +// Options +// ============================================================================= + +/** + * Options for configuring the OpenAI client. + * + * @category options + * @since 4.0.0 + */ +export type Options = { + /** + * The OpenAI API key. + */ + readonly apiKey?: Redacted.Redacted | undefined + + /** + * The base URL for the OpenAI API. + * + * @default "https://api.openai.com/v1" + */ + readonly apiUrl?: string | undefined + + /** + * Optional organization ID for multi-org accounts. + */ + readonly organizationId?: Redacted.Redacted | undefined + + /** + * Optional project ID for project-scoped requests. + */ + readonly projectId?: Redacted.Redacted | undefined + + /** + * Optional transformer for the HTTP client. + */ + readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined +} + +// ============================================================================= +// Constructor +// ============================================================================= + +const RedactedOpenAiHeaders = { + OpenAiOrganization: "OpenAI-Organization", + OpenAiProject: "OpenAI-Project" +} + +const withRedactedHeaders = Effect.updateService( + Headers.CurrentRedactedNames, + Array.appendAll(Object.values(RedactedOpenAiHeaders)) +) + +/** + * Creates an OpenAI client service with the given options. + * + * **When to use** + * + * Use when you need the OpenAI client service value inside an effect. + * + * **Details** + * + * The returned service uses the current `HttpClient`, prepends `apiUrl` or + * `https://api.openai.com/v1`, adds the bearer token and optional OpenAI + * organization/project headers, accepts JSON responses, filters for successful + * HTTP statuses, and applies `transformClient` when provided. + * + * **Gotchas** + * + * A scoped `OpenAiConfig.withClientTransform` is applied when request helpers + * run, after the `transformClient` option supplied to `make`. + * + * @see {@link layer} for providing this client from explicit options + * @see {@link layerConfig} for loading client settings from `Config` + * + * @category constructors + * @since 4.0.0 + */ +export const make = Effect.fnUntraced( + function*( + options: Options + ): Effect.fn.Return { + const baseClient = yield* HttpClient.HttpClient + const apiUrl = options.apiUrl ?? "https://api.openai.com/v1" + + const httpClient = baseClient.pipe( + HttpClient.mapRequest(Function.flow( + HttpClientRequest.prependUrl(apiUrl), + options.apiKey + ? HttpClientRequest.bearerToken(Redacted.value(options.apiKey)) + : identity, + options.organizationId + ? HttpClientRequest.setHeader( + RedactedOpenAiHeaders.OpenAiOrganization, + Redacted.value(options.organizationId) + ) + : identity, + options.projectId + ? HttpClientRequest.setHeader( + RedactedOpenAiHeaders.OpenAiProject, + Redacted.value(options.projectId) + ) + : identity, + HttpClientRequest.acceptJson + )), + HttpClient.filterStatusOk, + options.transformClient + ? options.transformClient + : identity + ) + + const resolveHttpClient = Effect.map( + OpenAiConfig.getOrUndefined, + (config) => + Predicate.isNotUndefined(config?.transformClient) + ? config.transformClient(httpClient) + : httpClient + ) + + const decodeResponse = HttpClientResponse.schemaBodyJson(OpenAiSchema.Response) + + const createResponse = ( + payload: typeof OpenAiSchema.CreateResponse.Encoded + ): Effect.Effect< + [body: typeof OpenAiSchema.Response.Type, response: HttpClientResponse.HttpClientResponse], + AiError.AiError + > => + resolveHttpClient.pipe( + Effect.flatMap((client) => + client.execute(HttpClientRequest.post("/responses", { + body: HttpBody.jsonUnsafe(payload) + })).pipe( + Effect.flatMap((response) => + decodeResponse(response).pipe( + Effect.map((body): [typeof OpenAiSchema.Response.Type, HttpClientResponse.HttpClientResponse] => [ + body, + response + ]) + ) + ), + Effect.catchTags({ + HttpClientError: (error) => Errors.mapHttpClientError(error, "createResponse"), + SchemaError: (error) => Effect.fail(Errors.mapSchemaError(error, "createResponse")) + }) + ) + ), + withRedactedHeaders + ) + + const buildResponseStream = ( + response: HttpClientResponse.HttpClientResponse + ): [ + HttpClientResponse.HttpClientResponse, + Stream.Stream + ] => { + const stream = response.stream.pipe( + Stream.decodeText(), + Stream.pipeThroughChannel(Sse.decodeDataSchema(OpenAiSchema.ResponseStreamEvent)), + Stream.takeUntil((event) => + event.data.type === "response.completed" || + event.data.type === "response.incomplete" || + event.data.type === "response.failed" + ), + Stream.map((event) => event.data), + Stream.catchTags({ + // TODO: handle SSE retries + Retry: (error) => Stream.die(error), + SseError: (error) => Stream.fail(Errors.mapSseError(error, "createResponseStream")), + HttpClientError: (error) => Stream.fromEffect(Errors.mapHttpClientError(error, "createResponseStream")), + SchemaError: (error) => Stream.fail(Errors.mapSchemaError(error, "createResponseStream")) + }) + ) + return [response, stream] + } + + const createResponseStream: Service["createResponseStream"] = (payload) => + Effect.contextWith((services) => { + const socket = Context.getOrUndefined(services, OpenAiSocket) + if (socket) return socket.createResponseStream(payload) + return resolveHttpClient.pipe( + Effect.flatMap((client) => + client.execute(HttpClientRequest.post("/responses", { + body: HttpBody.jsonUnsafe({ ...payload, stream: true }) + })).pipe( + Effect.map(buildResponseStream), + Effect.catchTag( + "HttpClientError", + (error) => Errors.mapHttpClientError(error, "createResponseStream") + ) + ) + ), + withRedactedHeaders + ) + }) + + const decodeEmbedding = HttpClientResponse.schemaBodyJson(OpenAiSchema.CreateEmbeddingResponse) + + const createEmbedding = ( + payload: typeof OpenAiSchema.CreateEmbeddingRequest.Encoded + ): Effect.Effect => + resolveHttpClient.pipe( + Effect.flatMap((client) => + client.execute(HttpClientRequest.post("/embeddings", { + body: HttpBody.jsonUnsafe(payload) + })).pipe( + Effect.flatMap(decodeEmbedding), + Effect.catchTags({ + HttpClientError: (error) => Errors.mapHttpClientError(error, "createEmbedding"), + SchemaError: (error) => Effect.fail(Errors.mapSchemaError(error, "createEmbedding")) + }) + ) + ), + withRedactedHeaders + ) + + return OpenAiClient.of({ + client: httpClient, + createResponse, + createResponseStream, + createEmbedding + }) + }, + withRedactedHeaders +) + +// ============================================================================= +// Layers +// ============================================================================= + +/** + * Creates a layer for the OpenAI client with the given options. + * + * **When to use** + * + * Use when you already have explicit `Options` values, such as an API key or + * custom API URL, and want to provide `OpenAiClient` as a `Layer`. + * + * @see {@link make} for constructing the client service effectfully + * @see {@link layerConfig} for loading client settings from `Config` + * + * @category layers + * @since 4.0.0 + */ +export const layer = (options: Options): Layer.Layer => + Layer.effect(OpenAiClient, make(options)) + +/** + * Creates a layer for the OpenAI client from provided `Config` values. + * + * **When to use** + * + * Use when you need client settings for OpenAI-compatible APIs to be read from + * Effect `Config` values while providing `OpenAiClient` as a `Layer`. + * + * **Details** + * + * Only config values supplied in `options` are loaded. Omitted fields are + * passed to `make` as `undefined`, and `transformClient` is forwarded as a + * plain option. + * + * @see {@link make} for constructing the client service effectfully + * @see {@link layer} for providing the client from already-resolved options + * + * @category layers + * @since 4.0.0 + */ +export const layerConfig = (options?: { + /** + * The config value to load for the API key. + */ + readonly apiKey?: Config.Config | undefined> | undefined + + /** + * The config value to load for the API URL. + */ + readonly apiUrl?: Config.Config | undefined + + /** + * The config value to load for the organization ID. + */ + readonly organizationId?: Config.Config | undefined> | undefined + + /** + * The config value to load for the project ID. + */ + readonly projectId?: Config.Config | undefined> | undefined + + /** + * Optional transformer for the HTTP client. + */ + readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined +}): Layer.Layer => + Layer.effect( + OpenAiClient, + Effect.gen(function*() { + const apiKey = Predicate.isNotUndefined(options?.apiKey) + ? yield* options.apiKey : + undefined + const apiUrl = Predicate.isNotUndefined(options?.apiUrl) + ? yield* options.apiUrl : + undefined + const organizationId = Predicate.isNotUndefined(options?.organizationId) + ? yield* options.organizationId + : undefined + const projectId = Predicate.isNotUndefined(options?.projectId) + ? yield* options.projectId : + undefined + return yield* make({ + apiKey, + apiUrl, + organizationId, + projectId, + transformClient: options?.transformClient + }) + }) + ) + +// ============================================================================= +// Websocket mode +// ============================================================================= + +/** + * Response stream event emitted by the OpenAI Responses API. + * + * @category models + * @since 4.0.0 + */ +export type ResponseStreamEvent = typeof OpenAiSchema.ResponseStreamEvent.Type + +/** + * Service for creating OpenAI response streams over a WebSocket connection. + * + * **When to use** + * + * Use when you need direct access to the WebSocket-backed response streaming + * service rather than wrapping an effect with WebSocket mode. + * + * **Details** + * + * `createResponseStream` sends a `response.create` message over the WebSocket + * connection and returns an HTTP response together with a stream of + * `ResponseStreamEvent` values. + * + * **Gotchas** + * + * WebSocket response streams are serialized to one request at a time by the + * shared socket service. + * + * @see {@link withWebSocketMode} for enabling WebSocket mode for one effect + * @see {@link layerWebSocketMode} for providing WebSocket mode through a layer + * + * @category services + * @since 4.0.0 + */ +export class OpenAiSocket extends Context.Service + ) => Effect.Effect< + readonly [ + response: HttpClientResponse.HttpClientResponse, + stream: Stream.Stream + ], + AiError.AiError + > +}>()("@humanlayer/effect-ai-openai/OpenAiClient/OpenAiSocket") {} + +const makeSocket = Effect.gen(function*() { + const client = yield* OpenAiClient + const tracker = yield* ResponseIdTracker.make + const socketScope = yield* Effect.scope + const makeRequest = Effect.flatMap( + OpenAiConfig.getOrUndefined, + (config) => { + const httpClient = Predicate.isNotUndefined(config?.transformClient) + ? config.transformClient(client.client) + : client.client + return Effect.orDie(httpClient.preprocess(HttpClientRequest.post("/responses"))) + } + ) + const makeWebSocket = yield* Socket.WebSocketConstructor + + const decoder = new TextDecoder() + + const queueRef: RcRef.RcRef< + { + readonly send: (message: typeof OpenAiSchema.CreateResponse.Encoded) => Effect.Effect + readonly incoming: Queue.Dequeue + } + > = yield* RcRef.make({ + idleTimeToLive: 60_000, + acquire: Effect.gen(function*() { + const scope = yield* Effect.scope + const request = yield* makeRequest + const socket = yield* Socket.makeWebSocket(request.url.replace(/^http/, "ws")).pipe( + Effect.provideService(Socket.WebSocketConstructor, (url) => + makeWebSocket(url, { + headers: request.headers + } as any)) + ) + const write = yield* socket.writer + + yield* Scope.addFinalizerExit(scope, () => { + tracker.clearUnsafe() + return Effect.void + }) + + const incoming = yield* Queue.unbounded() + const send = (message: typeof OpenAiSchema.CreateResponse.Encoded) => + write(JSON.stringify({ + type: "response.create", + ...message + })).pipe( + Effect.mapError((_error) => + AiError.make({ + module: "OpenAiClient", + method: "createResponseStream", + reason: new AiError.NetworkError({ + reason: "TransportError", + request: { + method: "POST", + url: request.url, + urlParams: [], + hash: undefined, + headers: request.headers + }, + description: "Failed to send message over WebSocket" + }) + }) + ) + ) + + yield* socket.runRaw((msg) => { + const text = typeof msg === "string" ? msg : decoder.decode(msg) + try { + const event = decodeEvent(text) + if (event.type === "error" && "status" in event) { + const status = Number(event.status) + const error = "error" in event ? event.error as typeof ErrorEvent.Type.error : event + const json = JSON.stringify(error) + return Effect.fail( + AiError.make({ + module: "OpenAiClient", + method: "createResponseStream", + reason: AiError.reasonFromHttpStatus({ + description: json, + status: isNaN(status) ? + Object.hasOwn(errorTypeToStatus, error.type) + ? errorTypeToStatus[error.type] + : 500 : + status, + metadata: error as any, + http: { + body: json, + request: { + method: "POST", + url: request.url, + urlParams: [], + hash: undefined, + headers: request.headers + } + } + }) + }) + ) + } + Queue.offerUnsafe(incoming, event) + } catch {} + }).pipe( + Effect.catchTag("SocketError", (error) => + AiError.make({ + module: "OpenAiClient", + method: "createResponseStream", + reason: new AiError.NetworkError({ + reason: "TransportError", + request: { + method: "POST", + url: request.url, + urlParams: [], + hash: undefined, + headers: request.headers + }, + description: error.message + }) + })), + Effect.catchCause((cause) => Queue.failCause(incoming, cause)), + Effect.ensuring(Effect.forkIn(RcRef.invalidate(queueRef), socketScope, { + startImmediately: true + })), + Effect.forkScoped({ startImmediately: true }) + ) + + return { send, incoming } as const + }) + }) + + // Prime the websocket + yield* Effect.scoped(RcRef.get(queueRef)) + + // Websocket mode only allows one request at a time + const semaphore = Semaphore.makeUnsafe(1) + const request = yield* makeRequest + + return OpenAiSocket.context({ + createResponseStream(options) { + const stream = Stream.unwrap(Effect.gen(function*() { + const scope = yield* Effect.scope + yield* Effect.acquireRelease( + semaphore.take(1), + () => semaphore.release(1), + { interruptible: true } + ) + const { send, incoming } = yield* RcRef.get(queueRef) + let done = false + + yield* Scope.addFinalizerExit( + scope, + () => done ? Effect.void : RcRef.invalidate(queueRef) + ) + + yield* send(options).pipe( + Effect.forkScoped({ startImmediately: true }) + ) + + return Stream.fromQueue(incoming).pipe( + Stream.takeUntil((e) => { + done = e.type === "response.completed" || e.type === "response.incomplete" || e.type === "response.failed" + return done + }) + ) + })) + + return Effect.succeed([ + HttpClientResponse.fromWeb(request, new Response()), + stream + ]) + } + }).pipe( + Context.add(ResponseIdTracker.ResponseIdTracker, tracker) + ) +}) + +const ErrorEvent = Schema.Struct({ + type: Schema.Literal("error"), + status: Schema.Int.pipe( + Schema.withDecodingDefault(Effect.succeed(500)) + ), + error: Schema.Struct({ + type: Schema.String, + message: Schema.String + }) +}) + +const errorTypeToStatus: Record = { + invalid_request_error: 400, + invalid_api_key_error: 401, + insufficient_quota_error: 429, + rate_limit_error: 429, + service_unavailable_error: 503 +} + +const AllEvents = Schema.Union([ErrorEvent, OpenAiSchema.ResponseStreamEvent]) +const decodeEvent = Schema.decodeUnknownSync(Schema.fromJsonString(AllEvents)) + +/** + * Uses OpenAI's WebSocket mode for response streams within the provided effect. + * + * **When to use** + * + * Use to enable WebSocket mode around one effect that creates OpenAI response + * streams. + * + * **Gotchas** + * + * This only works with the following WebSocket constructor layers: + * + * - `NodeSocket.layerWebSocketConstructorWS` + * - `BunSocket.layerWebSocketConstructor` + * + * These constructor layers support the non-standard options needed to set the + * Authorization header. + * + * @see {@link layerWebSocketMode} for providing WebSocket mode through a layer + * @see {@link OpenAiSocket} for direct access to the WebSocket-backed streaming service + * + * @category providing services + * @since 4.0.0 + */ +export const withWebSocketMode = ( + effect: Effect.Effect +): Effect.Effect< + A, + E, + Exclude | OpenAiClient | Socket.WebSocketConstructor +> => + Effect.scopedWith((scope) => + Effect.flatMap( + Scope.provide(makeSocket, scope), + (services) => Effect.provideContext(effect, services) + ) + ) + +/** + * Uses OpenAI's websocket mode for all responses that use the Layer. + * + * **When to use** + * + * Use to provide WebSocket mode through layer composition for effects that use + * OpenAI response streaming. + * + * **Gotchas** + * + * This only works with the following WebSocket constructor layers: + * + * - `NodeSocket.layerWebSocketConstructorWS` + * - `BunSocket.layerWebSocketConstructor` + * + * These constructor layers support the non-standard options needed to set the + * Authorization header. + * + * @see {@link withWebSocketMode} for enabling WebSocket mode around a single effect + * + * @category layers + * @since 4.0.0 + */ +export const layerWebSocketMode: Layer.Layer< + OpenAiSocket | ResponseIdTracker.ResponseIdTracker, + never, + OpenAiClient | Socket.WebSocketConstructor +> = Layer.effectContext(makeSocket) diff --git a/packages/effect-ai-openai/src/OpenAiClientGenerated.ts b/packages/effect-ai-openai/src/OpenAiClientGenerated.ts new file mode 100644 index 0000000..ca41345 --- /dev/null +++ b/packages/effect-ai-openai/src/OpenAiClientGenerated.ts @@ -0,0 +1,204 @@ +/** + * @since 4.0.0 + */ +import * as Array from "effect/Array" +import type * as Config from "effect/Config" +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { identity } from "effect/Function" +import * as Function from "effect/Function" +import * as Layer from "effect/Layer" +import * as Predicate from "effect/Predicate" +import * as Redacted from "effect/Redacted" +import * as Headers from "effect/unstable/http/Headers" +import * as HttpClient from "effect/unstable/http/HttpClient" +import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import * as Generated from "./Generated.ts" +import { OpenAiConfig } from "./OpenAiConfig.ts" + +// ============================================================================= +// Service Identifier +// ============================================================================= + +/** + * Service identifier for the generated OpenAI client. + * + * @since 4.0.0 + * @category service + */ +export class OpenAiClientGenerated extends Context.Service()( + "@humanlayer/effect-ai-openai/OpenAiClientGenerated" +) {} + +// ============================================================================= +// Options +// ============================================================================= + +/** + * Options for configuring the generated OpenAI client. + * + * @since 4.0.0 + * @category options + */ +export type Options = { + /** + * The OpenAI API key. + */ + readonly apiKey?: Redacted.Redacted | undefined + + /** + * The base URL for the OpenAI API. + * + * @default "https://api.openai.com/v1" + */ + readonly apiUrl?: string | undefined + + /** + * Optional organization ID for multi-org accounts. + */ + readonly organizationId?: Redacted.Redacted | undefined + + /** + * Optional project ID for project-scoped requests. + */ + readonly projectId?: Redacted.Redacted | undefined + + /** + * Optional transformer for the HTTP client. + */ + readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined +} + +const RedactedOpenAiHeaders = { + OpenAiOrganization: "OpenAI-Organization", + OpenAiProject: "OpenAI-Project" +} + +const withRedactedHeaders = Effect.updateService( + Headers.CurrentRedactedNames, + Array.appendAll(Object.values(RedactedOpenAiHeaders)) +) + +// ============================================================================= +// Constructor +// ============================================================================= + +/** + * Creates a generated OpenAI client service with the given options. + * + * @since 4.0.0 + * @category constructors + */ +export const make = Effect.fnUntraced( + function*(options: Options): Effect.fn.Return { + const baseClient = yield* HttpClient.HttpClient + const apiUrl = options.apiUrl ?? "https://api.openai.com/v1" + + const httpClient = baseClient.pipe( + HttpClient.mapRequest(Function.flow( + HttpClientRequest.prependUrl(apiUrl), + options.apiKey + ? HttpClientRequest.bearerToken(Redacted.value(options.apiKey)) + : identity, + options.organizationId + ? HttpClientRequest.setHeader( + RedactedOpenAiHeaders.OpenAiOrganization, + Redacted.value(options.organizationId) + ) + : identity, + options.projectId + ? HttpClientRequest.setHeader( + RedactedOpenAiHeaders.OpenAiProject, + Redacted.value(options.projectId) + ) + : identity, + HttpClientRequest.acceptJson + )), + options.transformClient + ? options.transformClient + : identity + ) + + return Generated.make(httpClient, { + transformClient: Effect.fnUntraced(function*(client) { + const config = yield* OpenAiConfig.getOrUndefined + if (Predicate.isNotUndefined(config?.transformClient)) { + return config.transformClient(client) + } + return client + }) + }) + }, + withRedactedHeaders +) + +// ============================================================================= +// Layers +// ============================================================================= + +/** + * Creates a layer for the generated OpenAI client with the given options. + * + * @since 4.0.0 + * @category layers + */ +export const layer = (options: Options): Layer.Layer => + Layer.effect(OpenAiClientGenerated, make(options)) + +/** + * Creates a layer for the generated OpenAI client, loading the requisite + * configuration via Effect's `Config` module. + * + * @since 4.0.0 + * @category layers + */ +export const layerConfig = (options?: { + /** + * The config value to load for the API key. + */ + readonly apiKey?: Config.Config | undefined> | undefined + + /** + * The config value to load for the API URL. + */ + readonly apiUrl?: Config.Config | undefined + + /** + * The config value to load for the organization ID. + */ + readonly organizationId?: Config.Config | undefined> | undefined + + /** + * The config value to load for the project ID. + */ + readonly projectId?: Config.Config | undefined> | undefined + + /** + * Optional transformer for the HTTP client. + */ + readonly transformClient?: ((client: HttpClient.HttpClient) => HttpClient.HttpClient) | undefined +}): Layer.Layer => + Layer.effect( + OpenAiClientGenerated, + Effect.gen(function*() { + const apiKey = Predicate.isNotUndefined(options?.apiKey) + ? yield* options.apiKey : + undefined + const apiUrl = Predicate.isNotUndefined(options?.apiUrl) + ? yield* options.apiUrl : + undefined + const organizationId = Predicate.isNotUndefined(options?.organizationId) + ? yield* options.organizationId + : undefined + const projectId = Predicate.isNotUndefined(options?.projectId) + ? yield* options.projectId : + undefined + return yield* make({ + apiKey, + apiUrl, + organizationId, + projectId, + transformClient: options?.transformClient + }) + }) + ) diff --git a/packages/effect-ai-openai/src/OpenAiConfig.ts b/packages/effect-ai-openai/src/OpenAiConfig.ts new file mode 100644 index 0000000..3d71226 --- /dev/null +++ b/packages/effect-ai-openai/src/OpenAiConfig.ts @@ -0,0 +1,142 @@ +/** + * The `OpenAiConfig` module lets a workflow temporarily customize the HTTP + * client used by `@humanlayer/effect-ai-openai` request helpers. OpenAI client, language + * model, and embedding code read this scoped transform when they execute + * provider calls. + * + * @since 4.0.0 + */ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { dual } from "effect/Function" +import type { HttpClient } from "effect/unstable/http/HttpClient" + +/** + * Context service for scoped OpenAI configuration used by provider operations. + * + * **When to use** + * + * Use to provide scoped OpenAI client configuration, such as an HTTP client + * transform, to OpenAI provider operations without passing it through each call. + * + * @see {@link withClientTransform} for scoping an HTTP client transformation + * + * @category services + * @since 4.0.0 + */ +export class OpenAiConfig extends Context.Service< + OpenAiConfig, + OpenAiConfig.Service +>()("@humanlayer/effect-ai-openai/OpenAiConfig") { + /** + * Gets the configured OpenAI service from the current context when present. + * + * @since 4.0.0 + */ + static readonly getOrUndefined: Effect.Effect = Effect.map( + Effect.context(), + Context.getOrUndefined(OpenAiConfig) + ) +} + +/** + * Types used by the `OpenAiConfig` context service. + * + * @since 4.0.0 + */ +export declare namespace OpenAiConfig { + /** + * Configuration values read by OpenAI provider operations when executing + * requests. + * + * @category services + * @since 4.0.0 + */ + export interface Service { + readonly transformClient?: ((client: HttpClient) => HttpClient) | undefined + } +} + +/** + * Provides a scoped transform for the OpenAI HTTP client used by provider + * operations. + * + * **When to use** + * + * Use when you need temporary OpenAI HTTP client customization for a single + * effect or workflow without rebuilding the client layer. + * + * **Details** + * + * Supports both data-first and data-last forms. The transform is stored in the + * scoped `OpenAiConfig` service and read by OpenAI provider operations while + * running the supplied effect. + * + * **Gotchas** + * + * If a transform is already present in the scoped config, this helper replaces + * it. Compose transforms manually when both should apply. + * + * @category configuration + * @since 4.0.0 + */ +export const withClientTransform: { + /** + * Provides a scoped transform for the OpenAI HTTP client used by provider + * operations. + * + * **When to use** + * + * Use when you need temporary OpenAI HTTP client customization for a single + * effect or workflow without rebuilding the client layer. + * + * **Details** + * + * Supports both data-first and data-last forms. The transform is stored in the + * scoped `OpenAiConfig` service and read by OpenAI provider operations while + * running the supplied effect. + * + * **Gotchas** + * + * If a transform is already present in the scoped config, this helper replaces + * it. Compose transforms manually when both should apply. + * + * @category configuration + * @since 4.0.0 + */ + (transform: (client: HttpClient) => HttpClient): (self: Effect.Effect) => Effect.Effect + /** + * Provides a scoped transform for the OpenAI HTTP client used by provider + * operations. + * + * **When to use** + * + * Use when you need temporary OpenAI HTTP client customization for a single + * effect or workflow without rebuilding the client layer. + * + * **Details** + * + * Supports both data-first and data-last forms. The transform is stored in the + * scoped `OpenAiConfig` service and read by OpenAI provider operations while + * running the supplied effect. + * + * **Gotchas** + * + * If a transform is already present in the scoped config, this helper replaces + * it. Compose transforms manually when both should apply. + * + * @category configuration + * @since 4.0.0 + */ + ( + self: Effect.Effect, + transform: (client: HttpClient) => HttpClient + ): Effect.Effect +} = dual(2, ( + self: Effect.Effect, + transformClient: (client: HttpClient) => HttpClient +) => + Effect.flatMap( + OpenAiConfig.getOrUndefined, + (config) => Effect.provideService(self, OpenAiConfig, { ...config, transformClient }) + )) diff --git a/packages/effect-ai-openai/src/OpenAiEmbeddingModel.ts b/packages/effect-ai-openai/src/OpenAiEmbeddingModel.ts new file mode 100644 index 0000000..5072b74 --- /dev/null +++ b/packages/effect-ai-openai/src/OpenAiEmbeddingModel.ts @@ -0,0 +1,331 @@ +/** + * The `OpenAiEmbeddingModel` module provides the OpenAI implementation of + * Effect AI's `EmbeddingModel` service. It sends embedding requests through + * `OpenAiClient`, exposes constructors for layers and `AiModel` values, + * supports scoped request configuration overrides, and checks that OpenAI + * returns one numeric vector for each requested input. + * + * @since 4.0.0 + */ +import * as Context from "effect/Context" +import * as Effect from "effect/Effect" +import { dual } from "effect/Function" +import * as Layer from "effect/Layer" +import type { Simplify } from "effect/Types" +import * as AiError from "effect/unstable/ai/AiError" +import * as EmbeddingModel from "effect/unstable/ai/EmbeddingModel" +import * as AiModel from "effect/unstable/ai/Model" +import { OpenAiClient } from "./OpenAiClient.ts" +import type * as OpenAiSchema from "./OpenAiSchema.ts" + +/** + * Model identifiers supported by OpenAI's embeddings API. + * + * @category models + * @since 4.0.0 + */ +export type Model = "text-embedding-ada-002" | "text-embedding-3-small" | "text-embedding-3-large" + +/** + * Context service for OpenAI embedding model configuration. + * + * **When to use** + * + * Use when you need scoped OpenAI request defaults or overrides for embedding + * requests from Effect context. + * + * **Details** + * + * The service stores the OpenAI create-embedding request payload without + * `input`, carrying options such as `model`, `dimensions`, `encoding_format`, + * and `user`. + * + * @see {@link withConfigOverride} for scoping embedding request overrides + * + * @category services + * @since 4.0.0 + */ +export class Config extends Context.Service< + Config, + Simplify< + & Partial< + Omit< + typeof OpenAiSchema.CreateEmbeddingRequest.Encoded, + "input" + > + > + & { + readonly [x: string]: unknown + } + > +>()("@humanlayer/effect-ai-openai/OpenAiEmbeddingModel/Config") {} + +/** + * Creates an `AiModel` for an OpenAI embedding model with its configured vector dimensions. + * + * **When to use** + * + * Use to provide an OpenAI `EmbeddingModel` and its `Dimensions` service to an + * Effect program. + * + * @see {@link layer} for providing only the embedding model service + * @see {@link withConfigOverride} for scoped request configuration overrides + * + * @category constructors + * @since 4.0.0 + */ +export const model = ( + model: (string & {}) | Model, + options: { + readonly dimensions: number + readonly config?: Omit + } +): AiModel.Model<"openai", EmbeddingModel.EmbeddingModel | EmbeddingModel.Dimensions, OpenAiClient> => + AiModel.make( + "openai", + model, + Layer.merge( + layer({ + model, + config: { + ...options.config, + dimensions: options.dimensions + } + }), + Layer.succeed(EmbeddingModel.Dimensions, options.dimensions) + ) + ) + +/** + * Creates an OpenAI embedding model service. + * + * **When to use** + * + * Use to construct the `EmbeddingModel.Service` effectfully when + * `OpenAiClient` is already available in the environment. + * + * **Details** + * + * The `model` option is sent with each embedding request. Constructor `config` + * supplies create-embedding request fields other than `model` and `input`, and + * scoped overrides from `withConfigOverride` are merged last for each request. + * + * **Gotchas** + * + * The service expects numeric embedding vectors. It fails with + * `InvalidOutputError` when the provider returns base64 embeddings, + * out-of-range indexes, duplicate indexes, or an unexpected number of + * embeddings. + * + * @see {@link layer} for providing the embedding model service as a layer + * @see {@link model} for creating an `AiModel` that also provides dimensions + * @see {@link withConfigOverride} for scoped request configuration overrides + * + * @category constructors + * @since 4.0.0 + */ +export const make = Effect.fnUntraced(function*({ model, config: providerConfig }: { + readonly model: (string & {}) | Model + readonly config?: Omit | undefined +}): Effect.fn.Return { + const client = yield* OpenAiClient + + const makeConfig = Effect.contextWith((services: Context.Context) => + Effect.succeed({ model, ...providerConfig, ...Context.getOrUndefined(services, Config) }) + ) + + return yield* EmbeddingModel.make({ + embedMany: Effect.fnUntraced(function*({ inputs }) { + const config = yield* makeConfig + const response = yield* client.createEmbedding({ ...config, input: inputs }) + return yield* mapProviderResponse(inputs.length, response) + }) + }) +}) + +/** + * Creates a layer for the OpenAI embedding model. + * + * **When to use** + * + * Use when composing application layers and you want OpenAI to satisfy + * `EmbeddingModel.EmbeddingModel` while supplying `OpenAiClient` from another + * layer. + * + * **Gotchas** + * + * Use the default floating-point embedding format. The service expects numeric + * vectors and fails with `InvalidOutputError` if OpenAI returns base64 + * embeddings. + * + * @see {@link make} for constructing the embedding model service effectfully + * @see {@link model} for creating an `AiModel` that also provides embedding dimensions + * + * @category layers + * @since 4.0.0 + */ +export const layer = (options: { + readonly model: (string & {}) | Model + readonly config?: Omit | undefined +}): Layer.Layer => + Layer.effect(EmbeddingModel.EmbeddingModel, make(options)) + +/** + * Provides config overrides for OpenAI embedding model operations. + * + * **When to use** + * + * Use when you need scoped OpenAI embedding request defaults for a single + * effect or workflow without rebuilding the embedding model service. + * + * **Details** + * + * Supports both data-first and data-last forms. Existing scoped config is read + * first, then the provided overrides are applied so override fields take + * precedence. + * + * @see {@link Config} for the scoped embedding request configuration service + * + * @category configuration + * @since 4.0.0 + */ +export const withConfigOverride: { + /** + * Provides config overrides for OpenAI embedding model operations. + * + * **When to use** + * + * Use when you need scoped OpenAI embedding request defaults for a single + * effect or workflow without rebuilding the embedding model service. + * + * **Details** + * + * Supports both data-first and data-last forms. Existing scoped config is read + * first, then the provided overrides are applied so override fields take + * precedence. + * + * @see {@link Config} for the scoped embedding request configuration service + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service): (self: Effect.Effect) => Effect.Effect> + /** + * Provides config overrides for OpenAI embedding model operations. + * + * **When to use** + * + * Use when you need scoped OpenAI embedding request defaults for a single + * effect or workflow without rebuilding the embedding model service. + * + * **Details** + * + * Supports both data-first and data-last forms. Existing scoped config is read + * first, then the provided overrides are applied so override fields take + * precedence. + * + * @see {@link Config} for the scoped embedding request configuration service + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service): Effect.Effect> +} = dual< + /** + * Provides config overrides for OpenAI embedding model operations. + * + * **When to use** + * + * Use when you need scoped OpenAI embedding request defaults for a single + * effect or workflow without rebuilding the embedding model service. + * + * **Details** + * + * Supports both data-first and data-last forms. Existing scoped config is read + * first, then the provided overrides are applied so override fields take + * precedence. + * + * @see {@link Config} for the scoped embedding request configuration service + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service) => (self: Effect.Effect) => Effect.Effect>, + /** + * Provides config overrides for OpenAI embedding model operations. + * + * **When to use** + * + * Use when you need scoped OpenAI embedding request defaults for a single + * effect or workflow without rebuilding the embedding model service. + * + * **Details** + * + * Supports both data-first and data-last forms. Existing scoped config is read + * first, then the provided overrides are applied so override fields take + * precedence. + * + * @see {@link Config} for the scoped embedding request configuration service + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service) => Effect.Effect> +>(2, (self, overrides) => + Effect.flatMap( + Effect.serviceOption(Config), + (config) => + Effect.provideService(self, Config, { + ...(config._tag === "Some" ? config.value : {}), + ...overrides + }) + )) + +const mapProviderResponse = ( + inputLength: number, + response: typeof OpenAiSchema.CreateEmbeddingResponse.Type +): Effect.Effect => { + if (response.data.length !== inputLength) { + return Effect.fail( + invalidOutput("Provider returned " + response.data.length + " embeddings but expected " + inputLength) + ) + } + + const results = new Array>(inputLength) + const seen = new Set() + + for (const entry of response.data) { + if (!Number.isInteger(entry.index) || entry.index < 0 || entry.index >= inputLength) { + return Effect.fail(invalidOutput("Provider returned invalid embedding index: " + entry.index)) + } + if (seen.has(entry.index)) { + return Effect.fail(invalidOutput("Provider returned duplicate embedding index: " + entry.index)) + } + if (!Array.isArray(entry.embedding)) { + return Effect.fail(invalidOutput("Provider returned non-vector embedding at index " + entry.index)) + } + + seen.add(entry.index) + results[entry.index] = [...entry.embedding] + } + + if (seen.size !== inputLength) { + return Effect.fail( + invalidOutput("Provider returned embeddings for " + seen.size + " inputs but expected " + inputLength) + ) + } + + return Effect.succeed({ + results, + usage: { + inputTokens: response.usage?.prompt_tokens + } + }) +} + +const invalidOutput = (description: string): AiError.AiError => + AiError.make({ + module: "OpenAiEmbeddingModel", + method: "embedMany", + reason: new AiError.InvalidOutputError({ description }) + }) diff --git a/packages/effect-ai-openai/src/OpenAiError.ts b/packages/effect-ai-openai/src/OpenAiError.ts new file mode 100644 index 0000000..5e2a96d --- /dev/null +++ b/packages/effect-ai-openai/src/OpenAiError.ts @@ -0,0 +1,242 @@ +/** + * OpenAI error metadata augmentation. + * + * Provides OpenAI-specific metadata fields for AI error types through module + * augmentation, enabling typed access to OpenAI error details. + * + * @since 4.0.0 + */ + +/** + * OpenAI-specific error metadata fields. + * + * @category models + * @since 4.0.0 + */ +export type OpenAiErrorMetadata = { + /** + * The OpenAI error code returned by the API. + */ + readonly errorCode: string | null + /** + * The OpenAI error type returned by the API. + */ + readonly errorType: string | null + /** + * The unique request ID for debugging with OpenAI support. + */ + readonly requestId: string | null +} + +/** + * OpenAI-specific rate limit metadata fields. + * + * **Details** + * + * Extends base error metadata with rate limit specific information from + * OpenAI's rate limit headers. + * + * @category models + * @since 4.0.0 + */ +export type OpenAiRateLimitMetadata = OpenAiErrorMetadata & { + /** + * The rate limit type (e.g. "requests", "tokens"). + */ + readonly limit: string | null + /** + * Number of remaining requests in the current window. + */ + readonly remaining: number | null + /** + * Time until the request rate limit resets. + */ + readonly resetRequests: string | null + /** + * Time until the token rate limit resets. + */ + readonly resetTokens: string | null +} + +declare module "effect/unstable/ai/AiError" { + /** + * OpenAI metadata attached to `RateLimitError` values. + * + * **Details** + * + * Captures OpenAI error details together with rate limit header information + * from responses where the provider rejected the request because a limit was + * reached. + * + * @category models + * @since 4.0.0 + */ + export interface RateLimitErrorMetadata { + /** + * OpenAI-specific details for the rate limit response. + */ + readonly openai?: OpenAiRateLimitMetadata | null + } + + /** + * OpenAI metadata attached to `QuotaExhaustedError` values. + * + * **Details** + * + * Preserves provider error details for failures caused by exhausted account, + * billing, or usage quota. + * + * @category models + * @since 4.0.0 + */ + export interface QuotaExhaustedErrorMetadata { + /** + * OpenAI-specific details for the quota exhaustion response. + */ + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * OpenAI metadata attached to `AuthenticationError` values. + * + * **Details** + * + * Preserves provider error details for failed API key, authorization, or + * permission checks. + * + * @category models + * @since 4.0.0 + */ + export interface AuthenticationErrorMetadata { + /** + * OpenAI-specific details for the authentication failure. + */ + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * OpenAI metadata attached to `ContentPolicyError` values. + * + * **Details** + * + * Preserves provider error details when OpenAI rejects input or output because + * it violates a content policy. + * + * @category models + * @since 4.0.0 + */ + export interface ContentPolicyErrorMetadata { + /** + * OpenAI-specific details for the content policy response. + */ + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * OpenAI metadata attached to `InvalidRequestError` values. + * + * **Details** + * + * Preserves provider error details for malformed requests, unsupported + * parameters, or other request validation failures reported by OpenAI. + * + * @category models + * @since 4.0.0 + */ + export interface InvalidRequestErrorMetadata { + /** + * OpenAI-specific details for the invalid request response. + */ + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * OpenAI metadata attached to `InternalProviderError` values. + * + * **Details** + * + * Preserves provider error details for OpenAI-side failures such as transient + * server errors. + * + * @category models + * @since 4.0.0 + */ + export interface InternalProviderErrorMetadata { + /** + * OpenAI-specific details for the internal provider response. + */ + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * OpenAI metadata attached to `InvalidOutputError` values. + * + * **Details** + * + * Preserves provider error details when an OpenAI response cannot be parsed or + * validated as the expected output. + * + * @category models + * @since 4.0.0 + */ + export interface InvalidOutputErrorMetadata { + /** + * OpenAI-specific details for the invalid output response. + */ + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * OpenAI metadata attached to `StructuredOutputError` values. + * + * **Details** + * + * Preserves provider error details when OpenAI returns content that does not + * satisfy the requested structured output schema. + * + * @category models + * @since 4.0.0 + */ + export interface StructuredOutputErrorMetadata { + /** + * OpenAI-specific details for the structured output failure. + */ + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * OpenAI metadata attached to `UnsupportedSchemaError` values. + * + * **Details** + * + * Preserves provider error details when an unsupported schema failure is + * associated with an OpenAI response. + * + * @category models + * @since 4.0.0 + */ + export interface UnsupportedSchemaErrorMetadata { + /** + * OpenAI-specific details for the unsupported schema failure. + */ + readonly openai?: OpenAiErrorMetadata | null + } + + /** + * OpenAI metadata attached to `UnknownError` values. + * + * **Details** + * + * Preserves provider error details for OpenAI failures that do not map cleanly + * to a more specific AI error category. + * + * @category models + * @since 4.0.0 + */ + export interface UnknownErrorMetadata { + /** + * OpenAI-specific details for the unclassified provider failure. + */ + readonly openai?: OpenAiErrorMetadata | null + } +} diff --git a/packages/effect-ai-openai/src/OpenAiLanguageModel.ts b/packages/effect-ai-openai/src/OpenAiLanguageModel.ts new file mode 100644 index 0000000..2566203 --- /dev/null +++ b/packages/effect-ai-openai/src/OpenAiLanguageModel.ts @@ -0,0 +1,3345 @@ +/** + * The `OpenAiLanguageModel` module provides the OpenAI Responses API + * implementation of Effect AI's `LanguageModel` service. It translates Effect + * AI prompts, files, tools, structured output requests, reasoning metadata, and + * provider options into OpenAI response requests, then converts OpenAI + * non-streaming or streaming response results back into Effect AI response + * content and metadata. + * + * @since 4.0.0 + */ +import * as Context from "effect/Context" +import * as DateTime from "effect/DateTime" +import * as Effect from "effect/Effect" +import * as Encoding from "effect/Encoding" +import { dual } from "effect/Function" +import * as Layer from "effect/Layer" +import * as Option from "effect/Option" +import * as Predicate from "effect/Predicate" +import * as Redactable from "effect/Redactable" +import * as Schema from "effect/Schema" +import * as AST from "effect/SchemaAST" +import * as SchemaIssue from "effect/SchemaIssue" +import * as Stream from "effect/Stream" +import type { Span } from "effect/Tracer" +import type { DeepMutable, Mutable, Simplify } from "effect/Types" +import * as AiError from "effect/unstable/ai/AiError" +import * as IdGenerator from "effect/unstable/ai/IdGenerator" +import * as LanguageModel from "effect/unstable/ai/LanguageModel" +import * as AiModel from "effect/unstable/ai/Model" +import { toCodecOpenAI } from "effect/unstable/ai/OpenAiStructuredOutput" +import * as Prompt from "effect/unstable/ai/Prompt" +import type * as Response from "effect/unstable/ai/Response" +import * as Tool from "effect/unstable/ai/Tool" +import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import * as Generated from "./Generated.ts" +import * as InternalUtilities from "./internal/utilities.ts" +import { OpenAiClient } from "./OpenAiClient.ts" +import type * as OpenAiSchema from "./OpenAiSchema.ts" +import { addGenAIAnnotations } from "./OpenAiTelemetry.ts" +import type * as OpenAiTool from "./OpenAiTool.ts" + +const formatIssue = SchemaIssue.makeFormatterDefault() + +const ResponseModelIds = Generated.ModelIdsResponses.members[1] +const SharedModelIds = Generated.ModelIdsShared.members[1] + +/** + * OpenAI model identifiers supported by the Responses API language model. + * + * @category models + * @since 4.0.0 + */ +export type Model = typeof ResponseModelIds.Encoded | typeof SharedModelIds.Encoded + +/** + * Image detail level for vision requests. + */ +type ImageDetail = "auto" | "low" | "high" + +type PromptCacheBreakpoint = { readonly mode: "explicit" } + +// ============================================================================= +// Configuration +// ============================================================================= + +/** + * Context service for OpenAI language model configuration. + * + * **When to use** + * + * Use when you need to provide OpenAI Responses API request defaults through + * Effect context for language model operations. + * + * **Details** + * + * Config values are merged with the config object passed to `model`, `make`, or + * `layer`, with scoped context values taking precedence. + * + * @see {@link withConfigOverride} for scoping language model request overrides + * + * @category services + * @since 4.0.0 + */ +export class Config extends Context.Service< + Config, + Simplify< + & Partial< + Omit< + typeof OpenAiSchema.CreateResponse.Encoded, + "input" | "tools" | "tool_choice" | "stream" | "text" + > + > + & { + /** + * File ID prefixes used to identify file IDs in Responses API. + * When undefined, all file data is treated as base64 content. + * + * Examples: + * - OpenAI: ['file-'] for IDs like 'file-abc123' + * - Azure OpenAI: ['assistant-'] for IDs like 'assistant-abc123' + */ + readonly fileIdPrefixes?: ReadonlyArray | undefined + /** + * Configuration options for a text response from the model. + */ + readonly text?: { + /** + * Constrains the verbosity of the model's response. Lower values will + * result in more concise responses, while higher values will result in + * more verbose responses. + * + * Defaults to `"medium"`. + */ + readonly verbosity?: "low" | "medium" | "high" | undefined + } | undefined + /** + * Whether to use strict JSON schema validation. + * + * Defaults to `true`. + */ + readonly strictJsonSchema?: boolean | undefined + } + > +>()("@humanlayer/effect-ai-openai/OpenAiLanguageModel/Config") {} + +// ============================================================================= +// Provider Options / Metadata +// ============================================================================= + +declare module "effect/unstable/ai/Prompt" { + /** + * OpenAI-specific options for system messages. + * + * @category models + * @since 4.0.0 + */ + export interface SystemMessageOptions extends ProviderOptions { + /** + * Provider-specific system message options for the OpenAI Responses API. + */ + readonly openai?: { + /** + * Marks the system input text as the end of a reusable prompt prefix. + * + * Requires GPT-5.6 or later. OpenAI may reject requests that use this + * option with earlier models. + */ + readonly promptCacheBreakpoint?: PromptCacheBreakpoint | null + } | null + } + + /** + * OpenAI-specific options for file prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface FilePartOptions extends ProviderOptions { + /** + * Provider-specific file options for the OpenAI Responses API. + */ + readonly openai?: { + /** + * The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. + */ + readonly imageDetail?: ImageDetail | null + } | null + } + + /** + * OpenAI-specific options for reasoning prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningPartOptions extends ProviderOptions { + /** + * Provider-specific reasoning options for the OpenAI Responses API. + */ + readonly openai?: { + /** + * The ID of the item to reference. + */ + readonly itemId?: string | null + /** + * The encrypted content of the reasoning item - populated when a response + * is generated with `reasoning.encrypted_content` in the `include` + * parameter. + */ + readonly encryptedContent?: string | null + } | null + } + + /** + * OpenAI-specific options for assistant tool-call prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface ToolCallPartOptions extends ProviderOptions { + /** + * Provider-specific tool-call options for the OpenAI Responses API. + */ + readonly openai?: { + /** + * The ID of the item to reference. + */ + readonly itemId?: string | null + /** + * The status of item. + */ + readonly status?: typeof OpenAiSchema.MessageStatus.Encoded | null + /** + * The ID of the approval request. + */ + readonly approvalRequestId?: string | null + } | null + } + + /** + * OpenAI-specific options for tool-result prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface ToolResultPartOptions extends ProviderOptions { + /** + * Provider-specific tool-result options for the OpenAI Responses API. + */ + readonly openai?: { + /** + * The ID of the item to reference. + */ + readonly itemId?: string | null + /** + * The status of item. + */ + readonly status?: typeof OpenAiSchema.MessageStatus.Encoded | null + /** + * The ID of the approval request. + */ + readonly approvalId?: string | null + } | null + } + + /** + * OpenAI-specific options for text prompt parts. + * + * @category models + * @since 4.0.0 + */ + export interface TextPartOptions extends ProviderOptions { + /** + * Provider-specific text options for the OpenAI Responses API. + */ + readonly openai?: { + /** + * The ID of the item to reference. + */ + readonly itemId?: string | null + /** + * The status of item. + */ + readonly status?: typeof OpenAiSchema.MessageStatus.Encoded | null + /** + * A list of annotations that apply to the output text. + */ + readonly annotations?: ReadonlyArray | null + /** + * Marks the input text as the end of a reusable prompt prefix. + * + * Requires GPT-5.6 or later. OpenAI may reject requests that use this + * option with earlier models. + */ + readonly promptCacheBreakpoint?: PromptCacheBreakpoint | null + } | null + } +} + +declare module "effect/unstable/ai/Response" { + /** + * OpenAI metadata attached to a complete text response part. + * + * @category models + * @since 4.0.0 + */ + export interface TextPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the text part. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the text part. + */ + readonly itemId?: string | null + /** + * If the model emits a refusal content part, the refusal explanation + * from the model will be contained in the metadata of an empty text + * part. + */ + readonly refusal?: string | null + /** + * The status of item. + */ + readonly status?: typeof OpenAiSchema.MessageStatus.Encoded | null + /** + * The text content part annotations. + */ + readonly annotations?: ReadonlyArray | null + } + } + + /** + * OpenAI metadata emitted when a streamed text part starts. + * + * @category models + * @since 4.0.0 + */ + export interface TextStartPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed text start. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the streamed text part. + */ + readonly itemId?: string | null + } | null + } + + /** + * OpenAI metadata emitted when a streamed text part ends. + * + * @category models + * @since 4.0.0 + */ + export interface TextEndPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed text end. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the streamed text part. + */ + readonly itemId?: string | null + /** + * The annotations collected for the completed streamed text part. + */ + readonly annotations?: ReadonlyArray | null + } | null + } + + /** + * OpenAI metadata attached to a complete reasoning response part. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the reasoning part. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the reasoning part. + */ + readonly itemId?: string | null + /** + * Encrypted reasoning content that can be sent back in later requests. + */ + readonly encryptedContent?: string | null + } | null + } + + /** + * OpenAI metadata emitted when a streamed reasoning part starts. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningStartPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed reasoning start. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the reasoning part. + */ + readonly itemId?: string | null + /** + * Encrypted reasoning content that can be sent back in later requests. + */ + readonly encryptedContent?: string | null + } | null + } + + /** + * OpenAI metadata emitted for a streamed reasoning delta. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningDeltaPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed reasoning delta. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the reasoning part. + */ + readonly itemId?: string | null + } | null + } + + /** + * OpenAI metadata emitted when a streamed reasoning part ends. + * + * @category models + * @since 4.0.0 + */ + export interface ReasoningEndPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the streamed reasoning end. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the reasoning part. + */ + readonly itemId?: string | null + /** + * Encrypted reasoning content that can be sent back in later requests. + */ + readonly encryptedContent?: string + } | null + } + + /** + * OpenAI metadata attached to tool-call response parts. + * + * @category models + * @since 4.0.0 + */ + export interface ToolCallPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned for the tool call. + */ + readonly openai?: { + /** + * The OpenAI item ID associated with the tool call. + */ + readonly itemId?: string | null + } | null + } + + /** + * OpenAI metadata attached to document source citations. + * + * @category models + * @since 4.0.0 + */ + export interface DocumentSourcePartMetadata extends ProviderMetadata { + /** + * Provider-specific citation metadata for the OpenAI Responses API. + */ + readonly openai?: + | { + /** + * Identifies a citation to an uploaded file. + */ + readonly type: "file_citation" + /** + * The index of the file in the list of files. + */ + readonly index: number + /** + * The ID of the file. + */ + readonly fileId: string + } + | { + /** + * Identifies a citation to a generated file path. + */ + readonly type: "file_path" + /** + * The index of the file in the list of files. + */ + readonly index: number + /** + * The ID of the file. + */ + readonly fileId: string + } + | { + /** + * Identifies a citation to a file inside a container. + */ + readonly type: "container_file_citation" + /** + * The ID of the file. + */ + readonly fileId: string + /** + * The ID of the container file. + */ + readonly containerId: string + } + | null + } + + /** + * OpenAI metadata attached to URL source citations. + * + * @category models + * @since 4.0.0 + */ + export interface UrlSourcePartMetadata extends ProviderMetadata { + /** + * Provider-specific URL citation metadata for the OpenAI Responses API. + */ + readonly openai?: { + /** + * Identifies a citation to a URL. + */ + readonly type: "url_citation" + /** + * The index of the first character of the URL citation in the message. + */ + readonly startIndex: number + /** + * The index of the last character of the URL citation in the message. + */ + readonly endIndex: number + } | null + } + + /** + * OpenAI metadata attached to finish response parts. + * + * @category models + * @since 4.0.0 + */ + export interface FinishPartMetadata extends ProviderMetadata { + /** + * Provider-specific metadata returned when generation finishes. + */ + readonly openai?: { + /** + * The service tier reported by OpenAI for the response. + */ + readonly serviceTier?: "default" | "auto" | "flex" | "scale" | "priority" | null + } | null + } +} + +// ============================================================================= +// Language Model +// ============================================================================= + +/** + * Creates an OpenAI model descriptor that can be provided with + * `Effect.provide`. + * + * **When to use** + * + * Use when you want an OpenAI language model value that carries provider and + * model metadata and can be supplied directly to an Effect program. + * + * @see {@link layer} for creating a `LanguageModel.LanguageModel` layer directly + * @see {@link make} for constructing the language model service effectfully + * + * @category constructors + * @since 4.0.0 + */ +export const model = ( + model: (string & {}) | Model, + config?: Omit +): AiModel.Model<"openai", LanguageModel.LanguageModel, OpenAiClient> => + AiModel.make("openai", model, layer({ model, config })) + +// TODO +// /** +// * @since 4.0.0 +// * @category constructors +// */ +// export const modelWithTokenizer = ( +// model: (string & {}) | Model, +// config?: Omit +// ): AiModel.Model<"openai", LanguageModel.LanguageModel | Tokenizer.Tokenizer, OpenAiClient> => +// AiModel.make("openai", model, layerWithTokenizer({ model, config })) + +/** + * Creates an OpenAI `LanguageModel` service from a model identifier and + * optional request defaults. + * + * **When to use** + * + * Use to construct an OpenAI Responses API language model service backed by + * `OpenAiClient`. + * + * **Details** + * + * The returned effect requires `OpenAiClient`. Request defaults from the + * `config` option are merged with any `Config` service in the context, with + * context values taking precedence. The service supports both `generateText` + * and `streamText`. + * + * @see {@link layer} for providing the service as a `Layer` + * @see {@link model} for creating a model descriptor for `Effect.provide` + * + * @category constructors + * @since 4.0.0 + */ +export const make = Effect.fnUntraced(function*({ model, config: providerConfig }: { + readonly model: (string & {}) | Model + readonly config?: Omit | undefined +}): Effect.fn.Return { + const client = yield* OpenAiClient + + const makeConfig = Effect.gen(function*() { + const services = yield* Effect.context() + return { model, ...providerConfig, ...Context.getOrUndefined(services, Config) } + }) + + const makeRequest = Effect.fnUntraced( + function*>({ config, options, toolNameMapper }: { + readonly config: typeof Config.Service + readonly options: LanguageModel.ProviderOptions + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return { + const include = new Set() + const capabilities = getModelCapabilities(config.model as string) + const messages = yield* prepareMessages({ + config, + options, + capabilities, + include, + toolNameMapper + }) + const { toolChoice, tools } = yield* prepareTools({ + config, + options, + toolNameMapper + }) + const responseFormat = yield* prepareResponseFormat({ + config, + options + }) + const { fileIdPrefixes: _fip, strictJsonSchema: _sjs, ...apiConfig } = config + const request: Mutable = { + ...apiConfig, + input: messages, + include: include.size > 0 ? Array.from(include) : undefined, + text: { + verbosity: config.text?.verbosity ?? undefined, + format: responseFormat + } + } + if (tools) request.tools = tools + if (toolChoice) request.tool_choice = toolChoice + if (options.previousResponseId) request.previous_response_id = options.previousResponseId + return request + } + ) + + return yield* LanguageModel.make({ + codecTransformer: toCodecOpenAI, + generateText: Effect.fnUntraced( + function*(options) { + const config = yield* makeConfig + const toolNameMapper = new Tool.NameMapper(options.tools) + const request = yield* makeRequest({ config, options, toolNameMapper }) + annotateRequest(options.span, request) + const [rawResponse, response] = yield* client.createResponse(request) + annotateResponse(options.span, rawResponse) + return yield* makeResponse({ + options, + rawResponse, + response, + toolNameMapper + }) + } + ), + streamText: Effect.fnUntraced( + function*(options) { + const config = yield* makeConfig + const toolNameMapper = new Tool.NameMapper(options.tools) + const request = yield* makeRequest({ config, options, toolNameMapper }) + annotateRequest(options.span, request) + const [response, stream] = yield* client.createResponseStream(request) + return yield* makeStreamResponse({ + stream, + response, + config, + options, + toolNameMapper + }) + }, + (effect, options) => + effect.pipe( + Stream.unwrap, + Stream.map((response) => { + annotateStreamResponse(options.span, response) + return response + }) + ) + ) + }) +}) + +/** + * Creates a layer that provides the OpenAI `LanguageModel.LanguageModel` + * service. + * + * **When to use** + * + * Use when composing application layers and you want OpenAI to satisfy + * `LanguageModel.LanguageModel` while supplying `OpenAiClient` from another + * layer. + * + * **Details** + * + * The `config` option supplies request defaults for the selected model. Scoped + * values from `withConfigOverride` are merged when each request is built and + * take precedence over these defaults. + * + * @see {@link make} for constructing the language model service effectfully + * @see {@link model} for creating a model descriptor for `Effect.provide` + * @see {@link withConfigOverride} for scoped request configuration overrides + * + * @category layers + * @since 4.0.0 + */ +export const layer = (options: { + readonly model: (string & {}) | Model + readonly config?: Omit | undefined +}): Layer.Layer => + Layer.effect(LanguageModel.LanguageModel, make(options)) + +/** + * Provides scoped config overrides for OpenAI language model operations. + * + * **When to use** + * + * Use to apply OpenAI Responses API config overrides around one or more + * language model operations without changing the defaults passed to `model`, + * `make`, or `layer`. + * + * **Details** + * + * The override is dual, so it can be used in pipe form or as + * `withConfigOverride(effect, overrides)`. Overrides are merged with any + * existing `Config` service in the current context, and the override values take + * precedence. + * + * @see {@link Config} for the scoped configuration service consumed by this function + * + * @category configuration + * @since 4.0.0 + */ +export const withConfigOverride: { + /** + * Provides scoped config overrides for OpenAI language model operations. + * + * **When to use** + * + * Use to apply OpenAI Responses API config overrides around one or more + * language model operations without changing the defaults passed to `model`, + * `make`, or `layer`. + * + * **Details** + * + * The override is dual, so it can be used in pipe form or as + * `withConfigOverride(effect, overrides)`. Overrides are merged with any + * existing `Config` service in the current context, and the override values take + * precedence. + * + * @see {@link Config} for the scoped configuration service consumed by this function + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service): (self: Effect.Effect) => Effect.Effect> + /** + * Provides scoped config overrides for OpenAI language model operations. + * + * **When to use** + * + * Use to apply OpenAI Responses API config overrides around one or more + * language model operations without changing the defaults passed to `model`, + * `make`, or `layer`. + * + * **Details** + * + * The override is dual, so it can be used in pipe form or as + * `withConfigOverride(effect, overrides)`. Overrides are merged with any + * existing `Config` service in the current context, and the override values take + * precedence. + * + * @see {@link Config} for the scoped configuration service consumed by this function + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service): Effect.Effect> +} = dual< + /** + * Provides scoped config overrides for OpenAI language model operations. + * + * **When to use** + * + * Use to apply OpenAI Responses API config overrides around one or more + * language model operations without changing the defaults passed to `model`, + * `make`, or `layer`. + * + * **Details** + * + * The override is dual, so it can be used in pipe form or as + * `withConfigOverride(effect, overrides)`. Overrides are merged with any + * existing `Config` service in the current context, and the override values take + * precedence. + * + * @see {@link Config} for the scoped configuration service consumed by this function + * + * @category configuration + * @since 4.0.0 + */ + (overrides: typeof Config.Service) => (self: Effect.Effect) => Effect.Effect>, + /** + * Provides scoped config overrides for OpenAI language model operations. + * + * **When to use** + * + * Use to apply OpenAI Responses API config overrides around one or more + * language model operations without changing the defaults passed to `model`, + * `make`, or `layer`. + * + * **Details** + * + * The override is dual, so it can be used in pipe form or as + * `withConfigOverride(effect, overrides)`. Overrides are merged with any + * existing `Config` service in the current context, and the override values take + * precedence. + * + * @see {@link Config} for the scoped configuration service consumed by this function + * + * @category configuration + * @since 4.0.0 + */ + (self: Effect.Effect, overrides: typeof Config.Service) => Effect.Effect> +>(2, (self, overrides) => + Effect.flatMap( + Effect.serviceOption(Config), + (config) => + Effect.provideService(self, Config, { + ...(config._tag === "Some" ? config.value : {}), + ...overrides + }) + )) + +// ============================================================================= +// Prompt Conversion +// ============================================================================= + +const getSystemMessageMode = (model: string): "system" | "developer" => + model.startsWith("o") || + model.startsWith("gpt-5") || + model.startsWith("codex-") || + model.startsWith("computer-use") + ? "developer" + : "system" + +const prepareMessages = Effect.fnUntraced( + function*>({ + config, + options, + capabilities, + include, + toolNameMapper + }: { + readonly config: typeof Config.Service + readonly options: LanguageModel.ProviderOptions + readonly include: Set + readonly capabilities: ModelCapabilities + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return, AiError.AiError> { + const processedApprovalIds = new Set() + + const hasConversation = Predicate.isNotNullish(config.conversation) + + // Provider-Defined Tools + const applyPatchTool = options.tools.find((tool): tool is ReturnType => + Tool.isProviderDefined(tool) && tool.name === "OpenAiApplyPatch" + ) + const codeInterpreterTool = options.tools.find((tool): tool is ReturnType => + Tool.isProviderDefined(tool) && tool.name === "OpenAiCodeInterpreter" + ) + const shellTool = options.tools.find((tool): tool is ReturnType => + Tool.isProviderDefined(tool) && tool.name === "OpenAiShell" + ) + const localShellTool = options.tools.find((tool): tool is ReturnType => + Tool.isProviderDefined(tool) && tool.name === "OpenAiLocalShell" + ) + const webSearchTool = options.tools.find((tool): tool is ReturnType => + Tool.isProviderDefined(tool) && tool.name === "OpenAiWebSearch" + ) + const webSearchPreviewTool = options.tools.find((tool): tool is ReturnType => + Tool.isProviderDefined(tool) && tool.name === "OpenAiWebSearchPreview" + ) + + // Handle Included Features + if (Predicate.isNotUndefined(config.top_logprobs)) { + include.add("message.output_text.logprobs") + } + if (config.store === false && capabilities.isReasoningModel) { + include.add("reasoning.encrypted_content") + } + if (codeInterpreterTool) { + include.add("code_interpreter_call.outputs") + } + if (webSearchTool || webSearchPreviewTool) { + include.add("web_search_call.action.sources") + } + + const messages: Array = [] + const prompt = options.incrementalPrompt ?? options.prompt + + for (const message of prompt.content) { + switch (message.role) { + case "system": { + messages.push({ + role: getSystemMessageMode(config.model as string), + content: [{ + type: "input_text", + text: message.content, + ...getPromptCacheBreakpoint(message) + }] + }) + break + } + + case "user": { + const content: Array = [] + + for (let index = 0; index < message.content.length; index++) { + const part = message.content[index] + + switch (part.type) { + case "text": { + content.push({ + type: "input_text", + text: part.text, + ...getPromptCacheBreakpoint(part) + }) + break + } + + case "file": { + if (part.mediaType.startsWith("image/")) { + const detail = getImageDetail(part) + const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType + + if (typeof part.data === "string" && isFileId(part.data, config)) { + content.push({ type: "input_image", file_id: part.data, detail }) + } + + if (part.data instanceof URL) { + content.push({ type: "input_image", image_url: part.data.toString(), detail }) + } + + if (part.data instanceof Uint8Array) { + const base64 = Encoding.encodeBase64(part.data) + const imageUrl = `data:${mediaType};base64,${base64}` + content.push({ type: "input_image", image_url: imageUrl, detail }) + } + } else if (part.mediaType === "application/pdf") { + if (typeof part.data === "string" && isFileId(part.data, config)) { + content.push({ type: "input_file", file_id: part.data }) + } + + if (part.data instanceof URL) { + content.push({ type: "input_file", file_url: part.data.toString() }) + } + + if (part.data instanceof Uint8Array) { + const base64 = Encoding.encodeBase64(part.data) + const fileName = part.fileName ?? `part-${index}.pdf` + const fileData = `data:application/pdf;base64,${base64}` + content.push({ type: "input_file", filename: fileName, file_data: fileData }) + } + } else { + return yield* AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareMessages", + reason: new AiError.InvalidRequestError({ + description: `Detected unsupported media type for file: '${part.mediaType}'` + }) + }) + } + } + } + } + + messages.push({ role: "user", content }) + + break + } + + case "assistant": { + const reasoningMessages: Record> = Object + .create(null) + + for (const part of message.content) { + switch (part.type) { + case "text": { + const id = getItemId(part) + + // When in conversation mode, skip items that already exist in the + // conversation context to avoid "Duplicate item found" errors + if (hasConversation && Predicate.isNotNull(id)) { + break + } + + if (config.store === true && Predicate.isNotNull(id)) { + messages.push({ type: "item_reference", id }) + break + } + + messages.push({ + id: id!, + type: "message", + role: "assistant", + status: part.options.openai?.status ?? "completed", + content: [{ + type: "output_text", + text: part.text, + annotations: part.options.openai?.annotations ?? [], + logprobs: [] + }] + }) + + break + } + + case "reasoning": { + const id = getItemId(part) + const encryptedContent = getEncryptedContent(part) + + if (hasConversation && Predicate.isNotNull(id)) { + break + } + + if (Predicate.isNotNull(id)) { + const message = reasoningMessages[id] + + if (config.store === true) { + // Use item references to refer to reasoning (single reference) + // when the first part is encountered + if (Predicate.isUndefined(message)) { + messages.push({ type: "item_reference", id }) + + // Store unused reasoning message to mark its id as used + reasoningMessages[id] = { + type: "reasoning", + id, + summary: [] + } + } + } else { + const summaryParts: Array = [] + + if (part.text.length > 0) { + summaryParts.push({ type: "summary_text", text: part.text }) + } + + if (Predicate.isUndefined(message)) { + reasoningMessages[id] = { + type: "reasoning", + id, + summary: summaryParts, + ...(Predicate.isNotNull(encryptedContent) + ? { encrypted_content: encryptedContent } + : undefined) + } + + messages.push(reasoningMessages[id]) + } else { + message.summary.push(...summaryParts) + + // Update encrypted content to enable setting it in the + // last summary part + if (Predicate.isNotNull(encryptedContent)) { + message.encrypted_content = encryptedContent + } + } + } + } + + break + } + + case "tool-call": { + const id = getItemId(part) + const status = getStatus(part) + + if (hasConversation && Predicate.isNotNull(id)) { + break + } + + if (config.store && Predicate.isNotNull(id)) { + messages.push({ type: "item_reference", id }) + break + } + + if (part.providerExecuted) { + break + } + + const toolName = toolNameMapper.getProviderName(part.name) + + if (Predicate.isNotUndefined(localShellTool) && toolName === "local_shell") { + const params = yield* Schema.decodeUnknownEffect(localShellTool.parametersSchema)(part.params).pipe( + Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareMessages", + reason: new AiError.ToolParameterValidationError({ + toolName: "local_shell", + toolParams: part.params as Schema.Json, + description: error.message + }) + }) + ) + ) + + messages.push({ + id: id!, + type: "local_shell_call", + call_id: part.id, + status: status ?? "completed", + action: params.action + }) + + break + } + + if (Predicate.isNotUndefined(shellTool) && toolName === "shell") { + const params = yield* Schema.decodeUnknownEffect(shellTool.parametersSchema)(part.params).pipe( + Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareMessages", + reason: new AiError.ToolParameterValidationError({ + toolName: "shell", + toolParams: part.params as Schema.Json, + description: error.message + }) + }) + ) + ) + + messages.push({ + id: id!, + type: "shell_call", + call_id: part.id, + status: status ?? "completed", + action: params.action + }) + + break + } + + messages.push({ + type: "function_call", + name: toolName, + call_id: part.id, + arguments: JSON.stringify(part.params), + ...(Predicate.isNotNull(id) ? { id } : {}), + ...(Predicate.isNotNull(status) ? { status } : {}) + }) + + break + } + + // Assistant tool-result parts are always provider executed + case "tool-result": { + // Skip execution denied results - these have no corresponding + // item in OpenAI's store + if ( + Predicate.hasProperty(part.result, "type") && + part.result.type === "execution-denied" + ) { + break + } + + if (hasConversation) { + break + } + + if (config.store === true) { + const id = getItemId(part) ?? part.id + messages.push({ type: "item_reference", id }) + } + } + } + } + + break + } + + case "tool": { + for (const part of message.content) { + if (part.type === "tool-approval-response") { + if (processedApprovalIds.has(part.approvalId)) { + continue + } + + processedApprovalIds.add(part.approvalId) + + if (config.store === true) { + messages.push({ type: "item_reference", id: part.approvalId }) + } + + messages.push({ + type: "mcp_approval_response", + approval_request_id: part.approvalId, + approve: part.approved + } as any) + + continue + } + + // Skip execution-denied results that already have an approvalId - + // this indicates that the part was already handled via tool-approval-response + if ( + Predicate.hasProperty(part.result, "type") && + part.result.type === "execution-denied" + ) { + if (Predicate.isNotNullish(part.options.openai?.approvalId)) { + continue + } + } + + const id = getItemId(part) ?? part.id + const status = getStatus(part) + const toolName = toolNameMapper.getProviderName(part.name) + + if (Predicate.isNotUndefined(applyPatchTool) && toolName === "apply_patch") { + messages.push({ + id, + type: "apply_patch_call_output", + call_id: part.id, + ...(part.result as any) + }) + continue + } + + if (Predicate.isNotUndefined(shellTool) && toolName === "shell") { + messages.push({ + id, + type: "shell_call_output", + call_id: part.id, + output: part.result as any, + ...(Predicate.isNotNull(status) ? { status } : {}) + }) + continue + } + + if (Predicate.isNotUndefined(localShellTool) && toolName === "local_shell") { + messages.push({ + id, + type: "local_shell_call_output", + call_id: part.id, + output: part.result as any, + ...(Predicate.isNotNull(status) ? { status } : {}) + }) + continue + } + + let output: string | Array + if (Predicate.isString(part.result)) { + output = part.result + } else if ( + Array.isArray(part.result) && + part.result.every((item) => Prompt.isPart(item) && (item.type === "text" || item.type === "file")) + ) { + output = [] + for (const outputPart of part.result) { + if (outputPart.type === "text") { + output.push({ type: "input_text", text: outputPart.text }) + continue + } + + if (!outputPart.mediaType.startsWith("image/")) { + return yield* AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareMessages", + reason: new AiError.InvalidRequestError({ + description: `Detected unsupported media type for tool result: '${outputPart.mediaType}'` + }) + }) + } + + const detail = getImageDetail(outputPart) + const mediaType = outputPart.mediaType === "image/*" ? "image/jpeg" : outputPart.mediaType + if (Predicate.isString(outputPart.data) && isFileId(outputPart.data, config)) { + output.push({ type: "input_image", file_id: outputPart.data, detail }) + } else if (outputPart.data instanceof URL) { + output.push({ type: "input_image", image_url: outputPart.data.toString(), detail }) + } else if (outputPart.data instanceof Uint8Array) { + output.push({ + type: "input_image", + image_url: `data:${mediaType};base64,${Encoding.encodeBase64(outputPart.data)}`, + detail + }) + } else { + output.push({ + type: "input_image", + image_url: outputPart.data.startsWith("data:") + ? outputPart.data + : `data:${mediaType};base64,${outputPart.data}`, + detail + }) + } + } + } else { + output = JSON.stringify(part.result) + } + + messages.push({ + type: "function_call_output", + call_id: part.id, + output, + ...(Predicate.isNotNull(status) ? { status } : {}) + }) + } + + break + } + } + } + + return messages + } +) + +// ============================================================================= +// HTTP Details +// ============================================================================= + +const buildHttpRequestDetails = ( + request: HttpClientRequest.HttpClientRequest +): typeof Response.HttpRequestDetails.Type => ({ + method: request.method, + url: request.url, + urlParams: Array.from(request.urlParams), + hash: Option.getOrUndefined(request.hash), + headers: Redactable.redact(request.headers) as Record +}) + +const buildHttpResponseDetails = ( + response: HttpClientResponse.HttpClientResponse +): typeof Response.HttpResponseDetails.Type => ({ + status: response.status, + headers: Redactable.redact(response.headers) as Record +}) + +// ============================================================================= +// Response Conversion +// ============================================================================= + +type ResponseStreamEvent = typeof OpenAiSchema.ResponseStreamEvent.Type + +type KnownResponseStreamEventType = + | "response.created" + | "response.completed" + | "response.incomplete" + | "response.failed" + | "response.output_item.added" + | "response.output_item.done" + | "response.output_text.delta" + | "response.output_text.annotation.added" + | "response.reasoning_summary_part.added" + | "response.reasoning_summary_part.done" + | "response.reasoning_summary_text.delta" + | "response.function_call_arguments.delta" + | "response.function_call_arguments.done" + | "response.code_interpreter_call_code.delta" + | "response.code_interpreter_call_code.done" + | "response.apply_patch_call_operation_diff.delta" + | "response.apply_patch_call_operation_diff.done" + | "response.image_generation_call.partial_image" + | "error" + +type KnownResponseStreamEvent = Extract + +const knownResponseStreamEventTypes = new Set([ + "response.created", + "response.completed", + "response.incomplete", + "response.failed", + "response.output_item.added", + "response.output_item.done", + "response.output_text.delta", + "response.output_text.annotation.added", + "response.reasoning_summary_part.added", + "response.reasoning_summary_part.done", + "response.reasoning_summary_text.delta", + "response.function_call_arguments.delta", + "response.function_call_arguments.done", + "response.code_interpreter_call_code.delta", + "response.code_interpreter_call_code.done", + "response.apply_patch_call_operation_diff.delta", + "response.apply_patch_call_operation_diff.done", + "response.image_generation_call.partial_image", + "error" +]) + +const isKnownResponseStreamEvent = ( + event: ResponseStreamEvent +): event is KnownResponseStreamEvent => knownResponseStreamEventTypes.has(event.type as KnownResponseStreamEventType) + +const makeResponse = Effect.fnUntraced( + function*>({ + options, + rawResponse, + response, + toolNameMapper + }: { + readonly options: LanguageModel.ProviderOptions + readonly rawResponse: OpenAiSchema.Response + readonly response: HttpClientResponse.HttpClientResponse + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return< + Array, + AiError.AiError, + IdGenerator.IdGenerator + > { + const idGenerator = yield* IdGenerator.IdGenerator + + const approvalRequests = getApprovalRequestIdMapping(options.prompt) + + const webSearchTool = options.tools.find((tool) => + Tool.isProviderDefined(tool) && + (tool.name === "OpenAiWebSearch" || + tool.name === "OpenAiWebSearchPreview") + ) as Tool.AnyProviderDefined | undefined + + let hasToolCalls = false + const parts: Array = [] + + const createdAt = new Date(rawResponse.created_at * 1000) + parts.push({ + type: "response-metadata", + id: rawResponse.id, + modelId: rawResponse.model as string, + timestamp: DateTime.formatIso(DateTime.fromDateUnsafe(createdAt)), + request: buildHttpRequestDetails(response.request) + }) + + for (const part of rawResponse.output) { + switch (part.type) { + case "apply_patch_call": { + const toolName = toolNameMapper.getCustomName("apply_patch") + parts.push({ + type: "tool-call", + id: part.call_id, + name: toolName, + params: { call_id: part.call_id, operation: part.operation }, + metadata: { openai: makeItemIdMetadata(part.id) } + }) + break + } + + case "code_interpreter_call": { + const toolName = toolNameMapper.getCustomName("code_interpreter") + parts.push({ + type: "tool-call", + id: part.id, + name: toolName, + params: { code: part.code, container_id: part.container_id }, + providerExecuted: true + }) + parts.push({ + type: "tool-result", + id: part.id, + name: toolName, + isFailure: false, + result: { outputs: part.outputs }, + providerExecuted: true + }) + break + } + + case "file_search_call": { + const toolName = toolNameMapper.getCustomName("file_search") + parts.push({ + type: "tool-call", + id: part.id, + name: toolName, + params: {}, + providerExecuted: true + }) + parts.push({ + type: "tool-result", + id: part.id, + name: toolName, + isFailure: false, + result: { + status: part.status, + queries: part.queries, + results: part.results ?? null + }, + providerExecuted: true + }) + break + } + + case "function_call": { + hasToolCalls = true + + const toolName = part.name + + const toolParams = yield* Effect.try({ + try: () => Tool.unsafeSecureJsonParse(part.arguments), + catch: (cause) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "makeResponse", + reason: new AiError.ToolParameterValidationError({ + toolName, + toolParams: {}, + description: `Faled to securely JSON parse tool parameters: ${cause}` + }) + }) + }) + + const params = yield* transformToolCallParams(options.tools, part.name, toolParams) + + parts.push({ + type: "tool-call", + id: part.call_id, + name: toolName, + params, + metadata: { openai: makeItemIdMetadata(part.id) } + }) + break + } + + case "image_generation_call": { + const toolName = toolNameMapper.getCustomName("image_generation") + parts.push({ + type: "tool-call", + id: part.id, + name: toolName, + params: {}, + providerExecuted: true + }) + parts.push({ + type: "tool-result", + id: part.id, + name: toolName, + isFailure: false, + result: { result: part.result } + }) + break + } + + case "local_shell_call": { + const toolName = toolNameMapper.getCustomName("local_shell") + parts.push({ + type: "tool-call", + id: part.call_id, + name: toolName, + params: { action: part.action }, + metadata: { openai: makeItemIdMetadata(part.id) } + }) + break + } + + case "mcp_call": { + const toolId = Predicate.isNotNullish(part.approval_request_id) + ? (approvalRequests.get(part.approval_request_id) ?? part.id) + : part.id + + const { toolName, params } = yield* normalizeMcpToolCall({ + toolNameMapper, + toolParams: part.arguments, + method: "makeResponse" + }) + + parts.push({ + type: "tool-call", + id: toolId, + name: toolName, + params, + providerExecuted: true + }) + + parts.push({ + type: "tool-result", + id: toolId, + name: toolName, + isFailure: false, + providerExecuted: true, + result: { + type: "mcp_call", + name: part.name, + arguments: part.arguments, + server_label: part.server_label, + ...(Predicate.isNotNullish(part.output) ? { output: part.output } : undefined), + ...(Predicate.isNotNullish(part.error) ? { error: part.error } : undefined) + }, + metadata: { openai: makeItemIdMetadata(part.id) } + }) + + break + } + + case "mcp_list_tools": { + // Skip + break + } + + case "mcp_approval_request": { + const approvalRequestId = (part as any).approval_request_id ?? part.id + const toolId = yield* idGenerator.generateId() + + const { toolName, params } = yield* normalizeMcpToolCall({ + toolNameMapper, + toolParams: part.arguments, + method: "makeResponse" + }) + + parts.push({ + type: "tool-call", + id: toolId, + name: toolName, + params, + providerExecuted: true + }) + + parts.push({ + type: "tool-approval-request", + toolCallId: toolId, + approvalId: approvalRequestId + }) + + break + } + + case "message": { + for (const contentPart of part.content) { + switch (contentPart.type) { + case "output_text": { + const annotations = contentPart.annotations.length > 0 + ? { annotations: contentPart.annotations as any } + : undefined + + parts.push({ + type: "text", + text: contentPart.text, + metadata: { + openai: { + ...makeItemIdMetadata(part.id), + ...annotations + } + } + }) + for (const annotation of contentPart.annotations) { + if (annotation.type === "container_file_citation") { + parts.push({ + type: "source", + sourceType: "document", + id: yield* idGenerator.generateId(), + mediaType: "text/plain", + title: annotation.filename, + fileName: annotation.filename, + metadata: { + openai: { + type: annotation.type, + fileId: annotation.file_id, + containerId: annotation.container_id + } + } + }) + } + if (annotation.type === "file_citation") { + parts.push({ + type: "source", + sourceType: "document", + id: yield* idGenerator.generateId(), + mediaType: "text/plain", + title: annotation.filename, + fileName: annotation.filename, + metadata: { + openai: { + type: annotation.type, + fileId: annotation.file_id, + index: annotation.index + } + } + }) + } + if (annotation.type === "file_path") { + parts.push({ + type: "source", + sourceType: "document", + id: yield* idGenerator.generateId(), + mediaType: "application/octet-stream", + title: annotation.file_id, + fileName: annotation.file_id, + metadata: { + openai: { + type: annotation.type, + fileId: annotation.file_id, + index: annotation.index + } + } + }) + } + if (annotation.type === "url_citation") { + parts.push({ + type: "source", + sourceType: "url", + id: yield* idGenerator.generateId(), + url: annotation.url, + title: annotation.title, + metadata: { + openai: { + type: annotation.type, + startIndex: annotation.start_index, + endIndex: annotation.end_index + } + } + }) + } + } + break + } + case "refusal": { + parts.push({ + type: "text", + text: "", + metadata: { openai: { refusal: contentPart.refusal } } + }) + break + } + } + } + break + } + + case "reasoning": { + const metadata = { + openai: { + ...makeItemIdMetadata(part.id), + ...makeEncryptedContentMetadata(part.encrypted_content) + } + } + // If there are no summary parts, we have to add an empty one to + // propagate the part identifier and encrypted content + if (part.summary.length === 0) { + parts.push({ type: "reasoning", text: "", metadata }) + } else { + for (const summary of part.summary) { + parts.push({ type: "reasoning", text: summary.text, metadata }) + } + } + break + } + + case "shell_call": { + const toolName = toolNameMapper.getCustomName("shell") + parts.push({ + type: "tool-call", + id: part.call_id, + name: toolName, + params: { action: part.action }, + metadata: { openai: makeItemIdMetadata(part.id) } + }) + break + } + + case "web_search_call": { + const toolName = toolNameMapper.getCustomName( + webSearchTool?.name ?? "web_search" + ) + parts.push({ + type: "tool-call", + id: part.id, + name: toolName, + params: webSearchTool?.name === "OpenAiWebSearchPreview" + ? {} + : { action: part.action }, + providerExecuted: true + }) + parts.push({ + type: "tool-result", + id: part.id, + name: toolName, + isFailure: false, + result: { action: part.action, status: part.status }, + providerExecuted: true + }) + break + } + } + } + + const finishReason = InternalUtilities.resolveFinishReason( + rawResponse.incomplete_details?.reason, + hasToolCalls + ) + + parts.push({ + type: "finish", + reason: finishReason, + usage: getUsage(rawResponse.usage), + response: buildHttpResponseDetails(response), + ...toServiceTier(rawResponse.service_tier) + }) + + return parts + } +) + +const makeStreamResponse = Effect.fnUntraced( + function*>({ + stream, + response, + config, + options, + toolNameMapper + }: { + readonly config: typeof Config.Service + readonly stream: Stream.Stream + readonly response: HttpClientResponse.HttpClientResponse + readonly options: LanguageModel.ProviderOptions + readonly toolNameMapper: Tool.NameMapper + }): Effect.fn.Return< + Stream.Stream, + AiError.AiError, + IdGenerator.IdGenerator + > { + const idGenerator = yield* IdGenerator.IdGenerator + + const approvalRequests = getApprovalRequestIdMapping(options.prompt) + const streamApprovalRequests = new Map() + + let hasToolCalls = false + + // Track annotations for current message to include in text-end metadata + const activeAnnotations: Array = [] + + type ReasoningSummaryPartStatus = "active" | "can-conclude" | "concluded" + type ReasoningPart = { + encryptedContent: string | undefined + summaryParts: Record + } + + // Track active reasoning items with state machine for proper concluding logic + const activeReasoning: Record = Object.create(null) + + const getOrCreateReasoningPart = ( + itemId: string, + encryptedContent?: string | null + ): ReasoningPart => { + const activePart = activeReasoning[itemId] + if (Predicate.isNotUndefined(activePart)) { + if (Predicate.isNotNullish(encryptedContent)) { + activePart.encryptedContent = encryptedContent + } + return activePart + } + + const reasoningPart: ReasoningPart = { + encryptedContent: Predicate.isNotNullish(encryptedContent) ? encryptedContent : undefined, + summaryParts: {} + } + activeReasoning[itemId] = reasoningPart + return reasoningPart + } + + // Track active tool calls with optional provider-specific state + const activeToolCalls: Record = {} + + const webSearchTool = options.tools.find((tool) => + Tool.isProviderDefined(tool) && + (tool.name === "OpenAiWebSearch" || + tool.name === "OpenAiWebSearchPreview") + ) as ReturnType | ReturnType | undefined + + return stream.pipe( + Stream.mapEffect(Effect.fnUntraced(function*(event) { + const parts: Array = [] + + if (!isKnownResponseStreamEvent(event)) { + return parts + } + + switch (event.type) { + case "response.created": { + const createdAt = new Date(event.response.created_at * 1000) + parts.push({ + type: "response-metadata", + id: event.response.id, + modelId: event.response.model, + timestamp: DateTime.formatIso(DateTime.fromDateUnsafe(createdAt)), + request: buildHttpRequestDetails(response.request) + }) + break + } + + case "error": { + parts.push({ type: "error", error: event }) + break + } + + case "response.completed": + case "response.incomplete": { + parts.push({ + type: "finish", + reason: InternalUtilities.resolveFinishReason( + event.response.incomplete_details?.reason, + hasToolCalls + ), + usage: getUsage(event.response.usage), + response: buildHttpResponseDetails(response), + ...toServiceTier(event.response.service_tier) + }) + break + } + + case "response.failed": { + if (event.response.error) { + parts.push({ type: "error", error: event.response.error }) + } + parts.push({ + type: "finish", + reason: "error", + usage: getUsage(event.response.usage), + response: buildHttpResponseDetails(response), + ...toServiceTier(event.response.service_tier) + }) + break + } + + case "response.output_item.added": { + switch (event.item.type) { + case "apply_patch_call": { + const toolId = event.item.call_id + const toolName = toolNameMapper.getCustomName("apply_patch") + const operation = event.item.operation + activeToolCalls[event.output_index] = { + id: toolId, + name: toolName, + applyPatch: { + hasDiff: operation.type !== "delete_file", + endEmitted: operation.type === "delete_file" + } + } + parts.push({ + type: "tool-params-start", + id: toolId, + name: toolName + }) + + if (operation.type === "delete_file") { + parts.push({ + type: "tool-params-delta", + id: toolId, + delta: JSON.stringify({ + call_id: toolId, + operation: operation + }) + }) + parts.push({ + type: "tool-params-end", + id: toolId + }) + } else { + parts.push({ + type: "tool-params-delta", + id: toolId, + delta: `{"call_id":"${InternalUtilities.escapeJSONDelta(toolId)}",` + + `"operation":{"type":"${InternalUtilities.escapeJSONDelta(operation.type)}",` + + `"path":"${InternalUtilities.escapeJSONDelta(operation.path)}","diff":"` + }) + } + break + } + + case "code_interpreter_call": { + const toolName = toolNameMapper.getCustomName("code_interpreter") + activeToolCalls[event.output_index] = { + id: event.item.id, + name: toolName, + codeInterpreter: { containerId: event.item.container_id } + } + parts.push({ + type: "tool-params-start", + id: event.item.id, + name: toolName, + providerExecuted: true + }) + parts.push({ + type: "tool-params-delta", + id: event.item.id, + delta: `{"containerId":"${event.item.container_id}","code":"` + }) + break + } + + case "computer_call": { + const toolName = toolNameMapper.getCustomName("computer_use") + activeToolCalls[event.output_index] = { + id: event.item.id, + name: toolName + } + parts.push({ + type: "tool-params-start", + id: event.item.id, + name: toolName, + providerExecuted: true + }) + break + } + + case "file_search_call": { + const toolName = toolNameMapper.getCustomName("file_search") + parts.push({ + type: "tool-call", + id: event.item.id, + name: toolName, + params: {}, + providerExecuted: true + }) + break + } + + case "function_call": { + activeToolCalls[event.output_index] = { + id: event.item.call_id, + name: event.item.name, + functionCall: { emitted: false } + } + parts.push({ + type: "tool-params-start", + id: event.item.call_id, + name: event.item.name + }) + break + } + + case "image_generation_call": { + const toolName = toolNameMapper.getCustomName("image_generation") + parts.push({ + type: "tool-call", + id: event.item.id, + name: toolName, + params: {}, + providerExecuted: true + }) + break + } + + case "mcp_call": + case "mcp_list_tools": + case "mcp_approval_request": { + // We emit MCP tool call / approvals on `output_item.done` to facilitate: + // - Aliasing tool call identifiers when an approval request id exists + // - Emit a proper tool-approval-request part for MCP approvals + break + } + + case "message": { + // Clear annotations for new message + activeAnnotations.length = 0 + parts.push({ + type: "text-start", + id: event.item.id, + metadata: { openai: makeItemIdMetadata(event.item.id) } + }) + break + } + + case "reasoning": { + const reasoningPart = getOrCreateReasoningPart(event.item.id, event.item.encrypted_content) + if (Predicate.isUndefined(reasoningPart.summaryParts[0])) { + reasoningPart.summaryParts[0] = "active" + parts.push({ + type: "reasoning-start", + id: `${event.item.id}:0`, + metadata: { + openai: { + ...makeItemIdMetadata(event.item.id), + ...makeEncryptedContentMetadata(reasoningPart.encryptedContent) + } + } + }) + } + break + } + + case "shell_call": { + const toolName = toolNameMapper.getCustomName("shell") + activeToolCalls[event.output_index] = { + id: event.item.id ?? event.item.call_id, + name: toolName + } + break + } + + case "web_search_call": { + const toolName = toolNameMapper.getCustomName( + webSearchTool?.providerName ?? "web_search" + ) + activeToolCalls[event.output_index] = { + id: event.item.id, + name: toolName + } + if (webSearchTool?.name === "OpenAiWebSearch") { + break + } + parts.push({ + type: "tool-params-start", + id: event.item.id, + name: webSearchTool?.name ?? "OpenAiWebSearch", + providerExecuted: true + }) + parts.push({ + type: "tool-params-end", + id: event.item.id + }) + parts.push({ + type: "tool-call", + id: event.item.id, + name: toolName, + params: {}, + providerExecuted: true + }) + break + } + } + + break + } + + case "response.output_item.done": { + switch (event.item.type) { + case "apply_patch_call": { + const toolCall = activeToolCalls[event.output_index] + if ( + Predicate.isNotUndefined(toolCall.applyPatch) && + !toolCall.applyPatch.endEmitted && + event.item.operation.type !== "delete_file" + ) { + if (!toolCall.applyPatch.hasDiff) { + parts.push({ + type: "tool-params-delta", + id: toolCall.id, + delta: InternalUtilities.escapeJSONDelta(event.item.operation.diff ?? "") + }) + } + parts.push({ + type: "tool-params-delta", + id: toolCall.id, + delta: `"}}` + }) + parts.push({ + type: "tool-params-end", + id: toolCall.id + }) + toolCall.applyPatch.endEmitted = true + } + // Emit the final tool call with the complete diff when the status is completed + if (Predicate.isNotUndefined(toolCall) && event.item.status === "completed") { + const toolName = toolNameMapper.getCustomName("apply_patch") + parts.push({ + type: "tool-call", + id: toolCall.id, + name: toolName, + params: { call_id: event.item.call_id, operation: event.item.operation }, + metadata: { openai: makeItemIdMetadata(event.item.id) } + }) + } + delete activeToolCalls[event.output_index] + break + } + + case "code_interpreter_call": { + delete activeToolCalls[event.output_index] + const toolName = toolNameMapper.getCustomName("code_interpreter") + parts.push({ + type: "tool-result", + id: event.item.id, + name: toolName, + isFailure: false, + result: { outputs: event.item.outputs }, + providerExecuted: true + }) + break + } + + case "computer_call": { + delete activeToolCalls[event.output_index] + const toolName = toolNameMapper.getCustomName("computer_use") + parts.push({ + type: "tool-params-end", + id: event.item.id + }) + parts.push({ + type: "tool-call", + id: event.item.id, + name: toolName, + params: {}, + providerExecuted: true + }) + parts.push({ + type: "tool-result", + id: event.item.id, + name: toolName, + isFailure: false, + result: { status: event.item.status ?? "completed" } + }) + break + } + + case "file_search_call": { + delete activeToolCalls[event.output_index] + const toolName = toolNameMapper.getCustomName("file_search") + const results = Predicate.isNotNullish(event.item.results) + ? { results: event.item.results } + : undefined + parts.push({ + type: "tool-result", + id: event.item.id, + name: toolName, + isFailure: false, + result: { ...results, status: event.item.status, queries: event.item.queries }, + providerExecuted: true + }) + break + } + + case "function_call": { + const toolCall = activeToolCalls[event.output_index] + if (Predicate.isNotUndefined(toolCall?.functionCall?.emitted) && toolCall.functionCall.emitted) { + delete activeToolCalls[event.output_index] + break + } + delete activeToolCalls[event.output_index] + + hasToolCalls = true + + const toolName = event.item.name + const toolArgs = event.item.arguments + + const toolParams = yield* Effect.try({ + try: () => Tool.unsafeSecureJsonParse(toolArgs), + catch: (cause) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "makeStreamResponse", + reason: new AiError.ToolParameterValidationError({ + toolName, + toolParams: {}, + description: `Failed securely JSON parse tool parameters: ${cause}` + }) + }) + }) + + const params = yield* transformToolCallParams(options.tools, toolName, toolParams) + + parts.push({ + type: "tool-params-end", + id: event.item.call_id + }) + + parts.push({ + type: "tool-call", + id: event.item.call_id, + name: toolName, + params, + metadata: { openai: makeItemIdMetadata(event.item.id) } + }) + + break + } + + case "image_generation_call": { + const toolName = toolNameMapper.getCustomName("image_generation") + parts.push({ + type: "tool-result", + id: event.item.id, + name: toolName, + isFailure: false, + result: { result: event.item.result }, + providerExecuted: true + }) + break + } + + case "local_shell_call": { + const toolName = toolNameMapper.getCustomName("local_shell") + parts.push({ + type: "tool-call", + id: event.item.call_id, + name: toolName, + params: { action: event.item.action }, + metadata: { openai: makeItemIdMetadata(event.item.id) } + }) + break + } + + case "mcp_call": { + const approvalRequestId = event.item.approval_request_id + + // Track approval with our own tool call identifiers + const toolId = Predicate.isNotNullish(approvalRequestId) + ? (streamApprovalRequests.get(approvalRequestId) ?? approvalRequests.get(approvalRequestId) ?? + event.item.id) + : event.item.id + + const { toolName, params } = yield* normalizeMcpToolCall({ + toolNameMapper, + toolParams: event.item.arguments, + method: "makeStreamResponse" + }) + + parts.push({ + type: "tool-call", + id: toolId, + name: toolName, + params, + providerExecuted: true + }) + + parts.push({ + type: "tool-result", + id: toolId, + name: toolName, + isFailure: false, + providerExecuted: true, + result: { + type: "mcp_call", + name: event.item.name, + arguments: event.item.arguments, + server_label: event.item.server_label, + ...(Predicate.isNotNullish(event.item.output) ? { output: event.item.output } : undefined), + ...(Predicate.isNotNullish(event.item.error) ? { error: event.item.error } : undefined) + }, + metadata: { openai: makeItemIdMetadata(event.item.id) } + }) + + break + } + + case "mcp_list_tools": { + // Skip + break + } + + case "mcp_approval_request": { + const toolId = yield* idGenerator.generateId() + const approvalRequestId = (event.item as any).approval_request_id ?? event.item.id + streamApprovalRequests.set(approvalRequestId, toolId) + const { toolName, params } = yield* normalizeMcpToolCall({ + toolNameMapper, + toolParams: event.item.arguments, + method: "makeStreamResponse" + }) + parts.push({ + type: "tool-call", + id: toolId, + name: toolName, + params, + providerExecuted: true + }) + parts.push({ + type: "tool-approval-request", + approvalId: approvalRequestId, + toolCallId: toolId + }) + break + } + + case "message": { + const annotations = activeAnnotations.length > 0 + ? { annotations: activeAnnotations.slice() } + : undefined + parts.push({ + type: "text-end", + id: event.item.id, + metadata: { openai: { ...annotations, ...makeItemIdMetadata(event.item.id) } } + }) + break + } + + case "reasoning": { + const reasoningPart = getOrCreateReasoningPart(event.item.id, event.item.encrypted_content) + for (const [summaryIndex, status] of Object.entries(reasoningPart.summaryParts)) { + if (status === "active" || status === "can-conclude") { + parts.push({ + type: "reasoning-end", + id: `${event.item.id}:${summaryIndex}`, + metadata: { + openai: { + ...makeItemIdMetadata(event.item.id), + ...makeEncryptedContentMetadata(reasoningPart.encryptedContent) + } + } + }) + } + } + delete activeReasoning[event.item.id] + break + } + + case "shell_call": { + delete activeToolCalls[event.output_index] + const toolName = toolNameMapper.getCustomName("shell") + parts.push({ + type: "tool-call", + id: event.item.id ?? event.item.call_id, + name: toolName, + params: { action: event.item.action }, + metadata: { openai: makeItemIdMetadata(event.item.id) } + }) + break + } + + case "web_search_call": { + delete activeToolCalls[event.output_index] + const toolName = toolNameMapper.getCustomName( + webSearchTool?.name ?? "web_search" + ) + if (webSearchTool?.name === "OpenAiWebSearch") { + parts.push({ + type: "tool-call", + id: event.item.id, + name: toolName, + params: { action: event.item.action }, + providerExecuted: true + }) + } + parts.push({ + type: "tool-result", + id: event.item.id, + name: toolName, + isFailure: false, + result: { action: event.item.action, status: event.item.status }, + providerExecuted: true + }) + break + } + } + + break + } + + case "response.output_text.delta": { + parts.push({ + type: "text-delta", + id: event.item_id, + delta: event.delta + }) + break + } + + case "response.output_text.annotation.added": { + const annotation = event.annotation as typeof OpenAiSchema.Annotation.Encoded + // Track annotation for text-end metadata + activeAnnotations.push(annotation) + if (annotation.type === "container_file_citation") { + parts.push({ + type: "source", + sourceType: "document", + id: yield* idGenerator.generateId(), + mediaType: "text/plain", + title: annotation.filename, + fileName: annotation.filename, + metadata: { + openai: { + type: annotation.type, + fileId: annotation.file_id, + containerId: annotation.container_id + } + } + }) + } else if (annotation.type === "file_citation") { + parts.push({ + type: "source", + sourceType: "document", + id: yield* idGenerator.generateId(), + mediaType: "text/plain", + title: annotation.filename, + fileName: annotation.filename, + metadata: { + openai: { + type: annotation.type, + fileId: annotation.file_id, + index: annotation.index + } + } + }) + } else if (annotation.type === "file_path") { + parts.push({ + type: "source", + sourceType: "document", + id: yield* idGenerator.generateId(), + mediaType: "application/octet-stream", + title: annotation.file_id, + fileName: annotation.file_id, + metadata: { + openai: { + type: annotation.type, + fileId: annotation.file_id, + index: annotation.index + } + } + }) + } else if (annotation.type === "url_citation") { + parts.push({ + type: "source", + sourceType: "url", + id: yield* idGenerator.generateId(), + url: annotation.url, + title: annotation.title, + metadata: { + openai: { + type: annotation.type, + startIndex: annotation.start_index, + endIndex: annotation.end_index + } + } + }) + } + break + } + + case "response.function_call_arguments.delta": { + const toolCallPart = activeToolCalls[event.output_index] + if (Predicate.isNotUndefined(toolCallPart)) { + parts.push({ + type: "tool-params-delta", + id: toolCallPart.id, + delta: event.delta + }) + } + break + } + + case "response.function_call_arguments.done": { + const toolCall = activeToolCalls[event.output_index] + if ( + Predicate.isNotUndefined(toolCall?.functionCall) && + !toolCall.functionCall.emitted + ) { + hasToolCalls = true + + const toolParams = yield* Effect.try({ + try: () => Tool.unsafeSecureJsonParse(event.arguments), + catch: (cause) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "makeStreamResponse", + reason: new AiError.ToolParameterValidationError({ + toolName: toolCall.name, + toolParams: {}, + description: `Failed securely JSON parse tool parameters: ${cause}` + }) + }) + }) + + const params = yield* transformToolCallParams(options.tools, toolCall.name, toolParams) + + parts.push({ + type: "tool-params-end", + id: toolCall.id + }) + + parts.push({ + type: "tool-call", + id: toolCall.id, + name: toolCall.name, + params, + metadata: { openai: makeItemIdMetadata(event.item_id) } + }) + + toolCall.functionCall.emitted = true + } + break + } + + case "response.apply_patch_call_operation_diff.delta": { + const toolCall = activeToolCalls[event.output_index] + if (Predicate.isNotUndefined(toolCall?.applyPatch)) { + parts.push({ + type: "tool-params-delta", + id: toolCall.id, + delta: InternalUtilities.escapeJSONDelta(event.delta) + }) + toolCall.applyPatch.hasDiff = true + } + break + } + + case "response.apply_patch_call_operation_diff.done": { + const toolCall = activeToolCalls[event.output_index] + if (Predicate.isNotUndefined(toolCall?.applyPatch) && !toolCall.applyPatch.endEmitted) { + if (!toolCall.applyPatch.hasDiff && Predicate.isNotUndefined(event.delta)) { + parts.push({ + type: "tool-params-delta", + id: toolCall.id, + delta: InternalUtilities.escapeJSONDelta(event.delta) + }) + toolCall.applyPatch.hasDiff = true + } + parts.push({ + type: "tool-params-delta", + id: toolCall.id, + delta: `"}}` + }) + parts.push({ + type: "tool-params-end", + id: toolCall.id + }) + toolCall.applyPatch.endEmitted = true + } + break + } + + case "response.code_interpreter_call_code.delta": { + const toolCall = activeToolCalls[event.output_index] + if (Predicate.isNotUndefined(toolCall)) { + parts.push({ + type: "tool-params-delta", + id: toolCall.id, + delta: InternalUtilities.escapeJSONDelta(event.delta) + }) + } + break + } + + case "response.code_interpreter_call_code.done": { + const toolCall = activeToolCalls[event.output_index] + if (Predicate.isNotUndefined(toolCall) && Predicate.isNotUndefined(toolCall.codeInterpreter)) { + const toolName = toolNameMapper.getCustomName("code_interpreter") + parts.push({ + type: "tool-params-delta", + id: toolCall.id, + delta: "\"}" + }) + parts.push({ type: "tool-params-end", id: toolCall.id }) + parts.push({ + type: "tool-call", + id: toolCall.id, + name: toolName, + params: { + code: event.code, + container_id: toolCall.codeInterpreter.containerId + }, + providerExecuted: true + }) + } + break + } + + case "response.image_generation_call.partial_image": { + const toolName = toolNameMapper.getCustomName("image_generation") + parts.push({ + type: "tool-result", + id: event.item_id, + name: toolName, + isFailure: false, + providerExecuted: false, + result: { result: event.partial_image_b64 }, + preliminary: true + }) + break + } + + case "response.reasoning_summary_part.added": { + const reasoningPart = getOrCreateReasoningPart(event.item_id) + if (event.summary_index > 0) { + // Conclude all can-conclude parts before starting new one + for (const [summaryIndex, status] of Object.entries(reasoningPart.summaryParts)) { + if (status === "can-conclude") { + parts.push({ + type: "reasoning-end", + id: `${event.item_id}:${summaryIndex}`, + metadata: { + openai: { + ...makeItemIdMetadata(event.item_id), + ...makeEncryptedContentMetadata(reasoningPart.encryptedContent) + } + } + }) + reasoningPart.summaryParts[Number(summaryIndex)] = "concluded" + } + } + } + + if (Predicate.isUndefined(reasoningPart.summaryParts[event.summary_index])) { + reasoningPart.summaryParts[event.summary_index] = "active" + parts.push({ + type: "reasoning-start", + id: `${event.item_id}:${event.summary_index}`, + metadata: { + openai: { + ...makeItemIdMetadata(event.item_id), + ...makeEncryptedContentMetadata(reasoningPart.encryptedContent) + } + } + }) + } + break + } + + case "response.reasoning_summary_text.delta": { + parts.push({ + type: "reasoning-delta", + id: `${event.item_id}:${event.summary_index}`, + delta: event.delta, + metadata: { openai: makeItemIdMetadata(event.item_id) } + }) + break + } + + case "response.reasoning_summary_part.done": { + const reasoningPart = getOrCreateReasoningPart(event.item_id) + // When OpenAI stores message data, we can immediately conclude the + // reasoning part given that we do not need the encrypted content + if (config.store === true) { + parts.push({ + type: "reasoning-end", + id: `${event.item_id}:${event.summary_index}`, + metadata: { openai: makeItemIdMetadata(event.item_id) } + }) + // Mark the summary part concluded + reasoningPart.summaryParts[event.summary_index] = "concluded" + } else { + // Mark the summary part as can-conclude given we still need a + // final summary part with the encrypted content + reasoningPart.summaryParts[event.summary_index] = "can-conclude" + } + break + } + } + + return parts + })), + Stream.flattenIterable + ) + } +) + +// ============================================================================= +// Telemetry +// ============================================================================= + +const annotateRequest = ( + span: Span, + request: typeof OpenAiSchema.CreateResponse.Encoded +): void => { + addGenAIAnnotations(span, { + system: "openai", + operation: { name: "chat" }, + request: { + model: request.model as string, + temperature: request.temperature as number | undefined, + topP: request.top_p as number | undefined, + maxTokens: request.max_output_tokens as number | undefined + }, + openai: { + request: { + responseFormat: (request.text as any)?.format?.type, + serviceTier: request.service_tier as string | undefined + } + } + }) +} + +const annotateResponse = (span: Span, response: OpenAiSchema.Response): void => { + const finishReason = response.incomplete_details?.reason as string | undefined + addGenAIAnnotations(span, { + response: { + id: response.id, + model: response.model as string, + finishReasons: Predicate.isNotUndefined(finishReason) ? [finishReason] : undefined + }, + usage: { + inputTokens: response.usage?.input_tokens as number | undefined, + outputTokens: response.usage?.output_tokens as number | undefined + }, + openai: { + response: { + serviceTier: response.service_tier as string | undefined + } + } + }) +} + +const annotateStreamResponse = (span: Span, part: Response.StreamPartEncoded) => { + if (part.type === "response-metadata") { + addGenAIAnnotations(span, { + response: { + id: part.id, + model: part.modelId + } + }) + } + if (part.type === "finish") { + const serviceTier = (part.metadata as any)?.openai?.serviceTier as string | undefined + addGenAIAnnotations(span, { + response: { + finishReasons: [part.reason] + }, + usage: { + inputTokens: part.usage.inputTokens.total, + outputTokens: part.usage.outputTokens.total + }, + openai: { + response: { serviceTier } + } + }) + } +} + +// ============================================================================= +// Tool Conversion +// ============================================================================= + +type OpenAiToolChoice = typeof OpenAiSchema.CreateResponse.Encoded["tool_choice"] + +const prepareTools = Effect.fnUntraced(function*>({ + config, + options, + toolNameMapper +}: { + readonly config: typeof Config.Service + readonly options: LanguageModel.ProviderOptions + readonly toolNameMapper: Tool.NameMapper +}): Effect.fn.Return<{ + readonly tools: ReadonlyArray | undefined + readonly toolChoice: OpenAiToolChoice | undefined +}, AiError.AiError> { + // Return immediately if no tools are in the toolkit + if (options.tools.length === 0) { + return { tools: undefined, toolChoice: undefined } + } + + const tools: Array = [] + let toolChoice: OpenAiToolChoice | undefined = undefined + + // Filter the incoming tools down to the set of allowed tools as indicated by + // the tool choice. This must be done here given that there is no tool name + // in OpenAI's provider-defined tools, so there would be no way to perform + // this filter otherwise + let allowedTools = options.tools + if (typeof options.toolChoice === "object" && "oneOf" in options.toolChoice) { + const allowedToolNames = new Set(options.toolChoice.oneOf) + allowedTools = options.tools.filter((tool) => allowedToolNames.has(tool.name)) + toolChoice = options.toolChoice.mode === "required" ? "required" : "auto" + } + + // Convert the tools in the toolkit to the provider-defined format + for (const tool of allowedTools) { + if (Tool.isUserDefined(tool) || Tool.isDynamic(tool)) { + const strict = Tool.getStrictMode(tool) ?? config.strictJsonSchema ?? true + const description = Tool.getDescription(tool) + const parameters = yield* tryToolJsonSchema(tool, "prepareTools") + tools.push({ + type: "function", + name: tool.name, + parameters, + strict, + ...(Predicate.isNotUndefined(description) ? { description } : undefined) + }) + } + + if (Tool.isProviderDefined(tool)) { + const openAiTool = tool as OpenAiTool.OpenAiTool + switch (openAiTool.name) { + case "OpenAiApplyPatch": { + tools.push({ type: "apply_patch" }) + break + } + case "OpenAiCodeInterpreter": { + const args = yield* Schema.decodeUnknownEffect(openAiTool.argsSchema)(tool.args).pipe( + Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareTools", + reason: new AiError.ToolConfigurationError({ + toolName: openAiTool.name, + description: error.message + }) + }) + ) + ) + tools.push({ + ...args, + type: "code_interpreter" + }) + break + } + case "OpenAiFileSearch": { + const args = yield* Schema.decodeUnknownEffect(openAiTool.argsSchema)(tool.args).pipe( + Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareTools", + reason: new AiError.ToolConfigurationError({ + toolName: openAiTool.name, + description: error.message + }) + }) + ) + ) + tools.push({ + ...args, + type: "file_search" + }) + break + } + case "OpenAiShell": { + tools.push({ type: "shell" }) + break + } + case "OpenAiImageGeneration": { + const args = yield* Schema.decodeUnknownEffect(openAiTool.argsSchema)(tool.args).pipe( + Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareTools", + reason: new AiError.ToolConfigurationError({ + toolName: openAiTool.name, + description: error.message + }) + }) + ) + ) + tools.push({ + ...args, + type: "image_generation" + }) + break + } + case "OpenAiLocalShell": { + tools.push({ type: "local_shell" }) + break + } + case "OpenAiMcp": { + const args = yield* Schema.decodeUnknownEffect(openAiTool.argsSchema)(tool.args).pipe( + Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareTools", + reason: new AiError.ToolConfigurationError({ + toolName: openAiTool.name, + description: error.message + }) + }) + ) + ) + tools.push({ + ...args, + type: "mcp" + }) + break + } + case "OpenAiWebSearch": { + const args = yield* Schema.decodeUnknownEffect(openAiTool.argsSchema)(tool.args).pipe( + Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareTools", + reason: new AiError.ToolConfigurationError({ + toolName: openAiTool.name, + description: error.message + }) + }) + ) + ) + tools.push({ + ...args, + type: "web_search" + }) + break + } + case "OpenAiWebSearchPreview": { + const args = yield* Schema.decodeUnknownEffect(openAiTool.argsSchema)(tool.args).pipe( + Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareTools", + reason: new AiError.ToolConfigurationError({ + toolName: openAiTool.name, + description: error.message + }) + }) + ) + ) + tools.push({ + ...args, + type: "web_search_preview" + }) + break + } + default: { + return yield* AiError.make({ + module: "OpenAiLanguageModel", + method: "prepareTools", + reason: new AiError.InvalidRequestError({ + description: `Unknown provider-defined tool '${tool.name}'` + }) + }) + } + } + } + } + + if (options.toolChoice === "auto" || options.toolChoice === "none" || options.toolChoice === "required") { + toolChoice = options.toolChoice + } + + if (typeof options.toolChoice === "object" && "tool" in options.toolChoice) { + const toolName = toolNameMapper.getProviderName(options.toolChoice.tool) + const providerNames = toolNameMapper.providerNames + if (providerNames.includes(toolName)) { + toolChoice = { type: toolName as any } + } else { + toolChoice = { type: "function", name: options.toolChoice.tool } + } + } + + return { tools, toolChoice } +}) + +// ============================================================================= +// Utilities +// ============================================================================= + +const isFileId = (data: string, config: typeof Config.Service): boolean => + config.fileIdPrefixes != null && config.fileIdPrefixes.some((prefix) => data.startsWith(prefix)) + +const getItemId = ( + part: + | Prompt.TextPart + | Prompt.ReasoningPart + | Prompt.ToolCallPart + | Prompt.ToolResultPart +): string | null => part.options.openai?.itemId ?? null +const getStatus = ( + part: + | Prompt.TextPart + | Prompt.ToolCallPart + | Prompt.ToolResultPart +): typeof OpenAiSchema.MessageStatus.Encoded | null => part.options.openai?.status ?? null +const getEncryptedContent = ( + part: Prompt.ReasoningPart +): string | null => part.options.openai?.encryptedContent ?? null + +const getImageDetail = (part: Prompt.FilePart): ImageDetail => part.options.openai?.imageDetail ?? "auto" + +const getPromptCacheBreakpoint = ( + input: Prompt.SystemMessage | Prompt.TextPart +) => { + const promptCacheBreakpoint = input.options.openai?.promptCacheBreakpoint + return Predicate.isNotNullish(promptCacheBreakpoint) ? { prompt_cache_breakpoint: promptCacheBreakpoint } : undefined +} + +const makeItemIdMetadata = (itemId: string | undefined) => Predicate.isNotUndefined(itemId) ? { itemId } : {} + +const makeEncryptedContentMetadata = (encryptedContent: string | null | undefined) => + Predicate.isNotNullish(encryptedContent) ? { encryptedContent } : undefined + +const unsupportedSchemaError = (error: unknown, method: string): AiError.AiError => + AiError.make({ + module: "OpenAiLanguageModel", + method, + reason: new AiError.UnsupportedSchemaError({ + description: error instanceof Error ? error.message : String(error) + }) + }) + +const tryCodecTransform = (schema: S, method: string) => + Effect.try({ + try: () => toCodecOpenAI(schema), + catch: (error) => unsupportedSchemaError(error, method) + }) + +const tryJsonSchema = (schema: S, method: string) => + Effect.try({ + try: () => Tool.getJsonSchemaFromSchema(schema, { transformer: toCodecOpenAI }), + catch: (error) => unsupportedSchemaError(error, method) + }) + +const tryToolJsonSchema = (tool: T, method: string) => + Effect.try({ + try: () => Tool.getJsonSchema(tool, { transformer: toCodecOpenAI }), + catch: (error) => unsupportedSchemaError(error, method) + }) + +const prepareResponseFormat = Effect.fnUntraced(function*({ config, options }: { + readonly config: typeof Config.Service + readonly options: LanguageModel.ProviderOptions +}): Effect.fn.Return { + if (options.responseFormat.type === "json") { + const name = options.responseFormat.objectName + const schema = options.responseFormat.schema + const jsonSchema = yield* tryJsonSchema(schema, "prepareResponseFormat") + return { + type: "json_schema", + name, + description: AST.resolveDescription(schema.ast) ?? "Response with a JSON object", + schema: jsonSchema, + strict: config.strictJsonSchema ?? true + } + } + return { type: "text" } +}) + +interface ModelCapabilities { + readonly isReasoningModel: boolean + readonly systemMessageMode: "remove" | "system" | "developer" + readonly supportsFlexProcessing: boolean + readonly supportsPriorityProcessing: boolean + /** + * Allow temperature, topP, logProbs when reasoningEffort is none. + */ + readonly supportsNonReasoningParameters: boolean +} + +const getModelCapabilities = (modelId: string): ModelCapabilities => { + const supportsFlexProcessing = modelId.startsWith("o3") || + modelId.startsWith("o4-mini") || + (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat")) + + const supportsPriorityProcessing = modelId.startsWith("gpt-4") || + modelId.startsWith("gpt-5-mini") || + (modelId.startsWith("gpt-5") && + !modelId.startsWith("gpt-5-nano") && + !modelId.startsWith("gpt-5-chat")) || + modelId.startsWith("o3") || + modelId.startsWith("o4-mini") + + // Use allowlist approach: only known reasoning models should use 'developer' role + // This prevents issues with fine-tuned models, third-party models, and custom models + const isReasoningModel = modelId.startsWith("o1") || + modelId.startsWith("o3") || + modelId.startsWith("o4-mini") || + modelId.startsWith("codex-mini") || + modelId.startsWith("computer-use-preview") || + (modelId.startsWith("gpt-5") && !modelId.startsWith("gpt-5-chat")) + + // https://platform.openai.com/docs/guides/latest-model#gpt-5-1-parameter-compatibility + // GPT-5.1 and GPT-5.2 support temperature, topP, logProbs when reasoningEffort is none + const supportsNonReasoningParameters = modelId.startsWith("gpt-5.1") || modelId.startsWith("gpt-5.2") + + const systemMessageMode = isReasoningModel ? "developer" : "system" + + return { + supportsFlexProcessing, + supportsPriorityProcessing, + isReasoningModel, + systemMessageMode, + supportsNonReasoningParameters + } +} + +const getApprovalRequestIdMapping = (prompt: Prompt.Prompt): ReadonlyMap => { + const mapping = new Map() + + for (const message of prompt.content) { + if (message.role !== "assistant") { + continue + } + + for (const part of message.content) { + if (part.type !== "tool-call") { + continue + } + + const approvalRequestId = part.options.openai?.approvalRequestId + + if (Predicate.isNotNullish(approvalRequestId)) { + mapping.set(approvalRequestId, part.id) + } + } + } + + return mapping +} + +const normalizeMcpToolCall = Effect.fnUntraced(function*>({ + toolNameMapper, + toolParams, + method +}: { + readonly toolNameMapper: Tool.NameMapper + readonly toolParams: unknown + readonly method: string +}): Effect.fn.Return<{ + readonly toolName: string + readonly params: unknown +}, AiError.AiError> { + const toolName = toolNameMapper.getCustomName("mcp") + + if (typeof toolParams !== "string") { + return { toolName, params: toolParams } + } + + const params = yield* Effect.try({ + try: () => Tool.unsafeSecureJsonParse(toolParams), + catch: (cause) => + AiError.make({ + module: "OpenAiLanguageModel", + method, + reason: new AiError.ToolParameterValidationError({ + toolName, + toolParams, + description: `Failed to securely JSON parse tool parameters: ${cause}` + }) + }) + }) + + return { toolName, params } +}) + +const getUsage = (usage: OpenAiSchema.ResponseUsage | null | undefined): Response.Usage => { + if (Predicate.isNullish(usage)) { + return { + inputTokens: { + uncached: undefined, + total: undefined, + cacheRead: undefined, + cacheWrite: undefined + }, + outputTokens: { + total: undefined, + text: undefined, + reasoning: undefined + } + } + } + + const inputTokens = usage.input_tokens + const outputTokens = usage.output_tokens + const cachedTokens = getUsageTokenDetail(usage.input_tokens_details, "cached_tokens") ?? 0 + const cacheWriteTokens = getUsageTokenDetail(usage.input_tokens_details, "cache_write_tokens") + const reasoningTokens = getUsageTokenDetail(usage.output_tokens_details, "reasoning_tokens") ?? 0 + + return { + inputTokens: { + uncached: inputTokens - cachedTokens, + total: inputTokens, + cacheRead: cachedTokens, + cacheWrite: cacheWriteTokens + }, + outputTokens: { + total: outputTokens, + text: outputTokens - reasoningTokens, + reasoning: reasoningTokens + } + } +} + +type ServiceTier = "default" | "auto" | "flex" | "scale" | "priority" | null + +const toServiceTier = (value: string | undefined): { + readonly metadata: { + readonly openai: { + readonly serviceTier: ServiceTier + } + } +} | undefined => { + switch (value) { + case "default": + case "auto": + case "flex": + case "scale": + case "priority": + return { metadata: { openai: { serviceTier: value } } } + default: + return undefined + } +} + +const getUsageTokenDetail = (details: unknown, key: string): number | undefined => + Predicate.hasProperty(details, key) && typeof details[key] === "number" ? details[key] : undefined + +const transformToolCallParams = Effect.fnUntraced(function*>( + tools: Tools, + toolName: string, + toolParams: unknown +): Effect.fn.Return { + const tool = tools.find((tool) => tool.name === toolName) + + if (Predicate.isUndefined(tool)) { + return yield* AiError.make({ + module: "OpenAiLanguageModel", + method: "makeResponse", + reason: new AiError.ToolNotFoundError({ + toolName, + availableTools: tools.map((tool) => tool.name) + }) + }) + } + + const { codec } = yield* tryCodecTransform(tool.parametersSchema, "makeResponse") + + const transform = Schema.decodeEffect(codec) + + return yield* ( + transform(toolParams) as Effect.Effect + ).pipe(Effect.mapError((error) => + AiError.make({ + module: "OpenAiLanguageModel", + method: "makeResponse", + reason: new AiError.ToolParameterValidationError({ + toolName, + toolParams, + description: formatIssue(error.issue) + }) + }) + )) +}) diff --git a/packages/effect-ai-openai/src/OpenAiSchema.ts b/packages/effect-ai-openai/src/OpenAiSchema.ts new file mode 100644 index 0000000..055b3c2 --- /dev/null +++ b/packages/effect-ai-openai/src/OpenAiSchema.ts @@ -0,0 +1,1331 @@ +/** + * The `OpenAiSchema` module defines the request, response, streaming, and + * embedding schemas used by the handwritten OpenAI client. These schemas are + * the transport boundary for JSON sent to and decoded from the Responses and + * embeddings endpoints. + * + * @since 4.0.0 + */ +import * as Effect from "effect/Effect" +import * as Predicate from "effect/Predicate" +import * as Schema from "effect/Schema" +import * as SchemaTransformation from "effect/SchemaTransformation" + +const UnknownRecord = Schema.Record(Schema.String, Schema.Unknown) + +const JsonObject = Schema.Record(Schema.String, Schema.Unknown) + +const MessageRole = Schema.Literals(["system", "developer", "user", "assistant"]) + +const ImageDetail = Schema.Literals(["low", "high", "auto"]) + +const PromptCacheBreakpoint = Schema.Struct({ + mode: Schema.Literal("explicit") +}) + +/** + * Schema for optional `include` values supported by the local handwritten + * Responses client schema. + * + * **Details** + * + * These values request additional response fields such as image URLs, encrypted + * reasoning content, output logprobs, code interpreter outputs, or web search + * sources. This schema enumerates the include values supported by this client + * path. + * + * @category schemas + * @since 4.0.0 + */ +export const IncludeEnum = Schema.Literals([ + "message.input_image.image_url", + "reasoning.encrypted_content", + "message.output_text.logprobs", + "code_interpreter_call.outputs", + "web_search_call.action.sources" +]) + +/** + * Type of optional `include` values accepted by OpenAI Responses requests. + * + * @category models + * @since 4.0.0 + */ +export type IncludeEnum = typeof IncludeEnum.Type + +/** + * Schema for lifecycle statuses shared by messages, reasoning items, and tool calls. + * + * **Details** + * + * Accepted values are `"in_progress"`, `"completed"`, and `"incomplete"`. + * This item-level status is used by message, reasoning, and tool-call shapes. + * + * @category schemas + * @since 4.0.0 + */ +export const MessageStatus = Schema.Literals(["in_progress", "completed", "incomplete"]) + +/** + * Lifecycle status shared by messages, reasoning items, and tool calls. + * + * **Details** + * + * Accepted values are `"in_progress"`, `"completed"`, and `"incomplete"`. + * + * @category models + * @since 4.0.0 + */ +export type MessageStatus = typeof MessageStatus.Type + +const InputTextContent = Schema.Struct({ + type: Schema.Literal("input_text"), + text: Schema.String, + prompt_cache_breakpoint: Schema.optional(PromptCacheBreakpoint) +}) + +const InputImageContent = Schema.Struct({ + type: Schema.Literal("input_image"), + image_url: Schema.optionalKey(Schema.NullOr(Schema.String)), + file_id: Schema.optionalKey(Schema.NullOr(Schema.String)), + detail: Schema.optionalKey(Schema.NullOr(ImageDetail)) +}) + +const InputFileContent = Schema.Struct({ + type: Schema.Literal("input_file"), + file_id: Schema.optionalKey(Schema.NullOr(Schema.String)), + filename: Schema.optionalKey(Schema.String), + file_url: Schema.optionalKey(Schema.String), + file_data: Schema.optionalKey(Schema.String) +}) + +/** + * Schema for content blocks accepted in OpenAI Responses input messages. + * + * **Details** + * + * Accepted block variants are `input_text`, `input_image`, and `input_file`. + * + * @see {@link InputItem} for request input item shapes that can contain these content blocks + * + * @category schemas + * @since 4.0.0 + */ +export const InputContent = Schema.Union([ + InputTextContent, + InputImageContent, + InputFileContent +]) + +/** + * Content block accepted in OpenAI Responses input messages. + * + * **Details** + * + * Accepted block variants are `input_text`, `input_image`, and `input_file`. + * + * @category models + * @since 4.0.0 + */ +export type InputContent = typeof InputContent.Type + +/** + * Schema for a text block containing a model-provided reasoning summary. + * + * **Details** + * + * The decoded shape is `type: "summary_text"` plus `text` containing the + * reasoning summary text. + * + * @see {@link ReasoningItem} for reasoning output items that contain summary text blocks + * + * @category schemas + * @since 4.0.0 + */ +export const SummaryTextContent = Schema.Struct({ + type: Schema.Literal("summary_text"), + text: Schema.String +}) + +/** + * Text content block used for model-provided reasoning summaries. + * + * @category models + * @since 4.0.0 + */ +export type SummaryTextContent = typeof SummaryTextContent.Type + +const ReasoningTextContent = Schema.Struct({ + type: Schema.Literal("reasoning_text"), + text: Schema.String +}) + +const RefusalContent = Schema.Struct({ + type: Schema.Literal("refusal"), + refusal: Schema.String +}) + +const TextContent = Schema.Struct({ + type: Schema.Literal("text"), + text: Schema.String +}) + +const ComputerScreenshotContent = Schema.Struct({ + type: Schema.Literal("computer_screenshot"), + image_url: Schema.NullOr(Schema.String), + file_id: Schema.NullOr(Schema.String) +}) + +const FileCitationAnnotation = Schema.Struct({ + type: Schema.Literal("file_citation"), + file_id: Schema.String, + index: Schema.Int, + filename: Schema.String +}) + +const UrlCitationAnnotation = Schema.Struct({ + type: Schema.Literal("url_citation"), + url: Schema.String, + start_index: Schema.Int, + end_index: Schema.Int, + title: Schema.String +}) + +const ContainerFileCitationAnnotation = Schema.Struct({ + type: Schema.Literal("container_file_citation"), + container_id: Schema.String, + file_id: Schema.String, + start_index: Schema.Int, + end_index: Schema.Int, + filename: Schema.String +}) + +const FilePathAnnotation = Schema.Struct({ + type: Schema.Literal("file_path"), + file_id: Schema.String, + index: Schema.Int +}) + +/** + * Schema for citation and file-path annotations attached to output text content. + * + * **Details** + * + * Accepts annotation objects discriminated by `type`: `file_citation`, + * `url_citation`, `container_file_citation`, or `file_path`. + * + * @category schemas + * @since 4.0.0 + */ +export const Annotation = Schema.Union([ + FileCitationAnnotation, + UrlCitationAnnotation, + ContainerFileCitationAnnotation, + FilePathAnnotation +]) + +/** + * Citation or file-path annotation attached to output text content. + * + * **Details** + * + * Accepted annotation variants are `file_citation`, `url_citation`, + * `container_file_citation`, and `file_path`. + * + * @category models + * @since 4.0.0 + */ +export type Annotation = typeof Annotation.Type + +const OutputTextContent = Schema.Struct({ + type: Schema.Literal("output_text"), + text: Schema.String, + annotations: Schema.Array(Annotation), + logprobs: Schema.optionalKey(Schema.Array(Schema.Unknown)) +}) + +const OutputMessageContent = Schema.Union([ + InputTextContent, + OutputTextContent, + TextContent, + SummaryTextContent, + ReasoningTextContent, + RefusalContent, + InputImageContent, + ComputerScreenshotContent, + InputFileContent +]) + +const OutputMessage = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("message"), + role: Schema.Literal("assistant"), + content: Schema.Array(OutputMessageContent), + status: MessageStatus +}) + +/** + * Schema for a reasoning output item containing encrypted content, summaries, and optional reasoning text. + * + * **When to use** + * + * Use when decoding or encoding OpenAI Responses reasoning items that may be + * carried into later request input. + * + * **Details** + * + * Reasoning items represent model reasoning content. `summary` is required, + * while `content` and `status` are optional. + * + * **Gotchas** + * + * `encrypted_content` is populated only when `reasoning.encrypted_content` is + * requested through `include`. + * + * @see {@link InputItem} for request input items that can carry reasoning items + * @see {@link IncludeEnum} for requesting encrypted reasoning content + * + * @category schemas + * @since 4.0.0 + */ +export const ReasoningItem = Schema.Struct({ + type: Schema.Literal("reasoning"), + id: Schema.String, + encrypted_content: Schema.optionalKey(Schema.NullOr(Schema.String)), + summary: Schema.Array(SummaryTextContent), + content: Schema.optionalKey(Schema.Array(ReasoningTextContent)), + status: Schema.optionalKey(MessageStatus) +}) + +/** + * Reasoning output item containing encrypted content, summaries, and optional reasoning text. + * + * **When to use** + * + * Use when typing OpenAI Responses reasoning items that may be carried into + * later request input. + * + * **Details** + * + * Reasoning items represent model reasoning content. `summary` is required, + * while `content` and `status` are optional. + * + * **Gotchas** + * + * `encrypted_content` is populated only when `reasoning.encrypted_content` is + * requested through `include`. + * + * @category models + * @since 4.0.0 + */ +export type ReasoningItem = typeof ReasoningItem.Type + +const FunctionCall = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + type: Schema.Literal("function_call"), + call_id: Schema.String, + name: Schema.String, + arguments: Schema.String, + status: Schema.optionalKey(MessageStatus) +}) + +const FunctionCallOutput = Schema.Struct({ + id: Schema.optionalKey(Schema.NullOr(Schema.String)), + type: Schema.Literal("function_call_output"), + call_id: Schema.String, + output: Schema.Union([ + Schema.String, + Schema.Array(InputContent) + ]), + status: Schema.optionalKey(Schema.NullOr(MessageStatus)) +}) + +const ItemReference = Schema.Struct({ + type: Schema.Literal("item_reference"), + id: Schema.String +}) + +const LocalShellCall = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + type: Schema.Literal("local_shell_call"), + call_id: Schema.String, + action: Schema.Unknown, + status: Schema.optionalKey(MessageStatus) +}) + +const LocalShellCallOutput = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + type: Schema.Literal("local_shell_call_output"), + call_id: Schema.String, + output: Schema.Unknown, + status: Schema.optionalKey(MessageStatus) +}) + +const ShellCall = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + type: Schema.Literal("shell_call"), + call_id: Schema.String, + action: Schema.Unknown, + status: Schema.optionalKey(MessageStatus) +}) + +const ShellCallOutput = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + type: Schema.Literal("shell_call_output"), + call_id: Schema.String, + output: Schema.Unknown, + status: Schema.optionalKey(MessageStatus) +}) + +const ApplyPatchCallOutput = Schema.Struct({ + id: Schema.optionalKey(Schema.String), + type: Schema.Literal("apply_patch_call_output"), + call_id: Schema.String, + status: Schema.optionalKey(MessageStatus), + output: Schema.optionalKey(Schema.Unknown) +}) + +const McpApprovalResponse = Schema.Struct({ + type: Schema.Literal("mcp_approval_response"), + approval_request_id: Schema.String, + approve: Schema.Boolean +}) + +const RequestMessageItem = Schema.Struct({ + type: Schema.optionalKey(Schema.Literal("message")), + role: MessageRole, + status: Schema.optionalKey(MessageStatus), + content: Schema.Union([ + Schema.String, + Schema.Array(InputContent) + ]) +}) + +/** + * Schema for item shapes accepted by an OpenAI Responses request `input` field. + * + * **When to use** + * + * Use when validating structured `CreateResponse.input` array items. + * + * **Details** + * + * Accepted item families include request/output messages, function call and + * function call output, reasoning items, item references, shell and local shell + * calls and outputs, apply-patch output, and MCP approval responses. + * + * @see {@link CreateResponse} for the request schema that consumes input items + * @see {@link InputContent} for content blocks inside message items + * + * @category schemas + * @since 4.0.0 + */ +export const InputItem = Schema.Union([ + RequestMessageItem, + OutputMessage, + FunctionCall, + FunctionCallOutput, + ReasoningItem, + ItemReference, + LocalShellCall, + LocalShellCallOutput, + ShellCall, + ShellCallOutput, + ApplyPatchCallOutput, + McpApprovalResponse +]) + +/** + * Item shape accepted by an OpenAI Responses request `input` field. + * + * **When to use** + * + * Use when typing structured `CreateResponse.input` array items. + * + * **Details** + * + * Accepted item families include request/output messages, function call and + * function call output, reasoning items, item references, shell and local shell + * calls and outputs, apply-patch output, and MCP approval responses. + * + * @category models + * @since 4.0.0 + */ +export type InputItem = typeof InputItem.Type + +const FunctionTool = Schema.Struct({ + type: Schema.Literal("function"), + name: Schema.String, + description: Schema.optionalKey(Schema.NullOr(Schema.String)), + parameters: Schema.optionalKey(Schema.NullOr(JsonObject)), + strict: Schema.optionalKey(Schema.NullOr(Schema.Boolean)) +}) + +const CustomTool = Schema.Struct({ + type: Schema.Literal("custom"), + name: Schema.String, + description: Schema.optionalKey(Schema.String), + format: Schema.optionalKey(Schema.Unknown) +}) + +const ProviderDefinedTool = Schema.StructWithRest( + Schema.Struct({ + type: Schema.Literals([ + "apply_patch", + "code_interpreter", + "file_search", + "image_generation", + "local_shell", + "mcp", + "shell", + "web_search", + "web_search_preview" + ]) + }), + [UnknownRecord] +) + +/** + * Schema for tool definitions that can be supplied to an OpenAI Responses request. + * + * **When to use** + * + * Use when validating or encoding the `tools` array for a Responses request, + * including provider-defined tool records with provider-specific fields. + * + * **Details** + * + * Accepted variants are function tools, custom tools, and provider-defined + * OpenAI tools. Provider-defined `type` literals include `apply_patch`, + * `code_interpreter`, `file_search`, `image_generation`, `local_shell`, `mcp`, + * `shell`, `web_search`, and `web_search_preview`. + * + * **Gotchas** + * + * Provider-defined tools use `Schema.StructWithRest`, so this schema checks the + * provider tool `type` and permits additional provider fields rather than fully + * validating every provider-specific tool payload. + * + * @see {@link ToolChoice} for selecting whether and which tools the model may call + * @see {@link CreateResponse} for the request schema that consumes tools + * + * @category schemas + * @since 4.0.0 + */ +export const Tool = Schema.Union([ + FunctionTool, + CustomTool, + ProviderDefinedTool +]) + +/** + * Tool definition that can be supplied to an OpenAI Responses request. + * + * @category models + * @since 4.0.0 + */ +export type Tool = typeof Tool.Type + +/** + * Schema for selecting whether and which tools the model may call in a Responses request. + * + * **When to use** + * + * Use when validating or encoding the `tool_choice` field that constrains model + * tool use separately from the tool definitions themselves. + * + * **Details** + * + * Accepted forms are `"none"`, `"auto"`, `"required"`, an allowed-tools set, + * a named function or custom tool, or a provider-defined tool choice. + * + * @see {@link Tool} for tool definitions referenced by tool choices + * @see {@link CreateResponse} for the request schema that consumes `tool_choice` + * + * @category schemas + * @since 4.0.0 + */ +export const ToolChoice = Schema.Union([ + Schema.Literals(["none", "auto", "required"]), + Schema.Struct({ + type: Schema.Literal("allowed_tools"), + mode: Schema.Literals(["auto", "required"]), + tools: Schema.Array(JsonObject) + }), + Schema.Struct({ + type: Schema.Literal("function"), + name: Schema.String + }), + Schema.Struct({ + type: Schema.Literal("custom"), + name: Schema.String + }), + Schema.StructWithRest( + Schema.Struct({ + type: Schema.Literals([ + "apply_patch", + "code_interpreter", + "file_search", + "image_generation", + "local_shell", + "mcp", + "shell", + "web_search", + "web_search_preview" + ]) + }), + [UnknownRecord] + ) +]) + +/** + * Tool selection mode or named tool choice for a Responses request. + * + * **Details** + * + * Accepted forms are `"none"`, `"auto"`, `"required"`, an allowed-tools set, + * a named function or custom tool, or a provider-defined tool choice. + * + * @category models + * @since 4.0.0 + */ +export type ToolChoice = typeof ToolChoice.Type + +/** + * Schema for text output format configuration, including plain text, JSON object, and JSON Schema responses. + * + * **When to use** + * + * Use when validating or encoding the `text.format` setting for a Responses + * request, especially when choosing structured JSON Schema output. + * + * **Details** + * + * Accepted variants are `text`, `json_schema`, and `json_object`. + * + * **Gotchas** + * + * `json_object` is the older JSON mode. Prefer `json_schema` for models that + * support it. + * + * @see {@link CreateResponse} for the request schema that consumes text format configuration + * + * @category schemas + * @since 4.0.0 + */ +export const TextResponseFormatConfiguration = Schema.Union([ + Schema.Struct({ type: Schema.Literal("text") }), + Schema.Struct({ + type: Schema.Literal("json_schema"), + description: Schema.optionalKey(Schema.String), + name: Schema.String, + schema: JsonObject, + strict: Schema.optionalKey(Schema.NullOr(Schema.Boolean)) + }), + Schema.Struct({ type: Schema.Literal("json_object") }) +]) + +/** + * Text output format configuration for plain text, JSON object, or JSON Schema responses. + * + * @category models + * @since 4.0.0 + */ +export type TextResponseFormatConfiguration = typeof TextResponseFormatConfiguration.Type + +/** + * Schema for request options used to create an OpenAI Responses API response. + * + * **When to use** + * + * Use to validate or encode payloads sent to the OpenAI Responses API. + * + * **Details** + * + * Validates the Responses API request payload, including input content, model + * selection, instructions, reasoning options, text output format, tools, + * `tool_choice`, streaming, storage, response continuation, sampling options, + * prompt caching, and optional response fields requested through `include`. + * + * **Gotchas** + * + * When `stream` is `true`, the API returns stream events instead of a single + * response object. + * + * @see {@link Response} for decoded non-streaming response objects + * @see {@link ResponseStreamEvent} for decoded streaming event objects + * + * @category schemas + * @since 4.0.0 + */ +export const CreateResponse = Schema.Struct({ + metadata: Schema.optional(Schema.Record(Schema.String, Schema.String)), + top_logprobs: Schema.optional(Schema.Int), + temperature: Schema.optional(Schema.Finite), + top_p: Schema.optional(Schema.Finite), + user: Schema.optional(Schema.String), + prompt_cache_key: Schema.optional(Schema.String), + prompt_cache_options: Schema.optional(Schema.Struct({ + mode: Schema.optional(Schema.Literals(["implicit", "explicit"])), + ttl: Schema.optional(Schema.Literal("30m")) + })), + service_tier: Schema.optional(Schema.String), + previous_response_id: Schema.optional(Schema.String), + model: Schema.optional(Schema.String), + reasoning: Schema.optional(Schema.Struct({ + effort: Schema.optional(Schema.Literals(["none", "minimal", "low", "medium", "high", "xhigh", "max"])), + + summary: Schema.optional(Schema.Literals(["auto", "concise", "detailed"])), + generate_summary: Schema.optional(Schema.Literals(["auto", "concise", "detailed"])) + })), + background: Schema.optional(Schema.Boolean), + max_output_tokens: Schema.optional(Schema.Int), + max_tool_calls: Schema.optional(Schema.Int), + text: Schema.optional( + Schema.Struct({ + format: Schema.optional(TextResponseFormatConfiguration), + verbosity: Schema.optional(Schema.Literals(["low", "medium", "high"])) + }) + ), + tools: Schema.optional(Schema.Array(Tool)), + tool_choice: Schema.optional(ToolChoice), + truncation: Schema.optional(Schema.Literals(["auto", "disabled"])), + input: Schema.optional( + Schema.Union([ + Schema.String, + Schema.Array(InputItem) + ]) + ), + include: Schema.optional(Schema.Array(IncludeEnum)), + store: Schema.optional(Schema.Boolean), + instructions: Schema.optional(Schema.String), + stream: Schema.optional(Schema.Boolean), + conversation: Schema.optional(Schema.String), + modalities: Schema.optional(Schema.Array(Schema.Literals(["text", "audio"]))), + seed: Schema.optional(Schema.Int) +}) + +/** + * Request options used to create an OpenAI Responses API response. + * + * @category options + * @since 4.0.0 + */ +export type CreateResponse = typeof CreateResponse.Type + +/** + * Schema for token accounting reported on OpenAI Responses API response objects. + * + * **Details** + * + * The required counters are `input_tokens`, `output_tokens`, and + * `total_tokens`. Provider-specific token detail objects are preserved through + * `input_tokens_details`, `output_tokens_details`, and additional fields. + * + * @category schemas + * @since 4.0.0 + */ +export const ResponseUsage = Schema.StructWithRest( + Schema.Struct({ + input_tokens: Schema.Int, + output_tokens: Schema.Int, + total_tokens: Schema.Int, + input_tokens_details: Schema.optionalKey(Schema.Unknown), + output_tokens_details: Schema.optionalKey(Schema.Unknown) + }), + [UnknownRecord] +) + +/** + * Token accounting reported on OpenAI Responses API response objects. + * + * **Details** + * + * Includes total input, output, and combined token counts, with provider-specific + * token detail fields preserved when present. + * + * @category models + * @since 4.0.0 + */ +export type ResponseUsage = typeof ResponseUsage.Type + +const ApplyPatchOperation = Schema.Struct({ + type: Schema.String, + path: Schema.String, + diff: Schema.optionalKey(Schema.String) +}) + +const ApplyPatchCall = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("apply_patch_call"), + call_id: Schema.String, + operation: ApplyPatchOperation, + status: Schema.optionalKey(MessageStatus) +}) + +const CodeInterpreterCall = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("code_interpreter_call"), + code: Schema.optionalKey(Schema.String), + container_id: Schema.String, + outputs: Schema.optionalKey(Schema.Array(Schema.Unknown)), + status: Schema.optionalKey(MessageStatus) +}) + +const ComputerCall = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("computer_call"), + status: Schema.optionalKey(MessageStatus) +}) + +const FileSearchCall = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("file_search_call"), + status: Schema.optionalKey(Schema.String), + queries: Schema.optionalKey(Schema.Array(Schema.String)), + results: Schema.optionalKey(Schema.NullOr(Schema.Unknown)) +}) + +const ImageGenerationCall = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("image_generation_call"), + result: Schema.optionalKey(Schema.NullOr(Schema.String)), + status: Schema.optionalKey(Schema.Literals(["in_progress", "completed", "generating", "failed"])) +}) + +const McpCall = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("mcp_call"), + approval_request_id: Schema.optionalKey(Schema.NullOr(Schema.String)), + name: Schema.String, + arguments: Schema.Unknown, + output: Schema.optionalKey(Schema.Unknown), + error: Schema.optionalKey(Schema.Unknown), + server_label: Schema.optionalKey(Schema.NullOr(Schema.String)) +}) + +const McpListTools = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("mcp_list_tools") +}) + +const McpApprovalRequest = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("mcp_approval_request"), + approval_request_id: Schema.optionalKey(Schema.String), + name: Schema.String, + arguments: Schema.Unknown +}) + +const WebSearchCall = Schema.Struct({ + id: Schema.String, + type: Schema.Literal("web_search_call"), + action: Schema.optionalKey(Schema.Unknown), + status: Schema.optionalKey(Schema.String) +}) + +const OutputItem = Schema.Union([ + ApplyPatchCall, + CodeInterpreterCall, + ComputerCall, + FileSearchCall, + FunctionCall, + ImageGenerationCall, + LocalShellCall, + McpCall, + McpListTools, + McpApprovalRequest, + OutputMessage, + ReasoningItem, + ShellCall, + WebSearchCall +]) + +const ResponseError = Schema.Struct({ + code: Schema.String, + message: Schema.String +}) + +/** + * Schema for an OpenAI Responses API response object. + * + * **When to use** + * + * Use to decode non-streaming OpenAI Responses API responses. + * + * **Details** + * + * Response objects include the response id, model, creation time, output items, + * optional token usage, optional incomplete details, and optional service tier. + * + * @see {@link CreateResponse} for the request schema that creates responses + * @see {@link ResponseUsage} for token accounting on responses + * @see {@link ResponseStreamEvent} for streaming response events + * + * @category schemas + * @since 4.0.0 + */ +export const Response = Schema.Struct({ + id: Schema.String, + object: Schema.optionalKey(Schema.Literal("response")), + model: Schema.String, + created_at: Schema.Int, + output: Schema.Array(OutputItem).pipe( + Schema.withDecodingDefault(Effect.succeed([])) + ), + usage: Schema.optionalKey(Schema.NullOr(ResponseUsage)), + error: Schema.optionalKey(Schema.NullOr(ResponseError)), + incomplete_details: Schema.optionalKey( + Schema.NullOr( + Schema.Struct({ + reason: Schema.optionalKey(Schema.Literals(["max_output_tokens", "content_filter"])) + }) + ) + ), + service_tier: Schema.optionalKey(Schema.String) +}) + +/** + * OpenAI Responses API response object. + * + * **When to use** + * + * Use when typing non-streaming OpenAI Responses API responses. + * + * **Details** + * + * Response objects include metadata, output items, optional token usage, and + * optional incomplete details. + * + * @category models + * @since 4.0.0 + */ +export type Response = typeof Response.Type + +const ResponseCreatedEvent = Schema.Struct({ + type: Schema.Literal("response.created"), + response: Response, + sequence_number: Schema.Int +}) + +const ResponseCompletedEvent = Schema.Struct({ + type: Schema.Literal("response.completed"), + response: Response, + sequence_number: Schema.Int +}) + +const ResponseIncompleteEvent = Schema.Struct({ + type: Schema.Literal("response.incomplete"), + response: Response, + sequence_number: Schema.Int +}) + +const ResponseFailedEvent = Schema.Struct({ + type: Schema.Literal("response.failed"), + response: Response, + sequence_number: Schema.Int +}) + +const ResponseOutputItemAddedEvent = Schema.Struct({ + type: Schema.Literal("response.output_item.added"), + output_index: Schema.Int, + sequence_number: Schema.Int, + item: OutputItem +}) + +const ResponseOutputItemDoneEvent = Schema.Struct({ + type: Schema.Literal("response.output_item.done"), + output_index: Schema.Int, + sequence_number: Schema.Int, + item: OutputItem +}) + +const ResponseOutputTextDeltaEvent = Schema.Struct({ + type: Schema.Literal("response.output_text.delta"), + item_id: Schema.String, + output_index: Schema.Int, + content_index: Schema.Int, + delta: Schema.String, + sequence_number: Schema.Int, + logprobs: Schema.optionalKey(Schema.Array(Schema.Unknown)) +}) + +const ResponseOutputTextAnnotationAddedEvent = Schema.Struct({ + type: Schema.Literal("response.output_text.annotation.added"), + item_id: Schema.String, + output_index: Schema.Int, + content_index: Schema.Int, + annotation_index: Schema.Int, + sequence_number: Schema.Int, + annotation: Annotation +}) + +const ResponseReasoningSummaryPartAddedEvent = Schema.Struct({ + type: Schema.Literal("response.reasoning_summary_part.added"), + item_id: Schema.String, + output_index: Schema.Int, + summary_index: Schema.Int, + sequence_number: Schema.Int, + part: SummaryTextContent +}) + +const ResponseReasoningSummaryPartDoneEvent = Schema.Struct({ + type: Schema.Literal("response.reasoning_summary_part.done"), + item_id: Schema.String, + output_index: Schema.Int, + summary_index: Schema.Int, + sequence_number: Schema.Int, + part: SummaryTextContent +}) + +const ResponseReasoningSummaryTextDeltaEvent = Schema.Struct({ + type: Schema.Literal("response.reasoning_summary_text.delta"), + item_id: Schema.String, + output_index: Schema.Int, + summary_index: Schema.Int, + delta: Schema.String, + sequence_number: Schema.Int +}) + +const ResponseFunctionCallArgumentsDeltaEvent = Schema.Struct({ + type: Schema.Literal("response.function_call_arguments.delta"), + item_id: Schema.String, + output_index: Schema.Int, + sequence_number: Schema.Int, + delta: Schema.String +}) + +const ResponseFunctionCallArgumentsDoneEvent = Schema.Struct({ + type: Schema.Literal("response.function_call_arguments.done"), + item_id: Schema.String, + output_index: Schema.Int, + sequence_number: Schema.Int, + arguments: Schema.String +}) + +const ResponseCodeInterpreterCallCodeDeltaEvent = Schema.Struct({ + type: Schema.Literal("response.code_interpreter_call_code.delta"), + item_id: Schema.String, + output_index: Schema.Int, + sequence_number: Schema.Int, + delta: Schema.String +}) + +const ResponseCodeInterpreterCallCodeDoneEvent = Schema.Struct({ + type: Schema.Literal("response.code_interpreter_call_code.done"), + item_id: Schema.String, + output_index: Schema.Int, + sequence_number: Schema.Int, + code: Schema.String +}) + +const ResponseApplyPatchCallOperationDiffDeltaEvent = Schema.Struct({ + type: Schema.Literal("response.apply_patch_call_operation_diff.delta"), + item_id: Schema.String, + output_index: Schema.Int, + sequence_number: Schema.Int, + delta: Schema.String +}) + +const ResponseApplyPatchCallOperationDiffDoneEvent = Schema.Struct({ + type: Schema.Literal("response.apply_patch_call_operation_diff.done"), + item_id: Schema.String, + output_index: Schema.Int, + sequence_number: Schema.Int, + delta: Schema.optionalKey(Schema.String) +}) + +const ResponseImageGenerationCallPartialImageEvent = Schema.Struct({ + type: Schema.Literal("response.image_generation_call.partial_image"), + item_id: Schema.String, + output_index: Schema.Int, + sequence_number: Schema.Int, + partial_image_b64: Schema.String +}) + +const ResponseErrorEvent = Schema.Struct({ + type: Schema.Literal("error"), + code: Schema.optionalKey(Schema.NullOr(Schema.String)), + message: Schema.String, + param: Schema.optionalKey(Schema.NullOr(Schema.String)), + sequence_number: Schema.optionalKey(Schema.Int), + status: Schema.optionalKey(Schema.Int) +}) + +// OpenAI can nest stream error details under `error`. +const NestedResponseErrorEvent = Schema.Struct({ + type: Schema.Literal("error"), + error: Schema.Struct({ + code: Schema.optionalKey(Schema.NullOr(Schema.String)), + message: Schema.String, + param: Schema.optionalKey(Schema.NullOr(Schema.String)) + }), + sequence_number: Schema.optionalKey(Schema.Int), + status: Schema.optionalKey(Schema.Int) +}).pipe( + Schema.decodeTo( + ResponseErrorEvent, + SchemaTransformation.transform({ + decode: ({ error, ...rest }) => ({ ...rest, ...error }), + encode: ({ code, message, param, ...rest }) => ({ + ...rest, + error: { + ...(Predicate.isNotUndefined(code) ? { code } : {}), + message, + ...(Predicate.isNotUndefined(param) ? { param } : {}) + } + }) + }) + ) +) + +const knownResponseStreamEventTypes = new Set([ + "response.created", + "response.completed", + "response.incomplete", + "response.failed", + "response.output_item.added", + "response.output_item.done", + "response.output_text.delta", + "response.output_text.annotation.added", + "response.reasoning_summary_part.added", + "response.reasoning_summary_part.done", + "response.reasoning_summary_text.delta", + "response.function_call_arguments.delta", + "response.function_call_arguments.done", + "response.code_interpreter_call_code.delta", + "response.code_interpreter_call_code.done", + "response.apply_patch_call_operation_diff.delta", + "response.apply_patch_call_operation_diff.done", + "response.image_generation_call.partial_image", + "error" +]) + +/** + * Fallback event shape for future or provider-specific response stream events. + * + * @category models + * @since 4.0.0 + */ +export type UnknownResponseStreamEvent = { + readonly type: string + readonly [key: string]: unknown +} + +const UnknownResponseStreamEvent = Schema.declare( + (value): value is UnknownResponseStreamEvent => + Predicate.hasProperty(value, "type") && + typeof value.type === "string" && + !knownResponseStreamEventTypes.has(value.type), + { + identifier: "UnknownResponseStreamEvent", + description: "Fallback for unknown future stream events" + } +) + +/** + * Schema for server-sent event shapes emitted by OpenAI Responses API streams. + * + * **When to use** + * + * Use to decode events from a streaming OpenAI Responses API request. + * + * **Details** + * + * Known event variants include response lifecycle events, output item events, + * text and reasoning deltas, tool-call deltas, partial image events, and error + * events. + * + * **Gotchas** + * + * Future event types decode through the fallback only when their `type` is not + * one of the known event types. Malformed known events still fail to decode. + * + * @see {@link Response} for complete response objects carried by lifecycle events + * @see {@link UnknownResponseStreamEvent} for the fallback shape for future event types + * + * @category schemas + * @since 4.0.0 + */ +export const ResponseStreamEvent = Schema.Union([ + ResponseCreatedEvent, + ResponseCompletedEvent, + ResponseIncompleteEvent, + ResponseFailedEvent, + ResponseOutputItemAddedEvent, + ResponseOutputItemDoneEvent, + ResponseOutputTextDeltaEvent, + ResponseOutputTextAnnotationAddedEvent, + ResponseReasoningSummaryPartAddedEvent, + ResponseReasoningSummaryPartDoneEvent, + ResponseReasoningSummaryTextDeltaEvent, + ResponseFunctionCallArgumentsDeltaEvent, + ResponseFunctionCallArgumentsDoneEvent, + ResponseCodeInterpreterCallCodeDeltaEvent, + ResponseCodeInterpreterCallCodeDoneEvent, + ResponseApplyPatchCallOperationDiffDeltaEvent, + ResponseApplyPatchCallOperationDiffDoneEvent, + ResponseImageGenerationCallPartialImageEvent, + ResponseErrorEvent, + NestedResponseErrorEvent, + UnknownResponseStreamEvent +]) + +/** + * Server-sent event shape emitted by OpenAI Responses API streams. + * + * **When to use** + * + * Use when typing events from a streaming OpenAI Responses API request. + * + * **Details** + * + * Includes known response stream events plus a fallback shape for unknown future + * event types. + * + * @category models + * @since 4.0.0 + */ +export type ResponseStreamEvent = typeof ResponseStreamEvent.Type + +/** + * Schema for one embedding item returned by the OpenAI embeddings API. + * + * **When to use** + * + * Use when validating individual embedding entries at the OpenAI client boundary + * before assuming the embedding payload is a numeric vector. + * + * **Details** + * + * An embedding item contains its `index`, optional `object` marker, and an + * `embedding` represented either as a numeric vector or as a string. + * + * **Gotchas** + * + * Callers that need numeric vectors must account for string embeddings, such as + * base64-encoded embeddings returned for string encoding formats. + * + * @category schemas + * @since 4.0.0 + */ +export const Embedding = Schema.Struct({ + embedding: Schema.Union([ + Schema.Array(Schema.Finite), + Schema.String + ]), + index: Schema.Int, + object: Schema.optionalKey(Schema.String) +}) + +/** + * One embedding item returned by the OpenAI embeddings API. + * + * **Details** + * + * Contains the item index and embedding payload. The embedding payload may be a + * numeric vector or a string. + * + * @category models + * @since 4.0.0 + */ +export type Embedding = typeof Embedding.Type + +/** + * Schema for the request payload sent to the OpenAI embeddings endpoint. + * + * **When to use** + * + * Use when validating or encoding embeddings requests before sending them to + * OpenAI, while leaving model-specific limits to the provider. + * + * **Details** + * + * Requires `input` and `model`. `input` may be a string, an array of strings, + * a token array, or an array of token arrays. Optional fields configure the + * embedding encoding format, requested dimensions, and user identifier. + * + * **Gotchas** + * + * This schema validates the transport shape, but OpenAI still enforces + * provider-side constraints such as non-empty input, integer token ids, input + * size limits, positive dimensions, and model-specific dimension support. + * + * @category schemas + * @since 4.0.0 + */ +export const CreateEmbeddingRequest = Schema.Struct({ + input: Schema.Union([ + Schema.String, + Schema.Array(Schema.String), + Schema.Array(Schema.Int), + Schema.Array(Schema.Array(Schema.Int)) + ]), + model: Schema.String, + encoding_format: Schema.optionalKey(Schema.Literals(["float", "base64"])), + dimensions: Schema.optionalKey(Schema.Int), + user: Schema.optionalKey(Schema.String) +}) + +/** + * Request payload sent to the OpenAI embeddings endpoint. + * + * @category models + * @since 4.0.0 + */ +export type CreateEmbeddingRequest = typeof CreateEmbeddingRequest.Type + +/** + * Schema for a successful response payload returned by the OpenAI embeddings endpoint. + * + * **When to use** + * + * Use when you need to validate embeddings responses at an OpenAI client + * boundary before trusting item shapes, especially when numeric and string + * embeddings are both allowed. + * + * **Details** + * + * The response contains an array of `Embedding` items, the model name, an + * optional `object: "list"` marker, and optional token usage counts for prompt + * and total tokens. + * + * **Gotchas** + * + * Each `Embedding` may contain either a numeric vector or a string embedding. + * Callers that require numeric vectors must account for string embeddings. + * + * @see {@link CreateEmbeddingRequest} for the request schema sent to the embeddings endpoint + * @see {@link Embedding} for individual embedding items in the response + * + * @category schemas + * @since 4.0.0 + */ +export const CreateEmbeddingResponse = Schema.Struct({ + data: Schema.Array(Embedding), + model: Schema.String, + object: Schema.optionalKey(Schema.Literal("list")), + usage: Schema.optionalKey( + Schema.Struct({ + prompt_tokens: Schema.Int, + total_tokens: Schema.Int + }) + ) +}) + +/** + * Successful response payload returned by the OpenAI embeddings endpoint. + * + * **When to use** + * + * Use when typing successful OpenAI embeddings responses. + * + * **Details** + * + * Contains embedding items, the model name, optional list marker, and optional + * token usage counts. + * + * @category models + * @since 4.0.0 + */ +export type CreateEmbeddingResponse = typeof CreateEmbeddingResponse.Type diff --git a/packages/effect-ai-openai/src/OpenAiTelemetry.ts b/packages/effect-ai-openai/src/OpenAiTelemetry.ts new file mode 100644 index 0000000..3d80a9e --- /dev/null +++ b/packages/effect-ai-openai/src/OpenAiTelemetry.ts @@ -0,0 +1,200 @@ +/** + * The `OpenAiTelemetry` module defines OpenAI-specific telemetry attributes + * and a helper for adding them to a tracing span. It keeps the standard GenAI + * telemetry attributes and adds request and response metadata, such as response + * format, service tier, and system fingerprint, under the `gen_ai.openai.*` + * OpenTelemetry namespaces. + * + * @since 4.0.0 + */ +import { dual } from "effect/Function" +import * as String from "effect/String" +import type { Span } from "effect/Tracer" +import type { Simplify } from "effect/Types" +import * as Telemetry from "effect/unstable/ai/Telemetry" + +/** + * The attributes used to describe telemetry in the context of Generative + * Artificial Intelligence (GenAI) Models requests and responses. + * + * **Details** + * + * These attributes follow the OpenTelemetry generative AI semantic + * conventions: + * https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/ + * + * @category models + * @since 4.0.0 + */ +export type OpenAiTelemetryAttributes = Simplify< + & Telemetry.GenAITelemetryAttributes + & Telemetry.AttributesWithPrefix + & Telemetry.AttributesWithPrefix +> + +/** + * All telemetry attributes which are part of the GenAI specification, + * including the OpenAI-specific attributes. + * + * @category models + * @since 4.0.0 + */ +export type AllAttributes = Telemetry.AllAttributes & RequestAttributes & ResponseAttributes + +/** + * Telemetry attributes which are part of the GenAI specification and are + * namespaced by `gen_ai.openai.request`. + * + * @category models + * @since 4.0.0 + */ +export interface RequestAttributes { + /** + * The response format that is requested. + */ + readonly responseFormat?: (string & {}) | WellKnownResponseFormat | null | undefined + /** + * The service tier requested. May be a specific tier, `default`, or `auto`. + */ + readonly serviceTier?: (string & {}) | WellKnownServiceTier | null | undefined +} + +/** + * Telemetry attributes which are part of the GenAI specification and are + * namespaced by `gen_ai.openai.response`. + * + * @category models + * @since 4.0.0 + */ +export interface ResponseAttributes { + /** + * The service tier used for the response. + */ + readonly serviceTier?: string | null | undefined + /** + * A fingerprint to track any eventual change in the Generative AI + * environment. + */ + readonly systemFingerprint?: string | null | undefined +} + +/** + * The `gen_ai.openai.request.response_format` attribute has the following + * list of well-known values. + * + * **Details** + * + * If one of them applies, then the respective value **MUST** be used; + * otherwise, a custom value **MAY** be used. + * + * @category models + * @since 4.0.0 + */ +export type WellKnownResponseFormat = "json_object" | "json_schema" | "text" + +/** + * The `gen_ai.openai.request.service_tier` attribute has the following + * list of well-known values. + * + * **Details** + * + * If one of them applies, then the respective value **MUST** be used; + * otherwise, a custom value **MAY** be used. + * + * @category models + * @since 4.0.0 + */ +export type WellKnownServiceTier = "auto" | "default" + +/** + * Options accepted by `addGenAIAnnotations`, combining standard GenAI + * telemetry attributes with optional OpenAI request and response attributes. + * + * @category options + * @since 4.0.0 + */ +export type OpenAiTelemetryAttributeOptions = Telemetry.GenAITelemetryAttributeOptions & { + openai?: { + request?: RequestAttributes | undefined + response?: ResponseAttributes | undefined + } | undefined +} + +const addOpenAiRequestAttributes = Telemetry.addSpanAttributes("gen_ai.openai.request", String.camelToSnake)< + RequestAttributes +> +const addOpenAiResponseAttributes = Telemetry.addSpanAttributes("gen_ai.openai.response", String.camelToSnake)< + ResponseAttributes +> + +/** + * Applies the specified OpenAI GenAI telemetry attributes to the provided + * `Span`. + * + * **When to use** + * + * Use to annotate an existing OpenTelemetry span with standard GenAI attributes + * plus OpenAI-specific request and response metadata. + * + * **Gotchas** + * + * Mutates the supplied `Span` in place. + * + * @see {@link OpenAiTelemetryAttributeOptions} for the accepted telemetry attributes + * @see {@link Telemetry.addGenAIAnnotations} for the provider-neutral annotation helper + * + * @category tracing + * @since 4.0.0 + */ +export const addGenAIAnnotations: { + /** + * Applies the specified OpenAI GenAI telemetry attributes to the provided + * `Span`. + * + * **When to use** + * + * Use to annotate an existing OpenTelemetry span with standard GenAI attributes + * plus OpenAI-specific request and response metadata. + * + * **Gotchas** + * + * Mutates the supplied `Span` in place. + * + * @see {@link OpenAiTelemetryAttributeOptions} for the accepted telemetry attributes + * @see {@link Telemetry.addGenAIAnnotations} for the provider-neutral annotation helper + * + * @category tracing + * @since 4.0.0 + */ + (options: OpenAiTelemetryAttributeOptions): (span: Span) => void + /** + * Applies the specified OpenAI GenAI telemetry attributes to the provided + * `Span`. + * + * **When to use** + * + * Use to annotate an existing OpenTelemetry span with standard GenAI attributes + * plus OpenAI-specific request and response metadata. + * + * **Gotchas** + * + * Mutates the supplied `Span` in place. + * + * @see {@link OpenAiTelemetryAttributeOptions} for the accepted telemetry attributes + * @see {@link Telemetry.addGenAIAnnotations} for the provider-neutral annotation helper + * + * @category tracing + * @since 4.0.0 + */ + (span: Span, options: OpenAiTelemetryAttributeOptions): void +} = dual(2, (span: Span, options: OpenAiTelemetryAttributeOptions) => { + Telemetry.addGenAIAnnotations(span, options) + if (options.openai != null) { + if (options.openai.request != null) { + addOpenAiRequestAttributes(span, options.openai.request) + } + if (options.openai.response != null) { + addOpenAiResponseAttributes(span, options.openai.response) + } + } +}) diff --git a/packages/effect-ai-openai/src/OpenAiTool.ts b/packages/effect-ai-openai/src/OpenAiTool.ts new file mode 100644 index 0000000..7d80c57 --- /dev/null +++ b/packages/effect-ai-openai/src/OpenAiTool.ts @@ -0,0 +1,342 @@ +/** + * The `OpenAiTool` module defines OpenAI provider tools for Effect AI language + * model requests. It exposes typed descriptors for tools such as Apply Patch, + * Code Interpreter, File Search, Image Generation, MCP, Web Search, and + * shell-like local tools, including their provider names, configuration + * arguments, call parameters, success schemas, and handler requirements. + * + * @since 4.0.0 + */ +import * as Schema from "effect/Schema" +import * as Tool from "effect/unstable/ai/Tool" +import * as Generated from "./Generated.ts" + +/** + * Union of all OpenAI provider-defined tools. + * + * @category models + * @since 4.0.0 + */ +export type OpenAiTool = + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + | ReturnType + +/** + * Defines the OpenAI Apply Patch tool that allows the model to apply diffs by creating, + * deleting, or updating files. This local tool runs in your environment and + * requires a handler to execute file operations. + * + * **When to use** + * + * Use when you want an OpenAI model to request structured file edits as create, + * delete, or update operations that your application executes through a local + * handler. + * + * @category tools + * @since 4.0.0 + */ +export const ApplyPatch = Tool.providerDefined({ + id: "openai.apply_patch", + customName: "OpenAiApplyPatch", + providerName: "apply_patch", + requiresHandler: true, + parameters: Schema.Struct({ + call_id: Generated.ApplyPatchToolCall.fields.call_id, + operation: Generated.ApplyPatchToolCall.fields.operation + }), + success: Schema.Struct({ + status: Generated.ApplyPatchToolCallOutput.fields.status, + output: Generated.ApplyPatchToolCallOutput.fields.output + }) +}) + +/** + * Defines the OpenAI Code Interpreter tool that allows the model to execute Python code in + * a sandboxed environment. + * + * **When to use** + * + * Use to enable OpenAI-hosted Python execution for a model response. + * + * **Details** + * + * The tool is configured with a `container` argument. Successful tool calls + * expose `outputs`, which may contain logs or generated images, or `null` when + * no outputs are available. + * + * @category tools + * @since 4.0.0 + */ +export const CodeInterpreter = Tool.providerDefined({ + id: "openai.code_interpreter", + customName: "OpenAiCodeInterpreter", + providerName: "code_interpreter", + args: Schema.Struct({ + container: Generated.CodeInterpreterTool.fields.container + }), + parameters: Schema.Struct({ + code: Generated.CodeInterpreterToolCall.fields.code, + container_id: Generated.CodeInterpreterToolCall.fields.container_id + }), + success: Schema.Struct({ + outputs: Generated.CodeInterpreterToolCall.fields.outputs + }) +}) + +/** + * Defines the OpenAI File Search tool that enables the model to search through uploaded + * files and vector stores. + * + * **When to use** + * + * Use to let an OpenAI model search uploaded files through one or more vector + * stores. + * + * **Details** + * + * The tool requires `vector_store_ids` and accepts optional `filters`, + * `max_num_results`, and `ranking_options`. Successful tool calls expose the + * search `status`, generated `queries`, and optional `results`. + * + * @category tools + * @since 4.0.0 + */ +export const FileSearch = Tool.providerDefined({ + id: "openai.file_search", + customName: "OpenAiFileSearch", + providerName: "file_search", + args: Schema.Struct({ + filters: Generated.FileSearchTool.fields.filters, + max_num_results: Generated.FileSearchTool.fields.max_num_results, + ranking_options: Generated.FileSearchTool.fields.ranking_options, + vector_store_ids: Generated.FileSearchTool.fields.vector_store_ids + }), + success: Schema.Struct({ + status: Generated.FileSearchToolCall.fields.status, + queries: Generated.FileSearchToolCall.fields.queries, + results: Generated.FileSearchToolCall.fields.results + }) +}) + +/** + * Defines the OpenAI Image Generation tool that enables the model to generate images using + * the GPT image models. + * + * **When to use** + * + * Use to enable OpenAI provider-defined image generation through a language + * model response. + * + * **Details** + * + * The tool configures the `image_generation` provider tool, including model, + * size, quality, output format, moderation, background, input-image options, + * and partial image settings. Successful tool calls expose `result` as base64 + * image data or `null`. + * + * @category tools + * @since 4.0.0 + */ +export const ImageGeneration = Tool.providerDefined({ + id: "openai.image_generation", + customName: "OpenAiImageGeneration", + providerName: "image_generation", + args: Schema.Struct({ + background: Generated.ImageGenTool.fields.background, + input_fidelity: Generated.ImageGenTool.fields.input_fidelity, + input_image_mask: Generated.ImageGenTool.fields.input_image_mask, + model: Generated.ImageGenTool.fields.model, + moderation: Generated.ImageGenTool.fields.moderation, + output_compression: Generated.ImageGenTool.fields.output_compression, + output_format: Generated.ImageGenTool.fields.output_format, + partial_images: Generated.ImageGenTool.fields.partial_images, + quality: Generated.ImageGenTool.fields.quality, + size: Generated.ImageGenTool.fields.size + }), + success: Schema.Struct({ + result: Generated.ImageGenToolCall.fields.result + }) +}) + +/** + * Defines the OpenAI Local Shell tool that enables the model to run a command with a local + * shell. This local tool runs in your environment and requires a handler to + * execute commands. + * + * **When to use** + * + * Use to let an OpenAI model request local shell commands that your application + * executes through a handler. + * + * **Details** + * + * The tool exposes a provider-defined `local_shell` call. It is marked as + * handler-required, so applications must provide the command execution policy + * and implementation. + * + * @category tools + * @since 4.0.0 + */ +export const LocalShell = Tool.providerDefined({ + id: "openai.local_shell", + customName: "OpenAiLocalShell", + providerName: "local_shell", + requiresHandler: true, + parameters: Schema.Struct({ + action: Generated.LocalShellToolCall.fields.action + }), + success: Schema.Struct({ + output: Generated.LocalShellToolCallOutput.fields.output + }) +}) + +/** + * Defines the OpenAI MCP tool that gives the model access to additional tools via remote + * Model Context Protocol (MCP) servers. + * + * **When to use** + * + * Use to let an OpenAI model call tools exposed by a remote MCP server. + * + * **Details** + * + * The tool accepts MCP server configuration such as allowed tools, + * authorization, connector id, approval requirements, server metadata, and + * server URL. Tool call results include the called tool name, arguments, output, + * error, and server label. + * + * **Gotchas** + * + * This schema leaves both `server_url` and `connector_id` optional, but OpenAI + * may require a server URL or connector id for a usable MCP tool configuration. + * + * @category tools + * @since 4.0.0 + */ +export const Mcp = Tool.providerDefined({ + id: "openai.mcp", + customName: "OpenAiMcp", + providerName: "mcp", + args: Schema.Struct({ + allowed_tools: Generated.MCPTool.fields.allowed_tools, + authorization: Generated.MCPTool.fields.authorization, + connector_id: Generated.MCPTool.fields.connector_id, + require_approval: Generated.MCPTool.fields.require_approval, + server_description: Generated.MCPTool.fields.server_description, + server_label: Generated.MCPTool.fields.server_label, + server_url: Generated.MCPTool.fields.server_url + }), + parameters: Schema.Unknown, + success: Schema.Struct({ + type: Generated.MCPToolCall.fields.type, + name: Generated.MCPToolCall.fields.name, + arguments: Generated.MCPToolCall.fields.arguments, + output: Generated.MCPToolCall.fields.output, + error: Generated.MCPToolCall.fields.error, + server_label: Generated.MCPToolCall.fields.server_label + }) +}) + +/** + * Defines the OpenAI shell tool for model-requested command execution. + * + * **When to use** + * + * Use to let an OpenAI model request shell commands that your application + * executes through a handler. + * + * **Details** + * + * The tool exposes a provider-defined `shell` call. It is marked as + * handler-required, so applications must provide the command execution policy + * and implementation. + * + * @category tools + * @since 4.0.0 + */ +export const Shell = Tool.providerDefined({ + id: "openai.shell", + customName: "OpenAiShell", + providerName: "shell", + requiresHandler: true, + parameters: Schema.Struct({ + action: Generated.FunctionShellCall.fields.action + }), + success: Schema.Struct({ + output: Generated.FunctionShellCallOutput.fields.output + }) +}) + +/** + * Defines the OpenAI Web Search tool that enables the model to search the web for + * information. + * + * **When to use** + * + * Use to enable OpenAI provider-defined web search for a model response. + * + * **Details** + * + * The tool accepts optional filters, user location, and search context size. + * Successful calls expose the performed search action and status. + * + * @see {@link WebSearchPreview} for the preview web search provider tool + * + * @category tools + * @since 4.0.0 + */ +export const WebSearch = Tool.providerDefined({ + id: "openai.web_search", + customName: "OpenAiWebSearch", + providerName: "web_search", + args: Schema.Struct({ + filters: Generated.WebSearchTool.fields.filters, + user_location: Generated.WebSearchTool.fields.user_location, + search_context_size: Generated.WebSearchTool.fields.search_context_size + }), + parameters: Schema.Struct({ + action: Generated.WebSearchToolCall.fields.action + }), + success: Schema.Struct({ + action: Generated.WebSearchToolCall.fields.action, + status: Generated.WebSearchToolCall.fields.status + }) +}) + +/** + * Defines the OpenAI preview Web Search tool for model responses. + * + * **When to use** + * + * Use to enable the preview OpenAI web search provider tool. + * + * **Details** + * + * The preview tool accepts optional user location and search context size, then + * exposes the performed search action and status in successful calls. + * + * @see {@link WebSearch} for the stable web search provider tool + * + * @category tools + * @since 4.0.0 + */ +export const WebSearchPreview = Tool.providerDefined({ + id: "openai.web_search_preview", + customName: "OpenAiWebSearchPreview", + providerName: "web_search_preview", + args: Schema.Struct({ + user_location: Generated.WebSearchPreviewTool.fields.user_location, + search_context_size: Generated.WebSearchPreviewTool.fields.search_context_size + }), + success: Schema.Struct({ + action: Generated.WebSearchToolCall.fields.action, + status: Generated.WebSearchToolCall.fields.status + }) +}) diff --git a/packages/effect-ai-openai/src/index.ts b/packages/effect-ai-openai/src/index.ts new file mode 100644 index 0000000..b1758b6 --- /dev/null +++ b/packages/effect-ai-openai/src/index.ts @@ -0,0 +1,55 @@ +/** + * @since 4.0.0 + */ + +// @barrel: Auto-generated exports. Do not edit manually. + +/** + * @since 1.0.0 + */ +export * as Generated from "./Generated.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiClient from "./OpenAiClient.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiClientGenerated from "./OpenAiClientGenerated.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiConfig from "./OpenAiConfig.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiEmbeddingModel from "./OpenAiEmbeddingModel.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiError from "./OpenAiError.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiLanguageModel from "./OpenAiLanguageModel.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiSchema from "./OpenAiSchema.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiTelemetry from "./OpenAiTelemetry.ts" + +/** + * @since 4.0.0 + */ +export * as OpenAiTool from "./OpenAiTool.ts" diff --git a/packages/effect-ai-openai/src/internal/errors.ts b/packages/effect-ai-openai/src/internal/errors.ts new file mode 100644 index 0000000..fc93181 --- /dev/null +++ b/packages/effect-ai-openai/src/internal/errors.ts @@ -0,0 +1,341 @@ +import * as Duration from "effect/Duration" +import * as Effect from "effect/Effect" +import { dual } from "effect/Function" +import * as Number from "effect/Number" +import * as Option from "effect/Option" +import * as Predicate from "effect/Predicate" +import * as Redactable from "effect/Redactable" +import * as Schema from "effect/Schema" +import * as AiError from "effect/unstable/ai/AiError" +import type * as Response from "effect/unstable/ai/Response" +import type * as Sse from "effect/unstable/encoding/Sse" +import type * as HttpClientError from "effect/unstable/http/HttpClientError" +import type * as HttpClientRequest from "effect/unstable/http/HttpClientRequest" +import type * as HttpClientResponse from "effect/unstable/http/HttpClientResponse" +import type { OpenAiErrorMetadata } from "../OpenAiError.ts" + +// ============================================================================= +// OpenAI Error Body Schema +// ============================================================================= + +/** @internal */ +export const OpenAiErrorBody = Schema.Struct({ + error: Schema.Struct({ + message: Schema.String, + type: Schema.optional(Schema.NullOr(Schema.String)), + param: Schema.optional(Schema.NullOr(Schema.String)), + code: Schema.optional(Schema.NullOr(Schema.String)) + }) +}) + +const OpenAiCompatibleErrorBody = Schema.Struct({ + error: Schema.String, + code: Schema.optional(Schema.String) +}) + +// ============================================================================= +// Error Mappers +// ============================================================================= + +/** @internal */ +export const mapSchemaError = dual< + (method: string) => (error: Schema.SchemaError) => AiError.AiError, + (error: Schema.SchemaError, method: string) => AiError.AiError +>(2, (error, method) => + AiError.make({ + module: "OpenAiClient", + method, + reason: AiError.InvalidOutputError.fromSchemaError(error) + })) + +/** @internal */ +export const mapSseError = dual< + (method: string) => (error: Sse.SseError) => AiError.AiError, + (error: Sse.SseError, method: string) => AiError.AiError +>(2, (error, method) => + AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.InvalidOutputError({ description: error.message }) + })) + +/** @internal */ +export const mapHttpClientError = dual< + (method: string) => (error: HttpClientError.HttpClientError) => Effect.Effect, + (error: HttpClientError.HttpClientError, method: string) => Effect.Effect +>(2, (error, method) => { + const reason = error.reason + switch (reason._tag) { + case "TransportError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.NetworkError({ + reason: "TransportError", + description: reason.description, + request: buildHttpRequestDetails(reason.request) + }) + })) + } + case "EncodeError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.NetworkError({ + reason: "EncodeError", + description: reason.description, + request: buildHttpRequestDetails(reason.request) + }) + })) + } + case "InvalidUrlError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.NetworkError({ + reason: "InvalidUrlError", + description: reason.description, + request: buildHttpRequestDetails(reason.request) + }) + })) + } + case "StatusCodeError": { + return mapStatusCodeError(reason, method) + } + case "DecodeError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.InvalidOutputError({ + description: reason.description ?? "Failed to decode response" + }) + })) + } + case "EmptyBodyError": { + return Effect.fail(AiError.make({ + module: "OpenAiClient", + method, + reason: new AiError.InvalidOutputError({ + description: reason.description ?? "Response body was empty" + }) + })) + } + } +}) + +/** @internal */ +const mapStatusCodeError = Effect.fnUntraced(function*( + error: HttpClientError.StatusCodeError, + method: string +) { + const { request, response, description } = error + const status = response.status + const headers = response.headers as Record + const requestId = headers["x-request-id"] + + // Try to get the actual response body. The description from filterStatusOk + // is often just "non 2xx status code", so try reading from response.text + let body: string | undefined = description + if (!description || !description.startsWith("{")) { + const responseBody = yield* Effect.option(response.text) + if (Option.isSome(responseBody) && responseBody.value) { + body = responseBody.value + } + } + + // Try to parse the body as JSON to extract error details + let json: unknown = undefined + // @effect-diagnostics effect/tryCatchInEffectGen:off + try { + json = Predicate.isNotUndefined(body) ? JSON.parse(body) : undefined + } catch { + json = undefined + } + const decoded = Schema.decodeUnknownOption(OpenAiErrorBody)(json) + const compatibleDecoded = Schema.decodeUnknownOption(OpenAiCompatibleErrorBody)(json) + const message = Option.isSome(decoded) + ? decoded.value.error.message + : Option.isSome(compatibleDecoded) + ? compatibleDecoded.value.error + : undefined + const errorCode = Option.isSome(decoded) + ? decoded.value.error.code ?? null + : Option.isSome(compatibleDecoded) + ? compatibleDecoded.value.code ?? null + : null + + const reason = mapStatusCodeToReason({ + status, + headers, + message, + http: buildHttpContext({ request, response, body }), + metadata: { + errorCode, + errorType: Option.isSome(decoded) ? decoded.value.error.type ?? null : null, + requestId: requestId ?? null + } + }) + + return yield* AiError.make({ module: "OpenAiClient", method, reason }) +}) + +// ============================================================================= +// Rate Limits +// ============================================================================= + +/** @internal */ +export const parseRateLimitHeaders = (headers: Record) => { + const retryAfterRaw = headers["retry-after"] + let retryAfter: Duration.Duration | undefined + if (Predicate.isNotUndefined(retryAfterRaw)) { + const parsed = Number.parse(retryAfterRaw) + if (Option.isSome(parsed)) { + retryAfter = Duration.seconds(parsed.value) + } + } + const remainingRaw = headers["x-ratelimit-remaining-requests"] + const remaining = Predicate.isNotUndefined(remainingRaw) + ? Option.getOrNull(Number.parse(remainingRaw)) + : null + return { + retryAfter, + limit: headers["x-ratelimit-limit-requests"] ?? null, + remaining, + resetRequests: headers["x-ratelimit-reset-requests"] ?? null, + resetTokens: headers["x-ratelimit-reset-tokens"] ?? null + } +} + +// ============================================================================= +// HTTP Context +// ============================================================================= + +/** @internal */ +export const buildHttpRequestDetails = ( + request: HttpClientRequest.HttpClientRequest +): typeof Response.HttpRequestDetails.Type => ({ + method: request.method, + url: request.url, + urlParams: Array.from(request.urlParams), + hash: Option.getOrUndefined(request.hash), + headers: Redactable.redact(request.headers) as Record +}) + +/** @internal */ +export const buildHttpContext = (params: { + readonly request: HttpClientRequest.HttpClientRequest + readonly response?: HttpClientResponse.HttpClientResponse + readonly body?: string | undefined +}): typeof AiError.HttpContext.Type => ({ + request: buildHttpRequestDetails(params.request), + response: Predicate.isNotUndefined(params.response) + ? { + status: params.response.status, + headers: Redactable.redact(params.response.headers) as Record + } + : undefined, + body: params.body +}) + +// ============================================================================= +// HTTP Status Code +// ============================================================================= + +/** @internal */ +export const mapStatusCodeToReason = ({ status, headers, message, metadata, http }: { + readonly status: number + readonly headers: Record + readonly message: string | undefined + readonly metadata: OpenAiErrorMetadata + readonly http: typeof AiError.HttpContext.Type +}): AiError.AiErrorReason => { + const errorDescription = AiError.buildErrorDescription({ + status, + message, + method: http.request.method, + url: http.request.url, + errorCode: metadata.errorCode, + errorType: metadata.errorType, + requestId: metadata.requestId, + body: http.body + }) + + switch (status) { + case 400: + return new AiError.InvalidRequestError({ + description: errorDescription, + metadata: { openai: metadata }, + http + }) + case 401: + return new AiError.AuthenticationError({ + kind: "InvalidKey", + description: errorDescription, + metadata, + http + }) + case 403: + return new AiError.AuthenticationError({ + kind: "InsufficientPermissions", + description: errorDescription, + metadata, + http + }) + case 404: + return new AiError.InvalidRequestError({ + description: errorDescription, + metadata: { openai: metadata }, + http + }) + case 409: + case 422: + return new AiError.InvalidRequestError({ + description: errorDescription, + metadata: { openai: metadata }, + http + }) + case 402: + return new AiError.QuotaExhaustedError({ + metadata: { openai: metadata }, + http + }) + case 429: { + // Best-effort detection: OpenAI returns insufficient_quota for billing/quota issues + if ( + metadata.errorCode === "insufficient_quota" || + metadata.errorType === "insufficient_quota" || + metadata.errorCode === "billing_insufficient_balance" || + metadata.errorType === "billing_insufficient_balance" + ) { + return new AiError.QuotaExhaustedError({ + metadata: { openai: metadata }, + http + }) + } + const { retryAfter, ...rateLimitMetadata } = parseRateLimitHeaders(headers) + return new AiError.RateLimitError({ + retryAfter, + metadata: { + openai: { + ...metadata, + ...rateLimitMetadata + } + }, + http + }) + } + default: + if (status >= 500) { + return new AiError.InternalProviderError({ + description: message ?? "Server error", + metadata, + http + }) + } + return new AiError.UnknownError({ + description: message, + metadata, + http + }) + } +} diff --git a/packages/effect-ai-openai/src/internal/utilities.ts b/packages/effect-ai-openai/src/internal/utilities.ts new file mode 100644 index 0000000..26cf670 --- /dev/null +++ b/packages/effect-ai-openai/src/internal/utilities.ts @@ -0,0 +1,27 @@ +import type * as Response from "effect/unstable/ai/Response" + +const finishReasonMap: Record = { + content_filter: "content-filter", + function_call: "tool-calls", + length: "length", + stop: "stop", + tool_calls: "tool-calls" +} + +/** @internal */ +export const escapeJSONDelta = (delta: string): string => JSON.stringify(delta).slice(1, -1) + +/** @internal */ +export const resolveFinishReason = ( + finishReason: string | null | undefined, + hasToolCalls: boolean +): Response.FinishReason => { + if (finishReason == null) { + return hasToolCalls ? "tool-calls" : "stop" + } + const reason = Object.hasOwn(finishReasonMap, finishReason) ? finishReasonMap[finishReason] : undefined + if (reason == null) { + return hasToolCalls ? "tool-calls" : "unknown" + } + return reason +} diff --git a/packages/effect-ai-openai/test/HumanlayerFork.test.ts b/packages/effect-ai-openai/test/HumanlayerFork.test.ts new file mode 100644 index 0000000..5127e3b --- /dev/null +++ b/packages/effect-ai-openai/test/HumanlayerFork.test.ts @@ -0,0 +1,146 @@ +import { assert, describe, it } from '@effect/vitest' +import { OpenAiClient, OpenAiLanguageModel, OpenAiSchema } from '@humanlayer/effect-ai-openai' +import { Effect, Layer, Predicate, Redacted, Schema } from 'effect' +import { LanguageModel, Prompt } from 'effect/unstable/ai' +import { FetchHttpClient } from 'effect/unstable/http' + +const OpenAiResponse = { + id: 'resp_humanlayer_provider_test', + object: 'response', + created_at: 0, + model: 'gpt-test', + status: 'completed', + output: [], + metadata: null, + temperature: null, + top_p: null, + tools: [], + tool_choice: 'auto', + error: null, + incomplete_details: null, + instructions: null, + parallel_tool_calls: true, +} + +const CapturedRequest = Schema.Struct({ + input: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), +}) + +const isWebRequest = (input: string | URL | Request): input is Request => Predicate.hasProperty(input, 'url') + +const makeCapturingFetch = (requests: Array): typeof fetch => + Object.assign( + async (input: string | URL | Request, init?: RequestInit) => { + const request = isWebRequest(input) ? input : new Request(String(input), init) + requests.push(await request.clone().text()) + return new Response(JSON.stringify(OpenAiResponse), { status: 200 }) + }, + { preconnect: fetch.preconnect }, + ) + +describe('@humanlayer/effect-ai-openai', () => { + it('uses HumanLayer-specific Effect service keys', () => { + assert.strictEqual(OpenAiClient.OpenAiClient.key, '@humanlayer/effect-ai-openai/OpenAiClient') + assert.strictEqual(OpenAiLanguageModel.Config.key, '@humanlayer/effect-ai-openai/OpenAiLanguageModel/Config') + }) + + it.live('preserves string and ordered multipart tool results while retaining JSON fallback', () => + Effect.gen(function* () { + const prompt = Prompt.fromMessages([ + Prompt.assistantMessage({ + content: [ + Prompt.toolCallPart({ + id: 'call_text', + name: 'text_tool', + params: {}, + providerExecuted: false, + }), + Prompt.toolCallPart({ + id: 'call_multipart', + name: 'multipart_tool', + params: {}, + providerExecuted: false, + }), + Prompt.toolCallPart({ + id: 'call_object', + name: 'object_tool', + params: {}, + providerExecuted: false, + }), + ], + }), + Prompt.toolMessage({ + content: [ + Prompt.toolResultPart({ + id: 'call_text', + name: 'text_tool', + result: 'PLAIN_TEXT_SENTINEL\n', + isFailure: false, + providerExecuted: false, + }), + Prompt.toolResultPart({ + id: 'call_multipart', + name: 'multipart_tool', + result: [ + Prompt.textPart({ text: 'BEFORE_IMAGE' }), + Prompt.filePart({ mediaType: 'image/png', data: 'iVBORw==' }), + Prompt.textPart({ text: 'AFTER_IMAGE' }), + ], + isFailure: false, + providerExecuted: false, + }), + Prompt.toolResultPart({ + id: 'call_object', + name: 'object_tool', + result: { answer: 42 }, + isFailure: false, + providerExecuted: false, + }), + ], + }), + ]) + const requests: Array = [] + const httpLayer = FetchHttpClient.layer.pipe( + Layer.provide(Layer.succeed(FetchHttpClient.Fetch, makeCapturingFetch(requests))), + ) + const modelLayer = OpenAiLanguageModel.model('gpt-test').pipe( + Layer.provide(OpenAiClient.layer({ apiKey: Redacted.make('sk-test') }).pipe(Layer.provide(httpLayer))), + ) + + yield* LanguageModel.generateText({ prompt }).pipe(Effect.provide(modelLayer)) + + const request = requests[0] + assert.isDefined(request) + const body = Schema.decodeUnknownSync(CapturedRequest)(JSON.parse(request)) + const outputs = body.input.filter((item) => item['type'] === 'function_call_output') + const textOutput = outputs.find((item) => item['call_id'] === 'call_text') + const multipartOutput = outputs.find((item) => item['call_id'] === 'call_multipart') + const objectOutput = outputs.find((item) => item['call_id'] === 'call_object') + + assert.isDefined(textOutput) + assert.isDefined(multipartOutput) + assert.isDefined(objectOutput) + assert.strictEqual(textOutput['output'], 'PLAIN_TEXT_SENTINEL\n') + assert.deepStrictEqual(multipartOutput['output'], [ + { type: 'input_text', text: 'BEFORE_IMAGE' }, + { type: 'input_image', image_url: 'data:image/png;base64,iVBORw==', detail: 'auto' }, + { type: 'input_text', text: 'AFTER_IMAGE' }, + ]) + assert.strictEqual(objectOutput['output'], JSON.stringify({ answer: 42 })) + }), + ) + + it('accepts incomplete flat and nested error events', () => { + const flat = Schema.decodeUnknownSync(OpenAiSchema.ResponseStreamEvent)({ + type: 'error', + message: 'flat provider error', + }) + const nested = Schema.decodeUnknownSync(OpenAiSchema.ResponseStreamEvent)({ + type: 'error', + error: { message: 'nested provider error' }, + }) + + assert.deepStrictEqual(flat, { type: 'error', message: 'flat provider error' }) + assert.deepStrictEqual(nested, { type: 'error', message: 'nested provider error' }) + }) +}) diff --git a/packages/effect-ai-openai/tsconfig.json b/packages/effect-ai-openai/tsconfig.json new file mode 100644 index 0000000..75fb0eb --- /dev/null +++ b/packages/effect-ai-openai/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../../tsconfig.json", + "compilerOptions": { + "noUncheckedIndexedAccess": false, + "noImplicitReturns": false + }, + "include": ["src"] +} diff --git a/packages/effect-ai-openai/vitest.config.ts b/packages/effect-ai-openai/vitest.config.ts new file mode 100644 index 0000000..62216b1 --- /dev/null +++ b/packages/effect-ai-openai/vitest.config.ts @@ -0,0 +1,3 @@ +import { base } from '@humanlayer/fold-vitest-config' + +export default base diff --git a/packages/fold-agent/src/Tools/ApplyPatchTool.ts b/packages/fold-agent/src/Tools/ApplyPatchTool.ts index 500a67a..8dfcd35 100644 --- a/packages/fold-agent/src/Tools/ApplyPatchTool.ts +++ b/packages/fold-agent/src/Tools/ApplyPatchTool.ts @@ -11,6 +11,8 @@ import { defineTool, parsePatch, platformToolDependencies, + ToolResultFailure, + ToolResultText, type PatchOp, type FoldTool, } from '@humanlayer/fold-core' @@ -117,12 +119,12 @@ export const applyPatchTool = (options?: { readonly cwd?: string }): FoldTool => }) } - return { message: `Applied patch.\n${computed.summary.join('\n')}` } + return ToolResultText.make({ text: `Applied patch.\n${computed.summary.join('\n')}` }) }), ).pipe( Effect.catchTag('PlatformError', (error) => Effect.fail(verificationFailed(platformErrorMessage('apply_patch', 'patch target', error))), ), ) - }), + }).pipe(Effect.mapError((error) => ToolResultFailure.make({ text: error.message }))), }) diff --git a/packages/fold-agent/src/Tools/BashTool.ts b/packages/fold-agent/src/Tools/BashTool.ts index 06a11e4..0b2a74d 100644 --- a/packages/fold-agent/src/Tools/BashTool.ts +++ b/packages/fold-agent/src/Tools/BashTool.ts @@ -21,6 +21,8 @@ import { InterruptNote, platformToolDependencies, ToolEvents, + ToolResultFailure, + ToolResultText, truncateTail, utf8ByteLength, type FoldTool, @@ -63,13 +65,9 @@ const BashParameters = Schema.Struct({ }), }) -const BashSuccess = Schema.Struct({ - output: Schema.String, -}) +const BashSuccess = ToolResultText -const BashFailure = Schema.Struct({ - message: Schema.String, -}) +const BashFailure = ToolResultFailure const defaultTimeoutMilliseconds = 120_000 const maxTimeoutMilliseconds = 2_147_483_647 @@ -425,6 +423,6 @@ export const bashTool = (options?: BashToolOptions): FoldTool => }) } - return { output: outputText.length === 0 ? '(no output)' : outputText } - }), + return ToolResultText.make({ text: outputText.length === 0 ? '(no output)' : outputText }) + }).pipe(Effect.mapError((error) => ToolResultFailure.make({ text: error.message }))), }) diff --git a/packages/fold-agent/src/Tools/EditTool.ts b/packages/fold-agent/src/Tools/EditTool.ts index 8c99b3c..68fac0b 100644 --- a/packages/fold-agent/src/Tools/EditTool.ts +++ b/packages/fold-agent/src/Tools/EditTool.ts @@ -10,6 +10,8 @@ import { editToolContract, normalizeEditInput, platformToolDependencies, + ToolResultFailure, + ToolResultText, type FoldTool, } from '@humanlayer/fold-core' import { Effect, FileSystem } from 'effect' @@ -69,6 +71,8 @@ export const editTool = (options?: { readonly cwd?: string }): FoldTool => ), ) - return { message: `Successfully replaced ${outcome.editsApplied} block(s) in ${params.path}.` } - }), + return ToolResultText.make({ + text: `Successfully replaced ${outcome.editsApplied} block(s) in ${params.path}.`, + }) + }).pipe(Effect.mapError((error) => ToolResultFailure.make({ text: error.message }))), }) diff --git a/packages/fold-agent/src/Tools/ReadTool.ts b/packages/fold-agent/src/Tools/ReadTool.ts index 5bbd1ab..024c350 100644 --- a/packages/fold-agent/src/Tools/ReadTool.ts +++ b/packages/fold-agent/src/Tools/ReadTool.ts @@ -11,11 +11,15 @@ import { defaultMaxBytes, platformToolDependencies, readToolContract, + ToolResultFailure, + ToolResultImagePart, + ToolResultMultipart, + ToolResultText, + ToolResultTextPart, truncateHead, type FoldTool, - type ToolResultBlock, } from '@humanlayer/fold-core' -import { Effect, FileSystem, Match, type PlatformError } from 'effect' +import { Effect, FileSystem, Match, Schema, type PlatformError } from 'effect' import { resolveReadPath, resolveToCwd } from '../Fs/PathResolve' import { detectSupportedImageMimeType, imageSniffBytes } from './Image/Mime' @@ -59,49 +63,55 @@ export const readTool = (options?: { readonly cwd?: string }): FoldTool => const bytes = yield* fs .readFile(absolutePath) - .pipe(Effect.mapError((error) => ({ message: platformErrorMessage('read', params.path, error) }))) + .pipe( + Effect.mapError((error) => + ToolResultFailure.make({ text: platformErrorMessage('read', params.path, error) }), + ), + ) const imageMimeType = detectSupportedImageMimeType(bytes.subarray(0, imageSniffBytes)) if (imageMimeType !== null) { const processed = yield* Effect.promise(() => processImage(bytes, imageMimeType)) if (!processed.ok) { - return { - content: [ - { - type: 'text' as const, - text: `Read image file [${imageMimeType}]\n${processed.message}`, - }, - ], - } + return ToolResultText.make({ + text: `Read image file [${imageMimeType}]\n${processed.message}`, + }) } const note = [`Read image file [${processed.mimeType}]`, ...processed.hints].join('\n') - const blocks: Array = [ - { type: 'text', text: note }, - { type: 'image', data: processed.data, mimeType: processed.mimeType }, - ] - return { content: blocks } + return ToolResultMultipart.make({ + content: [ + ToolResultTextPart.make({ text: note }), + ToolResultImagePart.make({ data: processed.data, mediaType: processed.mimeType }), + ], + }) } return yield* readTextContent(bytes, params) - }), + }).pipe( + Effect.mapError((error) => + Schema.is(ToolResultFailure)(error) ? error : ToolResultFailure.make({ text: error.message }), + ), + ), }) /** Read the text path: offset/limit selection, head truncation, and pi's verbatim notices. */ const readTextContent = ( bytes: Uint8Array, params: { readonly path: string; readonly offset?: number | undefined; readonly limit?: number | undefined }, -): Effect.Effect<{ content: ReadonlyArray }, { message: string }> => +): Effect.Effect => Effect.gen(function* () { const allLines = new TextDecoder().decode(bytes).split('\n') const startLine = params.offset !== undefined && params.offset > 0 ? Math.max(0, params.offset - 1) : 0 const startLineDisplay = startLine + 1 if (startLine >= allLines.length) { - return yield* Effect.fail({ - message: `Offset ${params.offset} is beyond end of file (${allLines.length} lines total)`, - }) + return yield* Effect.fail( + ToolResultFailure.make({ + text: `Offset ${params.offset} is beyond end of file (${allLines.length} lines total)`, + }), + ) } const userLimited = params.limit !== undefined @@ -114,14 +124,9 @@ const readTextContent = ( if (truncation.firstLineExceedsLimit) { const firstLineSize = formatSize(new TextEncoder().encode(allLines[startLine] ?? '').length) - return { - content: [ - { - type: 'text' as const, - text: `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(defaultMaxBytes)} limit. Use bash: sed -n '${startLineDisplay}p' ${params.path} | head -c ${defaultMaxBytes}]`, - }, - ], - } + return ToolResultText.make({ + text: `[Line ${startLineDisplay} is ${firstLineSize}, exceeds ${formatSize(defaultMaxBytes)} limit. Use bash: sed -n '${startLineDisplay}p' ${params.path} | head -c ${defaultMaxBytes}]`, + }) } let outputText = truncation.content @@ -139,5 +144,5 @@ const readTextContent = ( outputText += `\n\n[${remaining} more lines in file. Use offset=${startLine + selectedLines.length + 1} to continue.]` } - return { content: [{ type: 'text' as const, text: outputText }] } + return ToolResultText.make({ text: outputText }) }) diff --git a/packages/fold-agent/src/Tools/WebFetchTool.ts b/packages/fold-agent/src/Tools/WebFetchTool.ts index d08002b..661b23b 100644 --- a/packages/fold-agent/src/Tools/WebFetchTool.ts +++ b/packages/fold-agent/src/Tools/WebFetchTool.ts @@ -1,10 +1,13 @@ import { defineTool, - textResult, + ToolResultFailure, + ToolResultImagePart, + ToolResultMultipart, + ToolResultText, + ToolResultTextPart, webFetchToolContract, type FoldTool, - type ToolResultBlock, - type ToolResultContent, + type ToolResultSuccess, } from '@humanlayer/fold-core' import { Duration, Effect, Option, Schema, Stream } from 'effect' import { FetchHttpClient, Headers, HttpClient } from 'effect/unstable/http' @@ -26,9 +29,10 @@ const browserUserAgent = type WebFetchParameters = typeof webFetchToolContract.parameters.Type /** A tool result is one message value: reuse the whole `{ message }` shape the contract already advertises. */ -type WebFetchFailure = { readonly message: string } +type WebFetchFailure = ToolResultFailure -const failWith = (message: string): Effect.Effect => Effect.fail({ message }) +const failWith = (message: string): Effect.Effect => + Effect.fail(ToolResultFailure.make({ text: message })) // --- header parsing (parse, don't validate: the Content-Length header is untrusted text) --------------- @@ -167,27 +171,28 @@ const renderDocument = ( document: FetchedDocument, format: 'markdown' | 'text' | 'html', turndown: TurndownService, -): Effect.Effect => +): Effect.Effect => Effect.gen(function* () { const imageMimeType = imageMimeFor(document.bytes, document.contentType) if (imageMimeType !== null) { const processed = yield* Effect.promise(() => processImage(document.bytes, imageMimeType)) if (!processed.ok) { - return textResult(`Fetched image [${imageMimeType}]\n${processed.message}`) + return ToolResultText.make({ text: `Fetched image [${imageMimeType}]\n${processed.message}` }) } const note = [`Fetched image [${processed.mimeType}] from ${url}`, ...processed.hints].join('\n') - const blocks: ReadonlyArray = [ - { type: 'text', text: note }, - { type: 'image', data: processed.data, mimeType: processed.mimeType }, - ] - return { content: blocks } + return ToolResultMultipart.make({ + content: [ + ToolResultTextPart.make({ text: note }), + ToolResultImagePart.make({ data: processed.data, mediaType: processed.mimeType }), + ], + }) } const body = new TextDecoder().decode(document.bytes) - if (format === 'html') return textResult(body) - if (!isHtml(document.contentType, body)) return textResult(body) - return textResult(format === 'text' ? stripHtmlTags(body) : turndown.turndown(body)) + if (format === 'html') return ToolResultText.make({ text: body }) + if (!isHtml(document.contentType, body)) return ToolResultText.make({ text: body }) + return ToolResultText.make({ text: format === 'text' ? stripHtmlTags(body) : turndown.turndown(body) }) }) // --- tool --------------------------------------------------------------------------------------------- @@ -195,7 +200,7 @@ const renderDocument = ( export const webFetchTool = (): FoldTool => { const turndown = makeTurndown() - const runWebFetch = (params: WebFetchParameters): Effect.Effect => + const runWebFetch = (params: WebFetchParameters): Effect.Effect => Effect.gen(function* () { if (!params.url.startsWith('http://') && !params.url.startsWith('https://')) { return yield* failWith('URL must start with http:// or https://') diff --git a/packages/fold-agent/src/Tools/WebSearchTool.ts b/packages/fold-agent/src/Tools/WebSearchTool.ts index 531dc84..1899172 100644 --- a/packages/fold-agent/src/Tools/WebSearchTool.ts +++ b/packages/fold-agent/src/Tools/WebSearchTool.ts @@ -1,4 +1,11 @@ -import { CurrentAgent, defineTool, webSearchToolContract, type FoldTool } from '@humanlayer/fold-core' +import { + CurrentAgent, + defineTool, + ToolResultFailure, + ToolResultText, + webSearchToolContract, + type FoldTool, +} from '@humanlayer/fold-core' import { Effect, Predicate } from 'effect' const defaultTimeoutMs = 25_000 @@ -182,6 +189,6 @@ export const webSearchTool = (options?: WebSearchToolOptions): FoldTool => timeoutMs, }) - return result ?? 'No search results found. Please try a different query.' - }), + return ToolResultText.make({ text: result ?? 'No search results found. Please try a different query.' }) + }).pipe(Effect.mapError((error) => ToolResultFailure.make({ text: error.message }))), }) diff --git a/packages/fold-agent/src/Tools/WriteTool.ts b/packages/fold-agent/src/Tools/WriteTool.ts index 4a54dd3..c17b47c 100644 --- a/packages/fold-agent/src/Tools/WriteTool.ts +++ b/packages/fold-agent/src/Tools/WriteTool.ts @@ -6,6 +6,8 @@ import { defineTool, platformToolDependencies, + ToolResultFailure, + ToolResultText, utf8ByteLength, writeToolContract, type FoldTool, @@ -50,6 +52,8 @@ export const writeTool = (options?: { readonly cwd?: string }): FoldTool => ), ) - return { message: `Successfully wrote ${utf8ByteLength(params.content)} bytes to ${params.path}` } - }), + return ToolResultText.make({ + text: `Successfully wrote ${utf8ByteLength(params.content)} bytes to ${params.path}`, + }) + }).pipe(Effect.mapError((error) => ToolResultFailure.make({ text: error.message }))), }) diff --git a/packages/fold-agent/test/TestHelpers.ts b/packages/fold-agent/test/TestHelpers.ts index 9b6a8a4..dcd6254 100644 --- a/packages/fold-agent/test/TestHelpers.ts +++ b/packages/fold-agent/test/TestHelpers.ts @@ -171,10 +171,10 @@ const stringField = } /** The `message` field of a tool success/failure value. */ -export const messageOf: (value: unknown) => string = stringField('message') +export const messageOf: (value: unknown) => string = stringField('text') /** The `output` field of a bash tool success value. */ -export const outputOf: (value: unknown) => string = stringField('output') +export const outputOf: (value: unknown) => string = stringField('text') const parentDirs = (path: string): ReadonlyArray => { const parents: Array = [] diff --git a/packages/fold-agent/test/Tools/ReadTool.vi.test.ts b/packages/fold-agent/test/Tools/ReadTool.vi.test.ts index 7d8ab1c..ef6621d 100644 --- a/packages/fold-agent/test/Tools/ReadTool.vi.test.ts +++ b/packages/fold-agent/test/Tools/ReadTool.vi.test.ts @@ -2,7 +2,7 @@ import { writeFileSync } from 'node:fs' import { join } from 'node:path' import { expect, it } from '@effect/vitest' -import { ToolResultContent } from '@humanlayer/fold-core' +import { ToolResultMultipart, ToolResultText } from '@humanlayer/fold-core' import { Effect, Schema } from 'effect' import { readTool } from '../../src/index' @@ -31,16 +31,18 @@ const onePixelBmp = (): Uint8Array => { return bytes } -const isToolResultContent = Schema.is(ToolResultContent) +const isToolResultMultipart = Schema.is(ToolResultMultipart) +const isToolResultText = Schema.is(ToolResultText) -const contentOf = (result: unknown): ToolResultContent['content'] => { - if (!isToolResultContent(result)) throw new Error('expected a content-block tool result') +const contentOf = (result: unknown): ToolResultMultipart['content'] => { + if (!isToolResultMultipart(result)) throw new Error('expected multipart tool output') return result.content } const firstText = (result: unknown): string => { + if (isToolResultText(result)) return result.text const block = contentOf(result)[0] - if (block?.type !== 'text') throw new Error('expected a text block') + if (block?._tag !== 'text-part') throw new Error('expected a text part') return block.text } @@ -102,7 +104,7 @@ it.effect('fails with the offset-beyond-EOF message', () => Effect.flip, ) - expect(failure).toEqual({ message: 'Offset 99 is beyond end of file (2 lines total)' }) + expect(failure).toEqual({ _tag: 'failure', text: 'Offset 99 is beyond end of file (2 lines total)' }) }), ) @@ -124,12 +126,12 @@ it.effect('returns PNG images as an image content block with a note (hard requir const result = yield* runHandler(handlerOf(readTool({ cwd: dir }))({ path: 'pixel.png' })) const blocks = contentOf(result) - expect(blocks[0]?.type).toBe('text') + expect(blocks[0]?._tag).toBe('text-part') expect(firstText(result)).toContain('Read image file [image/png]') const image = blocks[1] - if (image?.type !== 'image') throw new Error('expected an image block') - expect(image.mimeType).toBe('image/png') + if (image?._tag !== 'image-part') throw new Error('expected an image part') + expect(image.mediaType).toBe('image/png') // Small image passes through unresized: bytes round-trip exactly. expect(image.data).toBe(onePixelPngBase64) }), @@ -145,8 +147,8 @@ it.effect('converts BMP to PNG with a conversion hint', () => expect(firstText(result)).toContain('[Image converted from image/bmp to image/png.]') const image = blocks[1] - if (image?.type !== 'image') throw new Error('expected an image block') - expect(image.mimeType).toBe('image/png') + if (image?._tag !== 'image-part') throw new Error('expected an image part') + expect(image.mediaType).toBe('image/png') }), ) diff --git a/packages/fold-agent/test/Tools/WebFetchTool.vi.test.ts b/packages/fold-agent/test/Tools/WebFetchTool.vi.test.ts index bc24413..2fd48b4 100644 --- a/packages/fold-agent/test/Tools/WebFetchTool.vi.test.ts +++ b/packages/fold-agent/test/Tools/WebFetchTool.vi.test.ts @@ -8,7 +8,7 @@ import { readFileSync } from 'node:fs' import { createServer, type Server } from 'node:http' import { it } from '@effect/vitest' -import { ToolResultContent } from '@humanlayer/fold-core' +import { ToolResultMultipart, ToolResultText } from '@humanlayer/fold-core' import { Effect, Schema } from 'effect' import { afterAll, beforeAll, expect } from 'vitest' @@ -34,16 +34,18 @@ const pngDimensions = (bytes: Uint8Array): { readonly width: number; readonly he return { width: view.getUint32(16, false), height: view.getUint32(20, false) } } -const isToolResultContent = Schema.is(ToolResultContent) +const isToolResultMultipart = Schema.is(ToolResultMultipart) +const isToolResultText = Schema.is(ToolResultText) -const contentOf = (result: unknown): ToolResultContent['content'] => { - if (!isToolResultContent(result)) throw new Error('expected a content-block tool result') +const contentOf = (result: unknown): ToolResultMultipart['content'] => { + if (!isToolResultMultipart(result)) throw new Error('expected multipart tool output') return result.content } const firstText = (result: unknown): string => { + if (isToolResultText(result)) return result.text const block = contentOf(result)[0] - if (block?.type !== 'text') throw new Error('expected a text block') + if (block?._tag !== 'text-part') throw new Error('expected a text part') return block.text } @@ -155,8 +157,8 @@ it.live('returns a fetched PNG photo as an image content block', () => expect(firstText(result)).toContain('Fetched image [image/png]') const image = blocks[1] - if (image?.type !== 'image') throw new Error('expected an image block') - expect(image.mimeType).toBe('image/png') + if (image?._tag !== 'image-part') throw new Error('expected an image part') + expect(image.mediaType).toBe('image/png') // A real 128x128 photo is within the resize limits, so it round-trips byte-for-byte. expect(image.data).toBe(hopperBase64) diff --git a/packages/fold-agent/test/Tools/WriteEditTools.vi.test.ts b/packages/fold-agent/test/Tools/WriteEditTools.vi.test.ts index dbf98e2..f783b56 100644 --- a/packages/fold-agent/test/Tools/WriteEditTools.vi.test.ts +++ b/packages/fold-agent/test/Tools/WriteEditTools.vi.test.ts @@ -15,7 +15,7 @@ it.effect('write creates parent directories and the file', () => handlerOf(writeTool({ cwd: dir }))({ path: 'nested/deeper/new.txt', content: 'hello fold\n' }), ) - expect(result).toEqual({ message: 'Successfully wrote 11 bytes to nested/deeper/new.txt' }) + expect(result).toEqual({ _tag: 'text', text: 'Successfully wrote 11 bytes to nested/deeper/new.txt' }) expect(readFileSync(join(dir, 'nested/deeper/new.txt'), 'utf-8')).toBe('hello fold\n') }), ) @@ -28,7 +28,7 @@ it.effect('write overwrites existing files and reports true UTF-8 bytes (not UTF // One emoji: 2 UTF-16 code units (pi would say 2), 4 UTF-8 bytes (fold reports 4 - D18). const result = yield* runHandler(handlerOf(writeTool({ cwd: dir }))({ path: 'file.txt', content: '🎉' })) - expect(result).toEqual({ message: 'Successfully wrote 4 bytes to file.txt' }) + expect(result).toEqual({ _tag: 'text', text: 'Successfully wrote 4 bytes to file.txt' }) expect(readFileSync(join(dir, 'file.txt'), 'utf-8')).toBe('🎉') }), ) @@ -48,7 +48,7 @@ it.effect('edit applies a batch and reports the pi success message', () => }), ) - expect(result).toEqual({ message: 'Successfully replaced 2 block(s) in code.ts.' }) + expect(result).toEqual({ _tag: 'text', text: 'Successfully replaced 2 block(s) in code.ts.' }) expect(readFileSync(join(dir, 'code.ts'), 'utf-8')).toBe('const a = 10\nconst b = 2\nconst c = 30\n') }), ) @@ -62,7 +62,7 @@ it.effect('edit accepts the legacy single-pair form through the shim', () => handlerOf(editTool({ cwd: dir }))({ path: 'legacy.txt', oldText: 'beta', newText: 'gamma' }), ) - expect(result).toEqual({ message: 'Successfully replaced 1 block(s) in legacy.txt.' }) + expect(result).toEqual({ _tag: 'text', text: 'Successfully replaced 1 block(s) in legacy.txt.' }) expect(readFileSync(join(dir, 'legacy.txt'), 'utf-8')).toBe('alpha gamma\n') }), ) diff --git a/packages/fold-codex/package.json b/packages/fold-codex/package.json index 30fe2fe..f008d7d 100644 --- a/packages/fold-codex/package.json +++ b/packages/fold-codex/package.json @@ -15,15 +15,14 @@ "test:watch": "bun vitest" }, "dependencies": { + "@humanlayer/effect-ai-openai": "workspace:*", "@humanlayer/fold-core": "workspace:*" }, "peerDependencies": { - "@effect/ai-openai": "catalog:", "@effect/platform-node": "catalog:", "effect": "catalog:" }, "devDependencies": { - "@effect/ai-openai": "catalog:", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@humanlayer/fold-agent": "workspace:*", diff --git a/packages/fold-codex/src/CodexModel.ts b/packages/fold-codex/src/CodexModel.ts index 3bb9dd2..eaf6ac8 100644 --- a/packages/fold-codex/src/CodexModel.ts +++ b/packages/fold-codex/src/CodexModel.ts @@ -1,5 +1,6 @@ +import * as NodeFileSystem from '@effect/platform-node/NodeFileSystem' /** - * The fold-codex model descriptor: clanka's shape over the official `@effect/ai-openai` provider + * The fold-codex model descriptor: clanka's shape over the official `@humanlayer/effect-ai-openai` provider * pointed at the ChatGPT Codex backend (D23). The stock OpenAiLanguageModel runs unchanged; all Codex * behavior lives in a decorated OpenAiClient underneath it, where every signature is concrete: * (1) leading `system`/`developer` input items lift into the Responses `instructions` field (clanka's @@ -13,9 +14,8 @@ * injection so retries never re-enter the auth path. Retryable provider responses, including 429, * retry before the first stream event and honor the provider's Retry-After delay. */ -import { OpenAiClient, OpenAiLanguageModel } from '@effect/ai-openai' -import type * as OpenAiSchema from '@effect/ai-openai/OpenAiSchema' -import * as NodeFileSystem from '@effect/platform-node/NodeFileSystem' +import { OpenAiClient, OpenAiLanguageModel } from '@humanlayer/effect-ai-openai' +import type * as OpenAiSchema from '@humanlayer/effect-ai-openai/OpenAiSchema' import { customModel, resolveCodexReasoning } from '@humanlayer/fold-core' import type { ReasoningLevel, FoldModel } from '@humanlayer/fold-core' import { Match, Context, Duration, Effect, Layer, Option, Schedule, Schema, Stream } from 'effect' diff --git a/packages/fold-codex/test/CodexImageReadDelivery.vi.test.ts b/packages/fold-codex/test/CodexImageReadDelivery.vi.test.ts new file mode 100644 index 0000000..95d7754 --- /dev/null +++ b/packages/fold-codex/test/CodexImageReadDelivery.vi.test.ts @@ -0,0 +1,105 @@ +/** + * Deterministic end-to-end regression for the image-read path up to the Codex HTTP boundary. It executes + * the real read tool and session prompt builder, then asserts the intended request emitted with no active tools. + */ +import { expect, it } from '@effect/vitest' +import { Effect, Encoding, Option, Schema } from 'effect' +import { FetchHttpClient } from 'effect/unstable/http' + +import { CodexTokenData, makeCodexLanguageModel } from '../src/index' +import type { CodexAuthStore } from '../src/index' +import { type CapturedFetchRequest, makeCapturingFetch, runImageReadInference } from './SessionModelPathTestHarness' + +const terminalSse = `data: ${JSON.stringify({ + type: 'response.completed', + response: { id: 'resp_capture', model: 'gpt-5.5', created_at: 1, output: [] }, + sequence_number: 1, +})}\n\n` + +const token = new CodexTokenData({ + type: 'oauth', + access: 'capture-access-token', + refresh: 'unused-refresh-token', + expires: Number.MAX_SAFE_INTEGER, + accountId: 'acct_capture', +}) + +const memoryAuthStore: CodexAuthStore = { + path: 'memory://codex-image-read-capture', + load: Effect.succeed(Option.some(token)), + save: (updated) => Effect.succeed(updated), + clear: Effect.void, +} + +const CapturedResponsesRequest = Schema.Struct({ + model: Schema.String, + stream: Schema.Boolean, + input: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), + tools: Schema.optionalKey(Schema.Array(Schema.Unknown)), +}) + +const decodeCapturedResponsesRequest = Schema.decodeUnknownSync(CapturedResponsesRequest) +const decodeWireContent = Schema.decodeUnknownSync(Schema.Array(Schema.Record(Schema.String, Schema.Unknown))) + +it.effect('sends an actual image read as input_image with zero inference tools', () => { + const requests: Array = [] + const capturingFetch = makeCapturingFetch( + requests, + () => new Response(terminalSse, { status: 200, headers: { 'content-type': 'text/event-stream' } }), + ) + + return Effect.gen(function* () { + const model = yield* makeCodexLanguageModel({ + model: 'gpt-5.5', + reasoning: 'off', + apiUrl: 'https://codex.capture.test/backend-api/codex', + store: memoryAuthStore, + requestRetryTimes: 0, + }) + const fixture = yield* runImageReadInference(model) + + expect(requests).toHaveLength(1) + const captured = requests[0] + if (captured === undefined) throw new Error('expected one captured Responses request') + expect(captured.url).toBe('https://codex.capture.test/backend-api/codex/responses') + expect(captured.authorization).toBe('Bearer capture-access-token') + if (process.env.FOLD_CODEX_DUMP_IMAGE_READ_REQUEST === '1') { + yield* Effect.sync(() => process.stdout.write(`${captured.body}\n`)) + } + + const body = decodeCapturedResponsesRequest(JSON.parse(captured.body)) + expect(body.model).toBe('gpt-5.5') + expect(body.stream).toBe(true) + // AgentRuntime passes an empty active toolkit; the provider omits `tools` entirely on the wire. + expect(body.tools).toBeUndefined() + + // The production read tool returned the exact generated PNG, and RequestBuilder lowered it to + // native Prompt parts inside the original tool result. + expect(JSON.stringify(fixture.readResult)).toContain(fixture.sourceImageBase64) + const promptFileParts = fixture.prompt.content.flatMap((message) => { + if (message.role !== 'tool') return [] + return message.content.flatMap((part) => + part.type === 'tool-result' && Array.isArray(part.result) + ? part.result.filter((resultPart) => resultPart.type === 'file') + : [], + ) + }) + expect(promptFileParts).toHaveLength(1) + const promptImage = promptFileParts[0] + if (!(promptImage?.data instanceof Uint8Array)) throw new Error('expected decoded image bytes') + expect(Encoding.encodeBase64(promptImage.data)).toBe(fixture.sourceImageBase64) + + // Text and image stay correlated in the native multipart function output. + const functionOutput = body.input.find((item) => item['type'] === 'function_call_output') + if (functionOutput === undefined || !Array.isArray(functionOutput['output'])) + throw new Error('expected multipart function_call_output') + const functionContent = decodeWireContent(functionOutput['output']) + const imageParts = functionContent.filter((part) => part['type'] === 'input_image') + expect(imageParts).toHaveLength(1) + expect(imageParts[0]?.['image_url']).toBe(`data:image/png;base64,${fixture.sourceImageBase64}`) + expect(functionContent.filter((part) => part['type'] === 'input_text')).toHaveLength(1) + expect(captured.body).not.toContain('Image omitted here') + expect(captured.body).not.toContain('The following image content belongs') + expect(captured.body).toContain(fixture.sourceImageBase64) + }).pipe(Effect.provideService(FetchHttpClient.Fetch, capturingFetch)) +}) diff --git a/packages/fold-codex/test/CodexLive.vi.test.ts b/packages/fold-codex/test/CodexLive.vi.test.ts index 49cc78f..8e743d0 100644 --- a/packages/fold-codex/test/CodexLive.vi.test.ts +++ b/packages/fold-codex/test/CodexLive.vi.test.ts @@ -12,6 +12,7 @@ import { describe, expect, it } from '@effect/vitest' import { Effect, Option, Schema, Stream } from 'effect' import { makeCodexLanguageModel } from '../src/index' +import { expectedImageIdentification, runImageReadInference } from './SessionModelPathTestHarness' const authPath = join(homedir(), '.fold', 'auth.json') @@ -31,6 +32,7 @@ const hasCodexCredentials = (): boolean => { const skip = Boolean(process.env.CI) || !hasCodexCredentials() const modelId = process.env.FOLD_CODEX_LIVE_MODEL ?? 'gpt-5.5' +const skipImageRead = skip || process.env.FOLD_CODEX_LIVE_IMAGE_READ !== '1' describe.skipIf(skip)('codex live (skipped in CI or without a codex entry in ~/.fold/auth.json)', () => { it.live( @@ -78,3 +80,22 @@ describe.skipIf(skip)('codex live (skipped in CI or without a codex entry in ~/. 180_000, ) }) + +// Opt-in regression probe proving a real Codex model can perceive an image returned by the read tool. +describe.skipIf(skipImageRead)( + 'codex image-read live (set FOLD_CODEX_LIVE_IMAGE_READ=1; skipped in CI or without local credentials)', + () => { + it.live( + 'identifies generated visual content delivered from the actual read result with zero inference tools', + () => + Effect.gen(function* () { + const service = yield* makeCodexLanguageModel({ model: modelId, reasoning: 'low' }) + const result = yield* runImageReadInference(service) + const normalized = result.text.toLowerCase().replaceAll(' ', '').trim() + + expect(normalized).toContain(expectedImageIdentification) + }).pipe(Effect.scoped), + 180_000, + ) + }, +) diff --git a/packages/fold-codex/test/CodexModel.vi.test.ts b/packages/fold-codex/test/CodexModel.vi.test.ts index 7216ff1..eed4219 100644 --- a/packages/fold-codex/test/CodexModel.vi.test.ts +++ b/packages/fold-codex/test/CodexModel.vi.test.ts @@ -1,6 +1,6 @@ -import type { OpenAiClient } from '@effect/ai-openai' -import type * as OpenAiSchema from '@effect/ai-openai/OpenAiSchema' import { describe, expect, it } from '@effect/vitest' +import type { OpenAiClient } from '@humanlayer/effect-ai-openai' +import type * as OpenAiSchema from '@humanlayer/effect-ai-openai/OpenAiSchema' import { Context, Deferred, Duration, Effect, Fiber, Layer, Ref, Stream } from 'effect' import { TestClock } from 'effect/testing' import { AiError } from 'effect/unstable/ai' diff --git a/packages/fold-codex/test/EffectToolResultEncodingRepro.vi.test.ts b/packages/fold-codex/test/EffectToolResultEncodingRepro.vi.test.ts new file mode 100644 index 0000000..63da14a --- /dev/null +++ b/packages/fold-codex/test/EffectToolResultEncodingRepro.vi.test.ts @@ -0,0 +1,131 @@ +import { assert, it } from '@effect/vitest' +/** + * Regression coverage for patched Effect AI client tool-result encoding. This bypasses Fold handlers + * and RequestBuilder so captured values isolate the @humanlayer/effect-ai-openai provider behavior. + */ +import { OpenAiClient, OpenAiLanguageModel } from '@humanlayer/effect-ai-openai' +import { Effect, Layer, Predicate, Redacted, Schema } from 'effect' +import { LanguageModel, Prompt } from 'effect/unstable/ai' +import { FetchHttpClient } from 'effect/unstable/http' + +import { type CapturedFetchRequest, makeCapturingFetch } from './SessionModelPathTestHarness' + +const openAiResponse = { + id: 'resp_effect_tool_result_repro', + object: 'response', + created_at: 0, + model: 'gpt-test', + status: 'completed', + output: [], + metadata: null, + temperature: null, + top_p: null, + tools: [], + tool_choice: 'auto', + error: null, + incomplete_details: null, + instructions: null, + parallel_tool_calls: true, +} + +const CapturedRequest = Schema.Struct({ + input: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), +}) + +it.live('passes strings through and emits multipart client tool results in Effect 4.0.0-rc.112', () => + Effect.gen(function* () { + const stringResult = 'PLAIN_TEXT_SENTINEL\n' + const multipartResult = [ + Prompt.textPart({ text: 'IMAGE_TEXT_SENTINEL' }), + Prompt.filePart({ mediaType: 'image/png', data: new Uint8Array([137, 80, 78, 71]) }), + ] + const prompt = Prompt.fromMessages([ + Prompt.assistantMessage({ + content: [ + Prompt.toolCallPart({ + id: 'call_text', + name: 'text_tool', + params: {}, + providerExecuted: false, + }), + Prompt.toolCallPart({ + id: 'call_image', + name: 'image_tool', + params: {}, + providerExecuted: false, + }), + Prompt.toolCallPart({ + id: 'call_object', + name: 'object_tool', + params: {}, + providerExecuted: false, + }), + ], + }), + Prompt.toolMessage({ + content: [ + Prompt.toolResultPart({ + id: 'call_text', + name: 'text_tool', + result: stringResult, + isFailure: false, + providerExecuted: false, + }), + Prompt.toolResultPart({ + id: 'call_image', + name: 'image_tool', + result: multipartResult, + isFailure: false, + providerExecuted: false, + }), + Prompt.toolResultPart({ + id: 'call_object', + name: 'object_tool', + result: { answer: 42 }, + isFailure: false, + providerExecuted: false, + }), + ], + }), + ]) + + const requests: Array = [] + const httpLayer = FetchHttpClient.layer.pipe( + Layer.provide( + Layer.succeed( + FetchHttpClient.Fetch, + makeCapturingFetch(requests, () => new Response(JSON.stringify(openAiResponse), { status: 200 })), + ), + ), + ) + const modelLayer = OpenAiLanguageModel.model('gpt-test').pipe( + Layer.provide(OpenAiClient.layer({ apiKey: Redacted.make('sk-test') }).pipe(Layer.provide(httpLayer))), + ) + + yield* LanguageModel.generateText({ prompt }).pipe(Effect.provide(modelLayer)) + + const captured = requests[0] + assert.isDefined(captured) + const body = Schema.decodeUnknownSync(CapturedRequest)(JSON.parse(captured.body)) + const outputs = body.input.filter( + (item) => item['type'] === 'function_call_output' && Predicate.isString(item['call_id']), + ) + const textOutput = outputs.find((item) => item['call_id'] === 'call_text') + const imageOutput = outputs.find((item) => item['call_id'] === 'call_image') + const objectOutput = outputs.find((item) => item['call_id'] === 'call_object') + + assert.isDefined(textOutput) + assert.isDefined(imageOutput) + assert.isDefined(objectOutput) + assert.strictEqual(textOutput['output'], stringResult) + assert.strictEqual(objectOutput['output'], JSON.stringify({ answer: 42 })) + assert.deepStrictEqual(imageOutput['output'], [ + { type: 'input_text', text: 'IMAGE_TEXT_SENTINEL' }, + { + type: 'input_image', + image_url: 'data:image/png;base64,iVBORw==', + detail: 'auto', + }, + ]) + }), +) diff --git a/packages/fold-codex/test/SessionModelPathTestHarness.ts b/packages/fold-codex/test/SessionModelPathTestHarness.ts new file mode 100644 index 0000000..a140674 --- /dev/null +++ b/packages/fold-codex/test/SessionModelPathTestHarness.ts @@ -0,0 +1,316 @@ +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { deflateSync } from 'node:zlib' + +import * as NodeServices from '@effect/platform-node/NodeServices' +import { readTool } from '@humanlayer/fold-agent' +import { + AgentId, + buildPrompt, + CurrentAgent, + CurrentToolCall, + EventLog, + foldPartOptionsKey, + InterruptNote, + layerInMemoryEventLog, + LogEntryInputs, + MessageId, + messagesForAgent, + providerToolCallIdKey, + StopController, + Subagents, + ToolCallId, + ToolEvents, + ToolState, + type FoldTool, + type ToolHandlerServices, + type ToolResultLogEntry, +} from '@humanlayer/fold-core' +import { Effect, Layer, Predicate, Schema, type Scope, Stream } from 'effect' +import { type LanguageModel, type Prompt, Toolkit } from 'effect/unstable/ai' + +export const imageIdentificationPrompt = + 'Inspect the image returned by read. Name its three vertical color bands from left to right. ' + + 'Answer only as left=,middle=,right=.' + +export const expectedImageIdentification = 'left=yellow,middle=magenta,right=cyan' + +const imageWidth = 96 +const imageHeight = 48 +const fixtureAgentId = AgentId.make('agent_aaaaaaaaaaaaaaaaaaaaaaaa') + +export type CapturedFetchRequest = { + readonly url: string + readonly authorization: string | null + readonly body: string +} + +const isWebRequest = (input: string | URL | Request): input is Request => Predicate.hasProperty(input, 'url') + +/** Replace only Fetch while recording the fully encoded outbound HTTP request. */ +export const makeCapturingFetch = (requests: Array, respond: () => Response): typeof fetch => + Object.assign( + async (input: string | URL | Request, init?: RequestInit) => { + const request = isWebRequest(input) ? input : new Request(String(input), init) + requests.push({ + url: request.url, + authorization: request.headers.get('authorization'), + body: await request.clone().text(), + }) + return respond() + }, + { preconnect: fetch.preconnect }, + ) + +/** A real scoped temp directory for production filesystem and process-backed tool handlers. */ +export const makeTemporaryTestDirectory = (prefix: string) => + Effect.acquireRelease( + Effect.sync(() => mkdtempSync(join(tmpdir(), prefix))), + (directory) => Effect.sync(() => rmSync(directory, { recursive: true, force: true })), + ) + +const pngCrc32 = (bytes: Uint8Array): number => { + let crc = 0xffffffff + for (const byte of bytes) { + crc ^= byte + for (let bit = 0; bit < 8; bit += 1) { + crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0) + } + } + return (crc ^ 0xffffffff) >>> 0 +} + +const pngChunk = (type: string, data: Uint8Array): Buffer => { + const typeBytes = Buffer.from(type, 'ascii') + const chunk = Buffer.alloc(12 + data.byteLength) + chunk.writeUInt32BE(data.byteLength, 0) + typeBytes.copy(chunk, 4) + Buffer.from(data).copy(chunk, 8) + chunk.writeUInt32BE(pngCrc32(Buffer.concat([typeBytes, data])), 8 + data.byteLength) + return chunk +} + +/** Generate a tiny lossless PNG with three unambiguous, metadata-free color bands. */ +export const makeDeterministicColorBandsPng = (): Uint8Array => { + const header = Buffer.alloc(13) + header.writeUInt32BE(imageWidth, 0) + header.writeUInt32BE(imageHeight, 4) + header[8] = 8 // bit depth + header[9] = 6 // RGBA + + const scanlines = Buffer.alloc(imageHeight * (1 + imageWidth * 4)) + for (let y = 0; y < imageHeight; y += 1) { + const rowOffset = y * (1 + imageWidth * 4) + scanlines[rowOffset] = 0 // no PNG row filter + for (let x = 0; x < imageWidth; x += 1) { + const pixelOffset = rowOffset + 1 + x * 4 + const color: readonly [number, number, number] = + x < imageWidth / 3 ? [255, 255, 0] : x < (imageWidth * 2) / 3 ? [255, 0, 255] : [0, 255, 255] + scanlines[pixelOffset] = color[0] + scanlines[pixelOffset + 1] = color[1] + scanlines[pixelOffset + 2] = color[2] + scanlines[pixelOffset + 3] = 255 + } + } + + return Buffer.concat([ + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + pngChunk('IHDR', header), + pngChunk('IDAT', deflateSync(scanlines)), + pngChunk('IEND', new Uint8Array()), + ]) +} + +const toolHandlerTestLayer: Layer.Layer = Layer.mergeAll( + NodeServices.layer, + Layer.succeed(ToolState, { get: () => Effect.succeed(null), set: () => Effect.void }), + Layer.succeed(ToolEvents, { emit: () => Effect.void }), + Layer.succeed(StopController, { requestStop: () => Effect.void, isStopRequested: Effect.succeed(false) }), + Layer.succeed(CurrentAgent, { + agentId: fixtureAgentId, + parentAgentId: null, + }), + Layer.succeed(CurrentToolCall, { toolCallId: ToolCallId.make('tool_call_aaaaaaaaaaaaaaaaaaaaaaaa') }), + Layer.succeed(InterruptNote, { set: () => Effect.void }), + Layer.succeed(Subagents, { + dispatch: () => Effect.die(new Error('Subagents are unavailable in the image-read test harness')), + fork: () => Effect.die(new Error('Subagents are unavailable in the image-read test harness')), + resume: () => Effect.die(new Error('Subagents are unavailable in the image-read test harness')), + continueSubagent: () => Effect.die(new Error('Subagents are unavailable in the image-read test harness')), + }), +) + +const decodeJson = Schema.decodeUnknownEffect(Schema.Json) + +const toolCallIdAt = (index: number): ToolCallId => + ToolCallId.make(`tool_call_${String.fromCharCode('a'.charCodeAt(0) + index).repeat(24)}`) + +const messageIdAt = (index: number): MessageId => + MessageId.make(`msg_${String.fromCharCode('a'.charCodeAt(0) + index).repeat(24)}`) + +export type DurableToolResultInput = { + readonly name: string + readonly params: typeof Schema.Json.Type + readonly result: typeof Schema.Json.Type + readonly isFailure: boolean + readonly providerToolCallId?: string +} + +export type SessionPromptFixture = { + readonly prompt: Prompt.Prompt + readonly entries: ReadonlyArray +} + +/** Execute one production Fold tool handler under the same platform and per-call services as runtime. */ +export const executeToolHandler = (tool: FoldTool, params: unknown): Effect.Effect => + tool.init.pipe( + Effect.flatMap((contribution) => contribution.handler(params)), + Effect.provide(toolHandlerTestLayer), + ) + +/** Decode a real handler result/failure into the JSON shape accepted by the durable EventLog. */ +export const decodeToolResultJson = (result: unknown) => decodeJson(result) + +/** Persist real tool results, project the EventLog, and build the exact prompt used by session turns. */ +export const buildSessionPromptWithToolResults = (input: { + readonly userText: string + readonly toolResults: ReadonlyArray +}): Effect.Effect => + Effect.gen(function* () { + const eventLog = yield* EventLog + yield* eventLog + .append( + LogEntryInputs['user-message']({ + agentId: fixtureAgentId, + parentAgentId: null, + toolCallId: null, + messageId: messageIdAt(0), + message: { + role: 'user', + content: [{ type: 'text', text: input.userText }], + }, + }), + ) + .pipe(Effect.orDie) + yield* eventLog + .append( + LogEntryInputs['assistant-message']({ + agentId: fixtureAgentId, + parentAgentId: null, + toolCallId: null, + messageId: messageIdAt(1), + finish: null, + message: { + role: 'assistant', + content: input.toolResults.map((toolResult, index) => ({ + type: 'tool-call' as const, + id: toolCallIdAt(index), + name: toolResult.name, + params: toolResult.params, + providerExecuted: false, + options: { + [foldPartOptionsKey]: { + [providerToolCallIdKey]: toolResult.providerToolCallId ?? `call_test_${index + 1}`, + }, + }, + })), + }, + }), + ) + .pipe(Effect.orDie) + + for (const [index, toolResult] of input.toolResults.entries()) { + yield* eventLog + .append( + LogEntryInputs['tool-result']({ + agentId: fixtureAgentId, + parentAgentId: null, + toolCallId: toolCallIdAt(index), + messageId: messageIdAt(index + 2), + message: { + role: 'tool', + content: [ + { + type: 'tool-result', + id: toolCallIdAt(index), + name: toolResult.name, + result: toolResult.result, + isFailure: toolResult.isFailure, + }, + ], + }, + }), + ) + .pipe(Effect.orDie) + } + + const allEntries = yield* Stream.runCollect(eventLog.entries()).pipe(Effect.orDie) + const entries = allEntries.filter((entry): entry is ToolResultLogEntry => + Predicate.isTagged(entry, 'tool-result'), + ) + const prompt = yield* buildPrompt(messagesForAgent(allEntries, fixtureAgentId)).pipe(Effect.orDie) + return { prompt, entries } + }).pipe(Effect.provide(layerInMemoryEventLog)) + +export type ImageReadPromptFixture = { + readonly prompt: Prompt.Prompt + readonly readResult: typeof Schema.Json.Type + readonly sourceImageBase64: string +} + +/** Execute the production read tool, then feed its durable result through the session prompt builder. */ +export const makeImageReadPromptFixture: Effect.Effect = + makeTemporaryTestDirectory('fold-image-read-delivery-').pipe( + Effect.flatMap((directory) => + Effect.gen(function* () { + const sourceImage = makeDeterministicColorBandsPng() + yield* Effect.sync(() => writeFileSync(join(directory, 'visual-fixture.png'), sourceImage)) + + const result = yield* executeToolHandler(readTool({ cwd: directory }), { path: 'visual-fixture.png' }) + const readResult = yield* decodeJson(result) + const { prompt } = yield* buildSessionPromptWithToolResults({ + userText: imageIdentificationPrompt, + toolResults: [ + { + name: 'read', + params: { path: 'visual-fixture.png' }, + result: readResult, + isFailure: false, + providerToolCallId: 'call_image_read_delivery', + }, + ], + }) + + return { + prompt, + readResult, + sourceImageBase64: Buffer.from(sourceImage).toString('base64'), + } + }), + ), + ) + +/** + * Run the exact model-call shape used by AgentRuntime: session-built prompt, streaming, an explicitly + * empty active toolkit, and tool-call resolution disabled for runtime-owned settlement. + */ +export const runImageReadInference = (model: LanguageModel.Service) => + Effect.gen(function* () { + const fixture = yield* makeImageReadPromptFixture + const emptyToolkit = yield* Toolkit.empty + const parts = yield* Stream.runCollect( + model.streamText({ + prompt: fixture.prompt, + toolkit: emptyToolkit, + disableToolCallResolution: true, + }), + ) + + let text = '' + for (const part of parts) { + if (part.type === 'text-delta') text += part.delta + } + + return { ...fixture, text } + }) diff --git a/packages/fold-codex/test/ToolResultFormattingIntegration.vi.test.ts b/packages/fold-codex/test/ToolResultFormattingIntegration.vi.test.ts new file mode 100644 index 0000000..64769ed --- /dev/null +++ b/packages/fold-codex/test/ToolResultFormattingIntegration.vi.test.ts @@ -0,0 +1,167 @@ +/** + * RED integration coverage for model-facing built-in tool results. The fixture executes production + * handlers against real files/processes, persists their untouched values, projects the session prompt, + * and captures the JSON emitted by the stock OpenAI Responses provider. + */ +import { readFileSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' + +import { assert, it } from '@effect/vitest' +import { OpenAiClient, OpenAiLanguageModel } from '@humanlayer/effect-ai-openai' +import { bashTool, editTool, readTool, writeTool } from '@humanlayer/fold-agent' +import { Effect, Layer, Redacted, Schema } from 'effect' +import { LanguageModel } from 'effect/unstable/ai' +import { FetchHttpClient } from 'effect/unstable/http' + +import { + buildSessionPromptWithToolResults, + type CapturedFetchRequest, + decodeToolResultJson, + executeToolHandler, + makeCapturingFetch, + makeTemporaryTestDirectory, +} from './SessionModelPathTestHarness' + +const openAiResponse = { + id: 'resp_tool_result_formatting', + object: 'response', + created_at: 0, + model: 'gpt-test', + status: 'completed', + output: [], + metadata: null, + temperature: null, + top_p: null, + tools: [], + tool_choice: 'auto', + error: null, + incomplete_details: null, + instructions: null, + parallel_tool_calls: true, +} + +const CapturedResponsesRequest = Schema.Struct({ + input: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), +}) + +const decodeCapturedResponsesRequest = Schema.decodeUnknownSync(CapturedResponsesRequest) + +const outputStringsFrom = (body: string): ReadonlyArray => { + const request = decodeCapturedResponsesRequest(JSON.parse(body)) + return request.input.flatMap((item) => + item['type'] === 'function_call_output' && typeof item['output'] === 'string' ? [item['output']] : [], + ) +} + +const expectedModelText = [ + 'read alpha\nread beta\n', + 'bash success\n', + 'bash failure\n\n\nCommand exited with code 7', + 'Successfully wrote 16 bytes to nested/written.txt', + 'Successfully replaced 1 block(s) in editable.txt.', +] + +const expectedDurableResults: ReadonlyArray = [ + { _tag: 'text', text: 'read alpha\nread beta\n' }, + { _tag: 'text', text: 'bash success\n' }, + { _tag: 'failure', text: 'bash failure\n\n\nCommand exited with code 7' }, + { _tag: 'text', text: 'Successfully wrote 16 bytes to nested/written.txt' }, + { _tag: 'text', text: 'Successfully replaced 1 block(s) in editable.txt.' }, +] + +const makeActualBuiltInToolResults = Effect.gen(function* () { + const directory = yield* makeTemporaryTestDirectory('fold-tool-result-formatting-') + writeFileSync(join(directory, 'read-source.txt'), 'read alpha\nread beta\n') + writeFileSync(join(directory, 'editable.txt'), 'before edit\nkeep\n') + + const readResult = yield* executeToolHandler(readTool({ cwd: directory }), { path: 'read-source.txt' }) + const bashSuccessResult = yield* executeToolHandler(bashTool({ cwd: directory, spillDir: directory }), { + command: "printf 'bash success\\n'", + }) + const bashFailureResult = yield* executeToolHandler(bashTool({ cwd: directory, spillDir: directory }), { + command: "printf 'bash failure\\n'; exit 7", + }).pipe(Effect.flip) + const writeResult = yield* executeToolHandler(writeTool({ cwd: directory }), { + path: 'nested/written.txt', + content: 'written by tool\n', + }) + const editResult = yield* executeToolHandler(editTool({ cwd: directory }), { + path: 'editable.txt', + edits: [{ oldText: 'before edit', newText: 'after edit' }], + }) + + const rawResults = yield* Effect.all([ + decodeToolResultJson(readResult), + decodeToolResultJson(bashSuccessResult), + decodeToolResultJson(bashFailureResult), + decodeToolResultJson(writeResult), + decodeToolResultJson(editResult), + ]) + const names = ['read', 'bash', 'bash', 'write', 'edit'] + const params = [ + { path: 'read-source.txt' }, + { command: "printf 'bash success\\n'" }, + { command: "printf 'bash failure\\n'; exit 7" }, + { path: 'nested/written.txt', content: 'written by tool\n' }, + { path: 'editable.txt', edits: [{ oldText: 'before edit', newText: 'after edit' }] }, + ] + const { prompt, entries } = yield* buildSessionPromptWithToolResults({ + userText: 'Run the requested built-in operations.', + toolResults: rawResults.map((result, index) => ({ + name: names[index] ?? 'unexpected', + params: params[index] ?? {}, + result, + isFailure: index === 2, + })), + }) + return { directory, rawResults, prompt, entries } +}) + +it.live('keeps actual built-in handler values structured in the durable EventLog', () => + Effect.gen(function* () { + const { directory, entries, rawResults } = yield* makeActualBuiltInToolResults + + assert.deepStrictEqual([...rawResults], expectedDurableResults) + assert.deepStrictEqual( + entries.map((entry) => { + const part = entry.message.content[0] + if (part?.type !== 'tool-result') throw new Error('expected a durable tool-result part') + return part.result + }), + rawResults, + ) + assert.strictEqual(readFileSync(join(directory, 'nested/written.txt'), 'utf8'), 'written by tool\n') + assert.strictEqual(readFileSync(join(directory, 'editable.txt'), 'utf8'), 'after edit\nkeep\n') + }), +) + +it.live('RED: sends actual built-in tool results as plain Responses function outputs', () => + Effect.gen(function* () { + const { prompt } = yield* makeActualBuiltInToolResults + + const requests: Array = [] + const capturingFetch = makeCapturingFetch( + requests, + () => + new Response(JSON.stringify(openAiResponse), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), + ) + const httpLayer = FetchHttpClient.layer.pipe( + Layer.provide(Layer.succeed(FetchHttpClient.Fetch, capturingFetch)), + ) + const clientLayer = OpenAiClient.layer({ apiKey: Redacted.make('sk-test') }).pipe(Layer.provide(httpLayer)) + const modelLayer = OpenAiLanguageModel.model('gpt-test').pipe(Layer.provide(clientLayer)) + + yield* LanguageModel.generateText({ prompt }).pipe(Effect.provide(modelLayer)) + + assert.strictEqual(requests.length, 1) + const captured = requests[0] + if (captured === undefined) throw new Error('expected one captured OpenAI Responses request') + assert.strictEqual(captured.url, 'https://api.openai.com/v1/responses') + + // Intended model contract: expose each handler's inner text/output/message, never its JSON envelope. + assert.deepStrictEqual(outputStringsFrom(captured.body), expectedModelText) + }), +) diff --git a/packages/fold-core/package.json b/packages/fold-core/package.json index 2ade7a7..bea70ff 100644 --- a/packages/fold-core/package.json +++ b/packages/fold-core/package.json @@ -15,16 +15,14 @@ "test:watch": "bun vitest" }, "dependencies": { + "@humanlayer/effect-ai-anthropic": "workspace:*", + "@humanlayer/effect-ai-openai": "workspace:*", "@humanlayer/effect-branded-id": "workspace:*" }, "peerDependencies": { - "@effect/ai-anthropic": "catalog:", - "@effect/ai-openai": "catalog:", "effect": "catalog:" }, "devDependencies": { - "@effect/ai-anthropic": "catalog:", - "@effect/ai-openai": "catalog:", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@humanlayer/fold-vitest-config": "workspace:*", diff --git a/packages/fold-core/src/Api/Provisioning.ts b/packages/fold-core/src/Api/Provisioning.ts index 4742434..3a83ad0 100644 --- a/packages/fold-core/src/Api/Provisioning.ts +++ b/packages/fold-core/src/Api/Provisioning.ts @@ -16,8 +16,8 @@ * provider HTTP client releases when its dispatch returns instead of leaking for the session's * lifetime. */ -import { AnthropicClient, AnthropicLanguageModel } from '@effect/ai-anthropic' -import { OpenAiClient, OpenAiLanguageModel } from '@effect/ai-openai' +import { AnthropicClient, AnthropicLanguageModel } from '@humanlayer/effect-ai-anthropic' +import { OpenAiClient, OpenAiLanguageModel } from '@humanlayer/effect-ai-openai' import { Context, Effect, Layer, Match, Stream } from 'effect' import type { FileSystem, Scope } from 'effect' import { LanguageModel, Toolkit } from 'effect/unstable/ai' diff --git a/packages/fold-core/src/Compaction/CompactionLayer.ts b/packages/fold-core/src/Compaction/CompactionLayer.ts index 9df6dd0..71c6e70 100644 --- a/packages/fold-core/src/Compaction/CompactionLayer.ts +++ b/packages/fold-core/src/Compaction/CompactionLayer.ts @@ -7,8 +7,8 @@ * model - subagents therefore summarize with their own model, D21), and returns the durable entry * payload. The session facade provides this service session-wide; the loop owns appends. */ -import { AnthropicLanguageModel } from '@effect/ai-anthropic' -import { OpenAiLanguageModel } from '@effect/ai-openai' +import { AnthropicLanguageModel } from '@humanlayer/effect-ai-anthropic' +import { OpenAiLanguageModel } from '@humanlayer/effect-ai-openai' import { Effect, Predicate, Stream } from 'effect' import { LanguageModel, Prompt } from 'effect/unstable/ai' diff --git a/packages/fold-core/src/Model/ModelRequestSettings.ts b/packages/fold-core/src/Model/ModelRequestSettings.ts index 41c7fdb..f574db7 100644 --- a/packages/fold-core/src/Model/ModelRequestSettings.ts +++ b/packages/fold-core/src/Model/ModelRequestSettings.ts @@ -6,8 +6,8 @@ * the projected model id also binds the request `model` - so `thinking-change` and same-provider * `model-change` entries take effect on the very next turn without rebuilding any layer (D23). */ -import { AnthropicLanguageModel } from '@effect/ai-anthropic' -import { OpenAiLanguageModel } from '@effect/ai-openai' +import { AnthropicLanguageModel } from '@humanlayer/effect-ai-anthropic' +import { OpenAiLanguageModel } from '@humanlayer/effect-ai-openai' import { Data, Match, Context, Layer } from 'effect' import type { Effect } from 'effect' diff --git a/packages/fold-core/src/Model/RequestBuilder.ts b/packages/fold-core/src/Model/RequestBuilder.ts index 6699504..0a8500f 100644 --- a/packages/fold-core/src/Model/RequestBuilder.ts +++ b/packages/fold-core/src/Model/RequestBuilder.ts @@ -8,11 +8,11 @@ * metadata into history. The assistant tool-call params stay exactly as decoded from the persisted * assistant message, keeping already-sent prompt bytes stable across turns. */ -import { Effect, Match, Option, Schema } from 'effect' +import { Effect, Encoding, Match, Option, Schema } from 'effect' import { Prompt } from 'effect/unstable/ai' import type { ProjectedMessage } from '../Projection/Projection' -import { ToolResultImageBlock } from '../Tools/ToolResultContent' +import { ToolResultOutput } from '../Tools/ToolResultContent' const anthropicEphemeralCacheControl = { type: 'ephemeral' } as const @@ -34,9 +34,8 @@ const decodeSystemMessage = Schema.decodeUnknownEffect(Prompt.SystemMessage) const decodeUserMessage = Schema.decodeUnknownEffect(Prompt.UserMessage) const decodeAssistantMessage = Schema.decodeUnknownEffect(Prompt.AssistantMessage) const decodeToolMessage = Schema.decodeUnknownEffect(Prompt.ToolMessage) -const decodeJsonObject = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.Unknown)) const decodeFoldPartOptions = Schema.decodeUnknownOption(Schema.Struct({ [providerToolCallIdKey]: Schema.String })) -const decodeToolResultContent = Schema.decodeUnknownOption(Schema.Struct({ content: Schema.Array(Schema.Unknown) })) +const decodeToolResultOutput = Schema.decodeUnknownOption(ToolResultOutput) const decodeErrorFor = (projected: ProjectedMessage) => (cause: unknown) => new PromptDecodeError({ @@ -143,72 +142,39 @@ const markLatestUserSideCacheBreakpoint = (messages: ReadonlyArray } | null => { - const envelope = decodeToolResultContent(result) - const object = decodeJsonObject(result) - if (Option.isNone(envelope) || Option.isNone(object)) return null - - const images = envelope.value.content.filter(isImageBlock) - if (images.length === 0) return null - - return { - sanitized: { - ...object.value, - content: envelope.value.content.map((block: unknown) => - isImageBlock(block) ? { type: 'text', text: imageOmittedPlaceholder } : block, - ), - }, - images, - } -} - -/** - * Deliver image blocks from tool results as native user file parts (D3): the provider serializes - * custom tool results as JSON text (verified fact 1), so images inside tool_result would reach the - * model as base64 noise. The image block is replaced with placeholder text and re-sent as a user - * message file part immediately after the tool message - uniform across providers (fact 2). - */ -const liftImagesFromToolMessage = ( - message: Prompt.ToolMessage, -): { readonly message: Prompt.ToolMessage; readonly followUp: Prompt.UserMessage | null } => { - const imageParts: Array = [] - const content = message.content.map((part) => { - if (part.type !== 'tool-result') return part - - const split = splitImageBlocks(part.result) - if (split === null) return part - - for (const image of split.images) { - imageParts.push(Prompt.filePart({ mediaType: image.mimeType, data: image.data })) - } - return Prompt.toolResultPart({ ...part, result: split.sanitized }) - }) - - if (imageParts.length === 0) return { message, followUp: null } - - return { - message: Prompt.toolMessage({ content, options: message.options }), - followUp: Prompt.userMessage({ - content: [ - Prompt.textPart({ text: 'The following image content belongs to the preceding tool result:' }), - ...imageParts, - ], +/** Convert a durable canonical result to provider-neutral live Prompt content. */ +const prepareToolResult = (result: unknown): Effect.Effect => { + const decoded = decodeToolResultOutput(result) + if (Option.isNone(decoded)) return Effect.succeed(result) + + return Match.value(decoded.value).pipe( + Match.tagsExhaustive({ + text: ({ text }) => Effect.succeed(text), + failure: ({ text }) => Effect.succeed(text), + multipart: ({ content }) => + Effect.forEach(content, (part) => + Match.value(part).pipe( + Match.tagsExhaustive({ + 'text-part': ({ text }) => Effect.succeed(Prompt.textPart({ text })), + 'image-part': ({ data, mediaType, fileName }) => + Effect.fromResult(Encoding.decodeBase64(data)).pipe( + Effect.map((bytes) => Prompt.filePart({ data: bytes, mediaType, fileName })), + ), + }), + ), + ), }), - } + ) } +/** Prepare each canonical result while retaining the surrounding tool message. */ +const prepareToolMessage = (message: Prompt.ToolMessage): Effect.Effect => + Effect.forEach(message.content, (part): Effect.Effect => + part.type === 'tool-result' + ? prepareToolResult(part.result).pipe(Effect.map((result) => Prompt.toolResultPart({ ...part, result }))) + : Effect.succeed(part), + ).pipe(Effect.map((content) => Prompt.toolMessage({ content, options: message.options }))) + /** * Build the live Prompt for one model request from an agent's projected messages. * @@ -249,15 +215,11 @@ export const buildPrompt = ( 'tool-result': (result) => decodeToolMessage(result.message).pipe( Effect.mapError(decodeErrorFor(result)), - Effect.tap((decoded) => - Effect.sync(() => { - const { message, followUp } = liftImagesFromToolMessage( - restoreToolResultIds(decoded, providerIdsByFoldId), - ) - promptMessages.push(message) - if (followUp !== null) promptMessages.push(followUp) - }), + Effect.flatMap((decoded) => + prepareToolMessage(restoreToolResultIds(decoded, providerIdsByFoldId)), ), + Effect.mapError(decodeErrorFor(result)), + Effect.tap((message) => Effect.sync(() => promptMessages.push(message))), ), 'compaction-summary': (summary) => Effect.sync(() => { diff --git a/packages/fold-core/src/Skills/SkillTool.ts b/packages/fold-core/src/Skills/SkillTool.ts index 2afc60c..b1cc247 100644 --- a/packages/fold-core/src/Skills/SkillTool.ts +++ b/packages/fold-core/src/Skills/SkillTool.ts @@ -9,6 +9,7 @@ import { Effect } from 'effect' import { defineTool, type SessionToolContribution, type FoldTool } from '../Api/ToolDefinition' import { skillToolContract } from '../Tools/Contracts' +import { ToolResultFailure, ToolResultText } from '../Tools/ToolResultContent' import type { SkillMeta } from './Schemas' import { skillSourceFor, type SkillSourceService, type FoldSkills } from './SkillSource' @@ -93,10 +94,7 @@ export const skillTool = (source: FoldSkills): FoldTool => ({ }) /** The skill tool's model-facing failure payload (schema: message + availableSkills). */ -type SkillToolFailure = { - readonly message: string - readonly availableSkills: ReadonlyArray -} +type SkillToolFailure = ToolResultFailure /** * Build the skill tool over a resolved source (D20). The description advertises the session-start @@ -120,22 +118,28 @@ export const makeSkillTool = (input: MakeSkillToolInput): FoldTool => { const skill = yield* input.source.load(params.name).pipe( Effect.catchTags({ SkillNotFoundError: (error) => - Effect.fail({ - message: `Skill "${params.name}" not found. Available skills: ${ - error.availableSkills.length === 0 ? '(none)' : error.availableSkills.join(', ') - }`, - availableSkills: error.availableSkills, - }), + Effect.fail( + ToolResultFailure.make({ + text: `Skill "${params.name}" not found. Available skills: ${ + error.availableSkills.length === 0 ? '(none)' : error.availableSkills.join(', ') + }`, + details: { availableSkills: error.availableSkills }, + }), + ), SkillSourceError: (error) => - Effect.fail({ - message: `Skill source failed: ${error.message}`, - availableSkills: snapshotNames, - }), + Effect.fail( + ToolResultFailure.make({ + text: `Skill source failed: ${error.message}`, + details: { availableSkills: snapshotNames }, + }), + ), }), ) const content = renderSkillContent(skill) - return { content: refreshReport === null ? content : `${content}\n\n${refreshReport}` } + return ToolResultText.make({ + text: refreshReport === null ? content : `${content}\n\n${refreshReport}`, + }) }), }) } diff --git a/packages/fold-core/src/Subagents/SubagentTool.ts b/packages/fold-core/src/Subagents/SubagentTool.ts index f750498..d2c608f 100644 --- a/packages/fold-core/src/Subagents/SubagentTool.ts +++ b/packages/fold-core/src/Subagents/SubagentTool.ts @@ -13,6 +13,7 @@ import { Effect, Match } from 'effect' import { defineTool, type FoldTool } from '../Api/ToolDefinition' import type { SkillNotFoundError } from '../Skills/SkillSource' import { subagentToolContract } from '../Tools/Contracts' +import { ToolResultFailure, ToolResultText } from '../Tools/ToolResultContent' import { shortAgentId } from './AgentIdRef' import type { SubagentBusyError, SubagentNotFoundError, SubagentTypeNotInRosterError } from './Errors' import type { ForkAgentDefinition } from './ForkAgentDefinition' @@ -45,10 +46,7 @@ export const subagentRosterOf = (tool: FoldTool): ReadonlyArray -} +type SubagentToolFailure = ToolResultFailure /** Render one subagent result per the D21 template: id + turns header, result body, outcome note. */ export const renderSubagentResult = (result: SubagentResult): string => { @@ -88,38 +86,42 @@ const outcomeNoteFor = (result: SubagentResult): string | null => { // --- pure failure-payload formatters, invoked from catchTag/catchTags branches ----------------------- /** Payload for an out-of-roster (or unknown) agent type. */ -const rosterFailure = (error: SubagentTypeNotInRosterError): SubagentToolFailure => ({ - message: - `Agent type "${error.requested}" is not available to you. Available agent types: ` + - `${error.availableAgents.length === 0 ? '(none)' : error.availableAgents.join(', ')}.`, - availableAgents: error.availableAgents, -}) +const rosterFailure = (error: SubagentTypeNotInRosterError): SubagentToolFailure => + ToolResultFailure.make({ + text: + `Agent type "${error.requested}" is not available to you. Available agent types: ` + + `${error.availableAgents.length === 0 ? '(none)' : error.availableAgents.join(', ')}.`, + details: { availableAgents: error.availableAgents }, + }) /** Payload for a failed skill preload. */ -const skillFailure = (error: SkillNotFoundError, allowedAgents: ReadonlyArray): SubagentToolFailure => ({ - message: - `Skill "${error.name}" not found. Available skills: ` + - `${error.availableSkills.length === 0 ? '(none)' : error.availableSkills.join(', ')}.`, - availableAgents: allowedAgents, -}) +const skillFailure = (error: SkillNotFoundError, allowedAgents: ReadonlyArray): SubagentToolFailure => + ToolResultFailure.make({ + text: + `Skill "${error.name}" not found. Available skills: ` + + `${error.availableSkills.length === 0 ? '(none)' : error.availableSkills.join(', ')}.`, + details: { availableAgents: allowedAgents }, + }) /** Payload for a resume reference no agent uniquely matches: unknown, or an ambiguous short prefix. */ -const notFoundFailure = (error: SubagentNotFoundError, allowedAgents: ReadonlyArray): SubagentToolFailure => ({ - message: - error.candidates === undefined || error.candidates.length === 0 - ? `No subagent with agent_id "${error.requested}" exists in this session. Use the agent_id from a ` + - `previous subagent result, or dispatch a fresh agent with the agent parameter.` - : `agent_id "${error.requested}" is ambiguous: it matches ${error.candidates.length} agents ` + - `(${[...new Set(error.candidates)].join(', ')}). Provide more characters of the agent_id to ` + - `identify exactly one.`, - availableAgents: allowedAgents, -}) +const notFoundFailure = (error: SubagentNotFoundError, allowedAgents: ReadonlyArray): SubagentToolFailure => + ToolResultFailure.make({ + text: + error.candidates === undefined || error.candidates.length === 0 + ? `No subagent with agent_id "${error.requested}" exists in this session. Use the agent_id from a ` + + `previous subagent result, or dispatch a fresh agent with the agent parameter.` + : `agent_id "${error.requested}" is ambiguous: it matches ${error.candidates.length} agents ` + + `(${[...new Set(error.candidates)].join(', ')}). Provide more characters of the agent_id to ` + + `identify exactly one.`, + details: { availableAgents: allowedAgents }, + }) /** Payload for resuming an agent that is currently running. */ -const busyFailure = (error: SubagentBusyError, allowedAgents: ReadonlyArray): SubagentToolFailure => ({ - message: `Subagent ${shortAgentId(error.agentId)} is currently running and cannot be resumed until it finishes.`, - availableAgents: allowedAgents, -}) +const busyFailure = (error: SubagentBusyError, allowedAgents: ReadonlyArray): SubagentToolFailure => + ToolResultFailure.make({ + text: `Subagent ${shortAgentId(error.agentId)} is currently running and cannot be resumed until it finishes.`, + details: { availableAgents: allowedAgents }, + }) /** Render the roster + usage guidance appended to the contract description for one factory value. */ const rosterDescriptionSuffix = (agents: ReadonlyArray): string => { @@ -153,7 +155,12 @@ export const subagentTool = ( const subagents = yield* Subagents const command = yield* parseSubagentCommand(params).pipe( Effect.catchTag('InvalidSubagentCommandError', (error) => - Effect.fail({ message: error.message, availableAgents: allowedAgents }), + Effect.fail( + ToolResultFailure.make({ + text: error.message, + details: { availableAgents: allowedAgents }, + }), + ), ), ) @@ -172,7 +179,7 @@ export const subagentTool = ( SubagentTypeNotInRosterError: (error) => Effect.fail(rosterFailure(error)), SkillNotFoundError: (error) => Effect.fail(skillFailure(error, allowedAgents)), }), - Effect.map((result) => ({ content: renderSubagentResult(result) })), + Effect.map((result) => ToolResultText.make({ text: renderSubagentResult(result) })), ), fork: (forkCommand) => subagents @@ -186,7 +193,7 @@ export const subagentTool = ( Effect.catchTag('SkillNotFoundError', (error) => Effect.fail(skillFailure(error, allowedAgents)), ), - Effect.map((result) => ({ content: renderSubagentResult(result) })), + Effect.map((result) => ToolResultText.make({ text: renderSubagentResult(result) })), ), resume: (resumeCommand) => subagents @@ -202,7 +209,7 @@ export const subagentTool = ( SubagentBusyError: (error) => Effect.fail(busyFailure(error, allowedAgents)), SkillNotFoundError: (error) => Effect.fail(skillFailure(error, allowedAgents)), }), - Effect.map((result) => ({ content: renderSubagentResult(result) })), + Effect.map((result) => ToolResultText.make({ text: renderSubagentResult(result) })), ), }), ) diff --git a/packages/fold-core/src/Tools/Contracts.ts b/packages/fold-core/src/Tools/Contracts.ts index 6e8dfab..c4d9cae 100644 --- a/packages/fold-core/src/Tools/Contracts.ts +++ b/packages/fold-core/src/Tools/Contracts.ts @@ -7,7 +7,7 @@ */ import { Schema } from 'effect' -import { ToolResultContent } from './ToolResultContent' +import { ToolResultFailure, ToolResultSuccess, ToolResultText } from './ToolResultContent' import { defaultMaxLines, formatSize, defaultMaxBytes } from './Truncation' /** A tool's model-facing surface without a handler: spread into `defineTool` next to one. */ @@ -24,9 +24,7 @@ export type ToolContract< } /** Uniform expected-failure payload for built-in tools: one instructive, model-visible message. */ -export const ToolFailure = Schema.Struct({ - message: Schema.String, -}) +export const ToolFailure = ToolResultFailure export type ToolFailure = typeof ToolFailure.Type // --- read ------------------------------------------------------------------------------------------- @@ -47,9 +45,9 @@ export const readToolContract = { `Text output is limited to ${defaultMaxLines} lines or ${formatSize(defaultMaxBytes)}; ` + `use offset and limit to read further sections of large files.`, parameters: ReadParameters, - success: ToolResultContent, + success: ToolResultSuccess, failure: ToolFailure, -} satisfies ToolContract +} satisfies ToolContract // --- write ------------------------------------------------------------------------------------------ @@ -58,9 +56,7 @@ const WriteParameters = Schema.Struct({ content: Schema.String.annotate({ description: 'Content to write to the file' }), }) -const WriteSuccess = Schema.Struct({ - message: Schema.String, -}) +const WriteSuccess = ToolResultText /** Contract for the write tool (pi port): full overwrite with recursive parent creation. */ export const writeToolContract = { @@ -100,9 +96,7 @@ const EditParameters = Schema.Struct({ }), }) -const EditSuccess = Schema.Struct({ - message: Schema.String, -}) +const EditSuccess = ToolResultText /** Contract for the edit tool (pi port): batch exact-match replacements with normalization fallback. */ export const editToolContract = { @@ -123,9 +117,7 @@ const ApplyPatchParameters = Schema.Struct({ patch_text: Schema.String.annotate({ description: 'The full patch text to apply.' }), }) -const ApplyPatchSuccess = Schema.Struct({ - message: Schema.String, -}) +const ApplyPatchSuccess = ToolResultText const applyPatchDescription = `Apply a patch to create, update, delete, or move files. @@ -183,9 +175,9 @@ export const webFetchToolContract = { 'gif, webp, bmp) are returned as inline images. Use this for specific official docs pages, articles, ' + 'and other known sources. Responses over 5MB are rejected.', parameters: WebFetchParameters, - success: ToolResultContent, + success: ToolResultSuccess, failure: ToolFailure, -} satisfies ToolContract +} satisfies ToolContract // --- web_search ------------------------------------------------------------------------------------- @@ -212,9 +204,9 @@ export const webSearchToolContract = { 'LLM-optimized result summary with source URLs. Prefer official documentation and fetch high-value ' + 'results with web_fetch when more detail is needed.', parameters: WebSearchParameters, - success: Schema.String, + success: ToolResultText, failure: ToolFailure, -} satisfies ToolContract +} satisfies ToolContract // --- skill ------------------------------------------------------------------------------------------ @@ -225,14 +217,9 @@ const SkillParameters = Schema.Struct({ }), }) -const SkillSuccess = Schema.Struct({ - content: Schema.String, -}) +const SkillSuccess = ToolResultText -const SkillFailure = Schema.Struct({ - message: Schema.String, - availableSkills: Schema.Array(Schema.String), -}) +const SkillFailure = ToolResultFailure /** Contract for the skill tool (D20): progressive disclosure of skill content by name. */ export const skillToolContract = { @@ -279,14 +266,9 @@ const SubagentParameters = Schema.Struct({ }), }) -const SubagentSuccess = Schema.Struct({ - content: Schema.String, -}) +const SubagentSuccess = ToolResultText -const SubagentFailure = Schema.Struct({ - message: Schema.String, - availableAgents: Schema.Array(Schema.String), -}) +const SubagentFailure = ToolResultFailure /** Contract for the subagent tool (D21): dispatch, fork, and resume subagents on the session log. */ export const subagentToolContract = { diff --git a/packages/fold-core/src/Tools/ToolResultContent.ts b/packages/fold-core/src/Tools/ToolResultContent.ts index 240cfff..caf9f3c 100644 --- a/packages/fold-core/src/Tools/ToolResultContent.ts +++ b/packages/fold-core/src/Tools/ToolResultContent.ts @@ -1,37 +1,72 @@ /** - * This file defines the shared content-block convention for built-in tool results (D3/D18): a tool's - * success value is `{ content: [text | image, ...] }`, pi-style. Image blocks are the hard requirement - * of the read tool; RequestBuilder detects them at request-build time and delivers them as native user - * file parts (the provider cannot render images inside tool_result JSON - verified fact 1/2), replacing - * the in-result block with placeholder text. + * Provider-neutral tool results persisted by Fold. Handlers return these tagged values directly; + * RequestBuilder converts them to live Prompt text/file parts, and providers encode those parts in + * the native tool-result field. The durable image representation is validated base64. */ -import { Schema } from 'effect' +import { Match, Schema } from 'effect' -/** One plain-text block inside a tool result. */ -export const ToolResultTextBlock = Schema.Struct({ - type: Schema.Literal('text'), +/** One plain-text block inside multipart tool output. */ +export const ToolResultTextPart = Schema.TaggedStruct('text-part', { text: Schema.String, }) -export type ToolResultTextBlock = typeof ToolResultTextBlock.Type - -/** One inline image inside a tool result: base64 data plus its MIME type. */ -export const ToolResultImageBlock = Schema.Struct({ - type: Schema.Literal('image'), - /** Base64-encoded image bytes. */ - data: Schema.String, - mimeType: Schema.String, +export type ToolResultTextPart = typeof ToolResultTextPart.Type + +/** One inline image inside multipart tool output. */ +export const ToolResultImagePart = Schema.TaggedStruct('image-part', { + /** Base64-encoded image bytes without a data URL prefix. */ + data: Schema.String.check(Schema.isBase64()), + mediaType: Schema.String, + fileName: Schema.optionalKey(Schema.String), }) -export type ToolResultImageBlock = typeof ToolResultImageBlock.Type +export type ToolResultImagePart = typeof ToolResultImagePart.Type -/** The block union carried under a tool result's `content`. */ -export const ToolResultBlock = Schema.Union([ToolResultTextBlock, ToolResultImageBlock]) -export type ToolResultBlock = typeof ToolResultBlock.Type +/** Ordered multipart tool output. */ +export const ToolResultPart = Schema.Union([ToolResultTextPart, ToolResultImagePart]) +export type ToolResultPart = typeof ToolResultPart.Type -/** Success schema shape for tools that return content blocks (read; extensible to others). */ -export const ToolResultContent = Schema.Struct({ - content: Schema.Array(ToolResultBlock), +/** Successful plain-text tool output. */ +export const ToolResultText = Schema.TaggedStruct('text', { + text: Schema.String, }) -export type ToolResultContent = typeof ToolResultContent.Type +export type ToolResultText = typeof ToolResultText.Type + +/** Successful multipart tool output. */ +export const ToolResultMultipart = Schema.TaggedStruct('multipart', { + content: Schema.Array(ToolResultPart), +}) +export type ToolResultMultipart = typeof ToolResultMultipart.Type + +/** Expected tool failure with model-visible text and optional durable diagnostics. */ +export const ToolResultFailure = Schema.TaggedStruct('failure', { + text: Schema.String, + details: Schema.optionalKey(Schema.Json), +}) +export type ToolResultFailure = typeof ToolResultFailure.Type + +/** Every canonical result a Fold built-in persists. */ +export const ToolResultOutput = Schema.Union([ToolResultText, ToolResultMultipart, ToolResultFailure]) +export type ToolResultOutput = typeof ToolResultOutput.Type + +/** Successful canonical result. */ +export const ToolResultSuccess = Schema.Union([ToolResultText, ToolResultMultipart]) +export type ToolResultSuccess = typeof ToolResultSuccess.Type -/** Build a single-text-block tool result. */ -export const textResult = (text: string): ToolResultContent => ({ content: [{ type: 'text', text }] }) +/** Render canonical output for text-only consumers such as Riptide. */ +export const renderToolResultOutputText = (output: ToolResultOutput): string => + Match.value(output).pipe( + Match.tagsExhaustive({ + text: ({ text }) => text, + failure: ({ text }) => text, + multipart: ({ content }) => + content + .map((part) => + Match.value(part).pipe( + Match.tagsExhaustive({ + 'text-part': ({ text }) => text, + 'image-part': () => '[image]', + }), + ), + ) + .join('\n'), + }), + ) diff --git a/packages/fold-core/test/Model/EffectAnthropicToolResultEncodingRepro.vi.test.ts b/packages/fold-core/test/Model/EffectAnthropicToolResultEncodingRepro.vi.test.ts new file mode 100644 index 0000000..695faf7 --- /dev/null +++ b/packages/fold-core/test/Model/EffectAnthropicToolResultEncodingRepro.vi.test.ts @@ -0,0 +1,142 @@ +import { assert, it } from '@effect/vitest' +/** Regression coverage for patched @humanlayer/effect-ai-anthropic client tool-result encoding. */ +import { AnthropicClient, AnthropicLanguageModel } from '@humanlayer/effect-ai-anthropic' +import { Effect, Layer, Predicate, Redacted, Schema } from 'effect' +import { LanguageModel, Prompt } from 'effect/unstable/ai' +import { HttpClient, type HttpClientError, HttpClientResponse } from 'effect/unstable/http' + +const CapturedRequest = Schema.Struct({ + messages: Schema.Array( + Schema.Struct({ + role: Schema.String, + content: Schema.Array(Schema.Record(Schema.String, Schema.Unknown)), + }), + ), +}) + +it.effect('passes strings through and emits multipart client tool results in Effect 4.0.0-rc.112', () => + Effect.gen(function* () { + let requestBody: unknown = null + const preprocess: HttpClient.HttpClient.Preprocess = Effect.succeed + const httpClient = HttpClient.makeWith( + Effect.fnUntraced(function* (requestEffect) { + const request = yield* requestEffect + if (!Predicate.isTagged(request.body, 'Uint8Array')) return yield* Effect.die('expected request bytes') + requestBody = JSON.parse(new TextDecoder().decode(request.body.body)) + return HttpClientResponse.fromWeb( + request, + new Response( + JSON.stringify({ + id: 'msg_repro', + type: 'message', + role: 'assistant', + model: 'claude-test', + content: [{ type: 'text', text: 'ok' }], + stop_reason: 'end_turn', + stop_sequence: null, + usage: { + cache_creation: null, + cache_creation_input_tokens: null, + cache_read_input_tokens: null, + inference_geo: null, + input_tokens: 1, + output_tokens: 1, + service_tier: null, + }, + }), + { status: 200, headers: { 'content-type': 'application/json' } }, + ), + ) + }), + preprocess, + ) + const clientLayer = AnthropicClient.layer({ apiKey: Redacted.make('sk-test') }).pipe( + Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient)), + ) + const modelLayer = AnthropicLanguageModel.model('claude-test').pipe(Layer.provide(clientLayer)) + const stringResult = 'PLAIN_TEXT_SENTINEL\n' + const multipartResult = [ + Prompt.textPart({ text: 'IMAGE_TEXT_SENTINEL' }), + Prompt.filePart({ mediaType: 'image/png', data: new Uint8Array([137, 80, 78, 71]) }), + ] + + yield* LanguageModel.generateText({ + prompt: Prompt.fromMessages([ + Prompt.assistantMessage({ + content: [ + Prompt.toolCallPart({ + id: 'call_text', + name: 'text_tool', + params: {}, + providerExecuted: false, + }), + Prompt.toolCallPart({ + id: 'call_image', + name: 'image_tool', + params: {}, + providerExecuted: false, + }), + Prompt.toolCallPart({ + id: 'call_object', + name: 'object_tool', + params: {}, + providerExecuted: false, + }), + ], + }), + Prompt.toolMessage({ + content: [ + Prompt.toolResultPart({ + id: 'call_text', + name: 'text_tool', + result: stringResult, + isFailure: false, + providerExecuted: false, + }), + Prompt.toolResultPart({ + id: 'call_image', + name: 'image_tool', + result: multipartResult, + isFailure: false, + providerExecuted: false, + }), + Prompt.toolResultPart({ + id: 'call_object', + name: 'object_tool', + result: { answer: 42 }, + isFailure: false, + providerExecuted: false, + }), + ], + }), + ]), + }).pipe(Effect.provide(modelLayer)) + + const body = Schema.decodeUnknownSync(CapturedRequest)(requestBody) + const toolResults = body.messages.flatMap((message) => + message.content.filter( + (block) => block['type'] === 'tool_result' && Predicate.isString(block['tool_use_id']), + ), + ) + const textOutput = toolResults.find((block) => block['tool_use_id'] === 'call_text') + const imageOutput = toolResults.find((block) => block['tool_use_id'] === 'call_image') + const objectOutput = toolResults.find((block) => block['tool_use_id'] === 'call_object') + + assert.isDefined(textOutput) + assert.isDefined(imageOutput) + assert.isDefined(objectOutput) + assert.strictEqual(textOutput['content'], stringResult) + assert.strictEqual(objectOutput['content'], JSON.stringify({ answer: 42 })) + assert.deepStrictEqual(imageOutput['content'], [ + { type: 'text', text: 'IMAGE_TEXT_SENTINEL' }, + { + type: 'image', + source: { + type: 'base64', + media_type: 'image/png', + data: 'iVBORw==', + }, + }, + ]) + }), +) diff --git a/packages/fold-core/test/Model/ModelRequestSettings.vi.test.ts b/packages/fold-core/test/Model/ModelRequestSettings.vi.test.ts index 8234641..3daa5ba 100644 --- a/packages/fold-core/test/Model/ModelRequestSettings.vi.test.ts +++ b/packages/fold-core/test/Model/ModelRequestSettings.vi.test.ts @@ -1,6 +1,6 @@ -import { AnthropicLanguageModel } from '@effect/ai-anthropic' -import { OpenAiLanguageModel } from '@effect/ai-openai' import { expect, it } from '@effect/vitest' +import { AnthropicLanguageModel } from '@humanlayer/effect-ai-anthropic' +import { OpenAiLanguageModel } from '@humanlayer/effect-ai-openai' import { Predicate, Effect } from 'effect' import { diff --git a/packages/fold-core/test/Model/RequestBuilderImages.vi.test.ts b/packages/fold-core/test/Model/RequestBuilderImages.vi.test.ts index 3183b2d..6ffa322 100644 --- a/packages/fold-core/test/Model/RequestBuilderImages.vi.test.ts +++ b/packages/fold-core/test/Model/RequestBuilderImages.vi.test.ts @@ -1,12 +1,20 @@ import { expect, it } from '@effect/vitest' -import { Effect } from 'effect' +import { Effect, Encoding } from 'effect' import type { Prompt } from 'effect/unstable/ai' -import { buildPrompt, imageOmittedPlaceholder, MessageId, ToolCallId, type ProjectedMessage } from '../../src/index' +import { + buildPrompt, + MessageId, + ToolCallId, + ToolResultImagePart, + ToolResultMultipart, + ToolResultText, + ToolResultTextPart, + type ProjectedMessage, +} from '../../src/index' const messageId = MessageId.make('msg_aaaaaaaaaaaaaaaaaaaaaaaa') const toolCallId = ToolCallId.make('tool_call_aaaaaaaaaaaaaaaaaaaaaaaa') - const imageBase64 = 'aGVsbG8taW1hZ2UtYnl0ZXM=' const conversationWith = (result: unknown): ReadonlyArray => [ @@ -35,80 +43,79 @@ const conversationWith = (result: unknown): ReadonlyArray => [ }, ] -it.effect('lifts image blocks out of tool results into a user file-part message (D3)', () => +const onlyToolResult = (prompt: Prompt.Prompt): Prompt.ToolResultPart => { + const toolMessage = prompt.content.find((message): message is Prompt.ToolMessage => message.role === 'tool') + const toolResult = toolMessage?.content[0] + if (toolResult?.type !== 'tool-result') throw new Error('expected a tool-result part') + return toolResult +} + +it.effect('lowers multipart results to text and file parts inside the original tool result', () => Effect.gen(function* () { const prompt = yield* buildPrompt( - conversationWith({ - content: [ - { type: 'text', text: 'Read image file [image/png]' }, - { type: 'image', data: imageBase64, mimeType: 'image/png' }, - ], - }), + conversationWith( + ToolResultMultipart.make({ + content: [ + ToolResultTextPart.make({ text: 'Read image file [image/png]' }), + ToolResultImagePart.make({ data: imageBase64, mediaType: 'image/png' }), + ], + }), + ), ) - expect(prompt.content.map((message) => message.role)).toEqual(['assistant', 'tool', 'user']) - - const toolMessage = prompt.content.find((message): message is Prompt.ToolMessage => message.role === 'tool') - const toolResult = toolMessage?.content[0] - if (toolResult?.type !== 'tool-result') throw new Error('expected a tool-result part') - - // The image block inside the tool result was replaced by placeholder text. - const sanitized = JSON.stringify(toolResult.result) - expect(sanitized).not.toContain(imageBase64) - expect(sanitized).toContain(imageOmittedPlaceholder) - expect(sanitized).toContain('Read image file [image/png]') - - // The image itself follows as a native user-message file part. - const followUp = prompt.content[2] - if (followUp?.role !== 'user') throw new Error('expected a trailing user message') - const fileParts = followUp.content.filter((part) => part.type === 'file') - expect(fileParts).toHaveLength(1) - expect(fileParts[0]?.mediaType).toBe('image/png') - expect(fileParts[0]?.data).toBe(imageBase64) + expect(prompt.content.map((message) => message.role)).toEqual(['assistant', 'tool']) + const result = onlyToolResult(prompt).result + if (!Array.isArray(result)) throw new Error('expected multipart Prompt content') + expect(result).toHaveLength(2) + expect(result[0]).toMatchObject({ type: 'text', text: 'Read image file [image/png]' }) + const image = result[1] + if (image?.type !== 'file' || !(image.data instanceof Uint8Array)) throw new Error('expected image bytes') + expect(image.mediaType).toBe('image/png') + expect(Encoding.encodeBase64(image.data)).toBe(imageBase64) }), ) -it.effect('lifts multiple image blocks in result order', () => +it.effect('preserves multiple image parts in result order', () => Effect.gen(function* () { const prompt = yield* buildPrompt( - conversationWith({ - content: [ - { type: 'image', data: 'Zmlyc3Q=', mimeType: 'image/png' }, - { type: 'image', data: 'c2Vjb25k', mimeType: 'image/jpeg' }, - ], - }), + conversationWith( + ToolResultMultipart.make({ + content: [ + ToolResultImagePart.make({ data: 'Zmlyc3Q=', mediaType: 'image/png' }), + ToolResultImagePart.make({ data: 'c2Vjb25k', mediaType: 'image/jpeg' }), + ], + }), + ), ) - const followUp = prompt.content[2] - if (followUp?.role !== 'user') throw new Error('expected a trailing user message') - const fileParts = followUp.content.filter((part) => part.type === 'file') - expect(fileParts.map((part) => (typeof part.data === 'string' ? part.data : null))).toEqual([ - 'Zmlyc3Q=', - 'c2Vjb25k', + const result = onlyToolResult(prompt).result + if (!Array.isArray(result)) throw new Error('expected multipart Prompt content') + expect( + result.map((part) => + part.type === 'file' && part.data instanceof Uint8Array ? Encoding.encodeBase64(part.data) : null, + ), + ).toEqual(['Zmlyc3Q=', 'c2Vjb25k']) + expect(result.map((part) => (part.type === 'file' ? part.mediaType : null))).toEqual([ + 'image/png', + 'image/jpeg', ]) - expect(fileParts.map((part) => part.mediaType)).toEqual(['image/png', 'image/jpeg']) }), ) -it.effect('leaves text-only tool results untouched with no follow-up message', () => +it.effect('lowers canonical text results to exact strings', () => Effect.gen(function* () { - const result = { content: [{ type: 'text', text: 'plain text result' }] } - const prompt = yield* buildPrompt(conversationWith(result)) + const prompt = yield* buildPrompt(conversationWith(ToolResultText.make({ text: 'plain text result' }))) expect(prompt.content.map((message) => message.role)).toEqual(['assistant', 'tool']) - - const toolMessage = prompt.content[1] - if (toolMessage?.role !== 'tool') throw new Error('expected a tool message') - const toolResult = toolMessage.content[0] - if (toolResult?.type !== 'tool-result') throw new Error('expected a tool-result part') - expect(toolResult.result).toEqual(result) + expect(onlyToolResult(prompt).result).toBe('plain text result') }), ) -it.effect('ignores results that do not follow the content-block convention', () => +it.effect('leaves unknown custom results available for provider JSON fallback', () => Effect.gen(function* () { - const prompt = yield* buildPrompt(conversationWith({ echoed: 'hi' })) + const customResult = { echoed: 'hi' } + const prompt = yield* buildPrompt(conversationWith(customResult)) - expect(prompt.content.map((message) => message.role)).toEqual(['assistant', 'tool']) + expect(onlyToolResult(prompt).result).toEqual(customResult) }), ) diff --git a/packages/fold-core/test/Skills/SkillTool.vi.test.ts b/packages/fold-core/test/Skills/SkillTool.vi.test.ts index 688b0fb..d10807a 100644 --- a/packages/fold-core/test/Skills/SkillTool.vi.test.ts +++ b/packages/fold-core/test/Skills/SkillTool.vi.test.ts @@ -1,6 +1,6 @@ import * as NodeFileSystem from '@effect/platform-node/NodeFileSystem' import { describe, expect, it } from '@effect/vitest' -import { Effect, Layer, Ref } from 'effect' +import { Effect, Layer, Ref, Schema } from 'effect' import { AgentId, @@ -13,6 +13,7 @@ import { Subagents, ToolCallId, ToolEvents, + ToolResultText, ToolState, type SkillMeta, type SkillSourceService, @@ -37,9 +38,7 @@ const ambientServices = Layer.mergeAll( ) const skillContentOf = (result: unknown): string => { - if (typeof result === 'object' && result !== null && 'content' in result && typeof result.content === 'string') { - return result.content - } + if (Schema.is(ToolResultText)(result)) return result.text throw new Error('expected a skill tool result with string content') } @@ -73,7 +72,8 @@ describe('makeSkillTool', () => { const result = yield* runHandler(realized.handler({ name: 'commit-helper' })) expect(result).toEqual({ - content: '\nWrite conventional commits.\n', + _tag: 'text', + text: '\nWrite conventional commits.\n', }) }).pipe(Effect.provide(NodeFileSystem.layer)), ) @@ -87,8 +87,9 @@ describe('makeSkillTool', () => { const result = yield* runHandler(realized.handler({ name: 'missing' })).pipe(Effect.flip) expect(result).toEqual({ - message: 'Skill "missing" not found. Available skills: commit-helper, reviewer', - availableSkills: ['commit-helper', 'reviewer'], + _tag: 'failure', + text: 'Skill "missing" not found. Available skills: commit-helper, reviewer', + details: { availableSkills: ['commit-helper', 'reviewer'] }, }) }).pipe(Effect.provide(NodeFileSystem.layer)), ) diff --git a/packages/fold-core/test/Subagents/SubagentToolWire.vi.test.ts b/packages/fold-core/test/Subagents/SubagentToolWire.vi.test.ts index 8b8c301..61da766 100644 --- a/packages/fold-core/test/Subagents/SubagentToolWire.vi.test.ts +++ b/packages/fold-core/test/Subagents/SubagentToolWire.vi.test.ts @@ -8,7 +8,7 @@ import * as NodeFileSystem from '@effect/platform-node/NodeFileSystem' * unknown agent_id) come back as instructive tool failures the model can correct from. */ import { expect, it } from '@effect/vitest' -import { Predicate, Context, Effect, Layer } from 'effect' +import { Predicate, Context, Effect, Layer, Schema } from 'effect' import { AgentId, @@ -21,12 +21,57 @@ import { startSession, subagentTool, ToolCallId, + ToolResultText, type UserMessageLogEntry, } from '../../src/index' import { claudeActiveModel, gptActiveModel, scriptedModel } from '../Api/ApiTestHelpers' import { textTurn, toolCallTurn } from '../TestLayers/ScriptedLanguageModel' import { renderedDriveResult, subagentStartedEntries } from './DriveHarness' +it.effect('presents the rendered subagent result to the parent model as plain text', () => + Effect.gen(function* () { + const researcherScripted = yield* scriptedModel(claudeActiveModel, [textTurn('verified findings')]) + const researcher = defineSubagent({ + name: 'researcher', + description: 'explores', + model: researcherScripted.model, + }) + const rootScripted = yield* scriptedModel(gptActiveModel, [ + toolCallTurn([ + { + id: 'provider-call-1', + name: 'subagent', + params: { description: 'verify behavior', prompt: 'inspect it', agent: 'researcher' }, + }, + ]), + textTurn('parent synthesis'), + ]) + const session = yield* startSession({ + agent: defineAgent({ model: rootScripted.model, tools: [subagentTool([researcher])] }), + }) + + yield* session.send('go') + + const entries = yield* session.entries + const durableEntry = entries.find((entry) => Predicate.isTagged(entry, 'tool-result')) + if (!Predicate.isTagged(durableEntry, 'tool-result')) throw new Error('expected a durable subagent result') + const durablePart = durableEntry.message.content[0] + if (durablePart?.type !== 'tool-result' || !Schema.is(ToolResultText)(durablePart.result)) { + throw new Error('expected the durable tagged subagent text') + } + const expected = durablePart.result.text + const parentPrompts = yield* rootScripted.scripted.prompts + const followUpPrompt = parentPrompts[1] + if (followUpPrompt === undefined) throw new Error('expected the parent follow-up prompt') + const toolResult = followUpPrompt.content + .flatMap((message) => (message.role === 'tool' ? message.content : [])) + .find((part) => part.type === 'tool-result') + if (toolResult?.type !== 'tool-result') throw new Error('expected a subagent tool result') + + expect(toolResult.result).toBe(expected) + }).pipe(Effect.scoped, Effect.provide(NodeFileSystem.layer)), +) + it.effect('the model resumes a subagent through the tool wire by its SHORT id: full context, new call', () => Effect.gen(function* () { const researcherScripted = yield* scriptedModel(claudeActiveModel, [ diff --git a/packages/fold-core/test/TestLayers/ScriptedLanguageModel.ts b/packages/fold-core/test/TestLayers/ScriptedLanguageModel.ts index 822ceb7..c4f660c 100644 --- a/packages/fold-core/test/TestLayers/ScriptedLanguageModel.ts +++ b/packages/fold-core/test/TestLayers/ScriptedLanguageModel.ts @@ -9,8 +9,8 @@ * Turn helpers build provider-shaped encoded stream parts: `toolCallTurn` emits provider-style ids * (for example `provider-call-1`) so tests can prove fold's tool-call id rewriting. */ -import { AnthropicLanguageModel } from '@effect/ai-anthropic' -import { OpenAiLanguageModel } from '@effect/ai-openai' +import { AnthropicLanguageModel } from '@humanlayer/effect-ai-anthropic' +import { OpenAiLanguageModel } from '@humanlayer/effect-ai-openai' import { Predicate, Effect, Layer, Ref, Stream } from 'effect' import { AiError, LanguageModel, type Prompt, type Response } from 'effect/unstable/ai' diff --git a/packages/fold-opencode/package.json b/packages/fold-opencode/package.json index 14c1b33..e4680e1 100644 --- a/packages/fold-opencode/package.json +++ b/packages/fold-opencode/package.json @@ -15,17 +15,15 @@ "test:watch": "bun vitest" }, "dependencies": { + "@humanlayer/effect-ai-openai": "workspace:*", + "@humanlayer/effect-ai-openai-compat": "workspace:*", "@humanlayer/fold-core": "workspace:*" }, "peerDependencies": { - "@effect/ai-openai": "catalog:", - "@effect/ai-openai-compat": "catalog:", "@effect/platform-node": "catalog:", "effect": "catalog:" }, "devDependencies": { - "@effect/ai-openai": "catalog:", - "@effect/ai-openai-compat": "catalog:", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@humanlayer/fold-vitest-config": "workspace:*", diff --git a/packages/fold-opencode/src/OpenCodeModel.ts b/packages/fold-opencode/src/OpenCodeModel.ts index 6ce64bc..777ba2c 100644 --- a/packages/fold-opencode/src/OpenCodeModel.ts +++ b/packages/fold-opencode/src/OpenCodeModel.ts @@ -1,6 +1,12 @@ /** Fold model factory for models exposed through OpenCode Console / Zen. */ -import { OpenAiClient as ResponsesClient, OpenAiLanguageModel as ResponsesLanguageModel } from '@effect/ai-openai' -import { OpenAiClient as ChatClient, OpenAiLanguageModel as ChatLanguageModel } from '@effect/ai-openai-compat' +import { + OpenAiClient as ResponsesClient, + OpenAiLanguageModel as ResponsesLanguageModel, +} from '@humanlayer/effect-ai-openai' +import { + OpenAiClient as ChatClient, + OpenAiLanguageModel as ChatLanguageModel, +} from '@humanlayer/effect-ai-openai-compat' import { customModel, resolveOpenAiReasoning } from '@humanlayer/fold-core' import type { FoldModel, ReasoningLevel } from '@humanlayer/fold-core' import { Match, Context, Effect, Layer, Option, Schema } from 'effect' diff --git a/packages/fold-xai/package.json b/packages/fold-xai/package.json index a2f31a1..4dc5601 100644 --- a/packages/fold-xai/package.json +++ b/packages/fold-xai/package.json @@ -15,15 +15,14 @@ "test:watch": "bun vitest" }, "dependencies": { + "@humanlayer/effect-ai-openai-compat": "workspace:*", "@humanlayer/fold-core": "workspace:*" }, "peerDependencies": { - "@effect/ai-openai-compat": "catalog:", "@effect/platform-node": "catalog:", "effect": "catalog:" }, "devDependencies": { - "@effect/ai-openai-compat": "catalog:", "@effect/platform-node": "catalog:", "@effect/vitest": "catalog:", "@humanlayer/fold-vitest-config": "workspace:*", diff --git a/packages/fold-xai/src/XaiModel.ts b/packages/fold-xai/src/XaiModel.ts index 1d0e134..3f34b1c 100644 --- a/packages/fold-xai/src/XaiModel.ts +++ b/packages/fold-xai/src/XaiModel.ts @@ -1,11 +1,11 @@ +import * as NodeFileSystem from '@effect/platform-node/NodeFileSystem' /** FoldModel factory for xAI's OpenAI-compatible inference API authenticated with OAuth. */ -import { OpenAiClient, OpenAiLanguageModel } from '@effect/ai-openai-compat' +import { OpenAiClient, OpenAiLanguageModel } from '@humanlayer/effect-ai-openai-compat' import type { ChatCompletionChunk, CreateResponse200, CreateResponse200Sse, -} from '@effect/ai-openai-compat/OpenAiClient' -import * as NodeFileSystem from '@effect/platform-node/NodeFileSystem' +} from '@humanlayer/effect-ai-openai-compat/OpenAiClient' import { customModel, resolveOpenAiReasoning } from '@humanlayer/fold-core' import type { FoldModel, ReasoningLevel } from '@humanlayer/fold-core' import { Context, Effect, Layer, Option, Predicate, Schema, Stream } from 'effect' diff --git a/patches/@effect%2Fai-openai@4.0.0-rc.112.patch b/patches/@effect%2Fai-openai@4.0.0-rc.112.patch deleted file mode 100644 index 999bdf6..0000000 --- a/patches/@effect%2Fai-openai@4.0.0-rc.112.patch +++ /dev/null @@ -1,90 +0,0 @@ -diff --git a/src/OpenAiSchema.ts b/src/OpenAiSchema.ts ---- a/src/OpenAiSchema.ts -+++ b/src/OpenAiSchema.ts -@@ -1045,10 +1045,10 @@ - - const ResponseErrorEvent = Schema.Struct({ - type: Schema.Literal("error"), -- code: Schema.NullOr(Schema.String), -+ code: Schema.optionalKey(Schema.NullOr(Schema.String)), - message: Schema.String, -- param: Schema.NullOr(Schema.String), -- sequence_number: Schema.Int, -+ param: Schema.optionalKey(Schema.NullOr(Schema.String)), -+ sequence_number: Schema.optionalKey(Schema.Int), - status: Schema.optionalKey(Schema.Int) - }) - -@@ -1056,11 +1056,11 @@ - const NestedResponseErrorEvent = Schema.Struct({ - type: Schema.Literal("error"), - error: Schema.Struct({ -- code: Schema.NullOr(Schema.String), -+ code: Schema.optionalKey(Schema.NullOr(Schema.String)), - message: Schema.String, -- param: Schema.NullOr(Schema.String) -+ param: Schema.optionalKey(Schema.NullOr(Schema.String)) - }), -- sequence_number: Schema.Int, -+ sequence_number: Schema.optionalKey(Schema.Int), - status: Schema.optionalKey(Schema.Int) - }).pipe( - Schema.decodeTo( -diff --git a/dist/OpenAiSchema.js b/dist/OpenAiSchema.js ---- a/dist/OpenAiSchema.js -+++ b/dist/OpenAiSchema.js -@@ -696,21 +696,21 @@ - }); - const ResponseErrorEvent = /*#__PURE__*/Schema.Struct({ - type: /*#__PURE__*/Schema.Literal("error"), -- code: /*#__PURE__*/Schema.NullOr(Schema.String), -+ code: /*#__PURE__*/Schema.optionalKey(/*#__PURE__*/Schema.NullOr(Schema.String)), - message: Schema.String, -- param: /*#__PURE__*/Schema.NullOr(Schema.String), -- sequence_number: Schema.Int, -+ param: /*#__PURE__*/Schema.optionalKey(/*#__PURE__*/Schema.NullOr(Schema.String)), -+ sequence_number: /*#__PURE__*/Schema.optionalKey(Schema.Int), - status: /*#__PURE__*/Schema.optionalKey(Schema.Int) - }); - // OpenAI can nest stream error details under `error`. - const NestedResponseErrorEvent = /*#__PURE__*/Schema.Struct({ - type: Schema.Literal("error"), - error: Schema.Struct({ -- code: Schema.NullOr(Schema.String), -+ code: Schema.optionalKey(Schema.NullOr(Schema.String)), - message: Schema.String, -- param: Schema.NullOr(Schema.String) -+ param: Schema.optionalKey(Schema.NullOr(Schema.String)) - }), -- sequence_number: Schema.Int, -+ sequence_number: Schema.optionalKey(Schema.Int), - status: Schema.optionalKey(Schema.Int) - }).pipe(/*#__PURE__*/Schema.decodeTo(ResponseErrorEvent, /*#__PURE__*/SchemaTransformation.transform({ - decode: ({ -diff --git a/dist/Generated.d.ts b/dist/Generated.d.ts ---- a/dist/Generated.d.ts -+++ b/dist/Generated.d.ts -@@ -3322,17 +3322,17 @@ - export declare const ResponseErrorCode: Schema.Literals; - export type ResponseErrorEvent = { - readonly "type": "error"; -- readonly "code": string | null; -+ readonly "code"?: string | null | undefined; - readonly "message": string; -- readonly "param": string | null; -- readonly "sequence_number": number; -+ readonly "param"?: string | null | undefined; -+ readonly "sequence_number"?: number | undefined; - }; - export declare const ResponseErrorEvent: Schema.Struct<{ - readonly type: Schema.Literal<"error">; -- readonly code: Schema.Union; -+ readonly code: Schema.optionalKey>; - readonly message: Schema.String; -- readonly param: Schema.Union; -- readonly sequence_number: Schema.Number; -+ readonly param: Schema.optionalKey>; -+ readonly sequence_number: Schema.optionalKey; - }>; - export type ResponseFileSearchCallCompletedEvent = { - readonly "type": "response.file_search_call.completed"; diff --git a/scripts/build/packages.ts b/scripts/build/packages.ts index e15413e..2ab7c06 100644 --- a/scripts/build/packages.ts +++ b/scripts/build/packages.ts @@ -4,55 +4,101 @@ import { join } from 'node:path' import { libraries, root, json } from '../release/manifest' const version = process.argv.find((_, index, args) => args[index - 1] === '--version') ?? '0.0.0' +const providersOnly = process.argv.includes('--providers') +const quiet = process.argv.includes('--quiet') const { default: solidTransformPlugin } = await import( join(root, 'packages/fold-cli/node_modules/@opentui/solid/scripts/solid-plugin.js') ) for (const name of libraries) { + if (providersOnly && !name.startsWith('effect-ai-')) continue const dir = join(root, 'packages', name) const manifest = await json<{ name: string - exports: Record + exports: Record bin?: Record }>(join(dir, 'package.json')) - const exports = Object.values(manifest.exports) - const entries = exports - .map((value) => (typeof value === 'string' ? value : value.source)) - .filter((entry): entry is string => entry !== undefined) + const entries = new Set() + for (const value of Object.values(manifest.exports)) { + const entry = typeof value === 'string' ? value : (value?.source ?? value?.import) + if (entry === undefined || !/\.[cm]?[jt]sx?$/.test(entry)) continue + if (!entry.includes('*')) { + entries.add(entry) + continue + } + const glob = new Bun.Glob(entry.replace(/^\.\//, '')) + for await (const file of glob.scan({ cwd: dir, onlyFiles: true })) entries.add(`./${file}`) + } for (const entry of Object.values(manifest.bin ?? {})) { const sourceEntry = entry.replace(/^(?:\.\/)?dist\//, './src/').replace(/\.js$/, '.ts') - if (!entries.includes(sourceEntry)) entries.push(sourceEntry) + entries.add(sourceEntry) } + if (entries.size === 0) throw new Error(`No TypeScript entrypoints found for ${manifest.name}`) const outdir = join(dir, 'dist') await rm(outdir, { recursive: true, force: true }) await mkdir(outdir, { recursive: true }) - const define: Record = {} - if (name === 'fold-cli') define.FOLD_VERSION = JSON.stringify(version) - const result = await Bun.build({ - entrypoints: entries.map((entry) => join(dir, entry)), - outdir, - root: join(dir, 'src'), - target: 'node', - format: 'esm', - packages: name === 'fold-cli' ? 'bundle' : 'external', - external: name === 'fold-cli' ? ['@opentui/core', '@opentui/core/*'] : [], - sourcemap: 'external', - plugins: name === 'fold-cli' ? [solidTransformPlugin] : [], - define, - }) - if (!result.success) throw new AggregateError(result.logs, `Failed to build ${manifest.name}`) + const effectAiProvider = name.startsWith('effect-ai-') + if (!effectAiProvider) { + const define: Record = {} + if (name === 'fold-cli') define.FOLD_VERSION = JSON.stringify(version) + const result = await Bun.build({ + entrypoints: [...entries].map((entry) => join(dir, entry)), + outdir, + root: join(dir, 'src'), + target: 'node', + format: 'esm', + packages: name === 'fold-cli' ? 'bundle' : 'external', + external: name === 'fold-cli' ? ['@opentui/core', '@opentui/core/*'] : [], + sourcemap: 'external', + plugins: name === 'fold-cli' ? [solidTransformPlugin] : [], + define, + }) + if (!result.success) throw new AggregateError(result.logs, `Failed to build ${manifest.name}`) + } const buildConfig = join(dir, 'tsconfig.release.json') + const compilerOptions: Record = { + noEmit: false, + declaration: true, + emitDeclarationOnly: !effectAiProvider, + outDir: './dist', + rootDir: './src', + } + if (effectAiProvider) { + compilerOptions.module = 'NodeNext' + compilerOptions.moduleResolution = 'NodeNext' + compilerOptions.rewriteRelativeImportExtensions = true + compilerOptions.sourceMap = true + } await Bun.write( buildConfig, - `${JSON.stringify({ extends: './tsconfig.json', compilerOptions: { noEmit: false, declaration: true, emitDeclarationOnly: true, outDir: './dist', rootDir: './src' }, include: ['src'], exclude: ['test', 'examples', 'scripts'] }, null, 2)}\n`, + `${JSON.stringify( + { + extends: './tsconfig.json', + compilerOptions, + include: ['src'], + exclude: ['test', 'examples', 'scripts'], + }, + null, + 2, + )}\n`, ) const declaration = Bun.spawn(['bunx', 'tsc', '-p', buildConfig], { cwd: root, - stdout: 'inherit', - stderr: 'inherit', + stdout: quiet ? 'pipe' : 'inherit', + stderr: quiet ? 'pipe' : 'inherit', }) - const declarationExit = await declaration.exited + const [declarationOutput, declarationError, declarationExit] = await Promise.all([ + quiet ? new Response(declaration.stdout).text() : '', + quiet ? new Response(declaration.stderr).text() : '', + declaration.exited, + ]) await rm(buildConfig, { force: true }) - if (declarationExit !== 0) throw new Error(`Failed to emit declarations for ${manifest.name}`) + if (declarationExit !== 0) { + if (quiet) { + process.stdout.write(declarationOutput) + process.stderr.write(declarationError) + } + throw new Error(`Failed to emit declarations for ${manifest.name}`) + } console.log(`built ${manifest.name}`) } diff --git a/scripts/release/fixtures/provider-consumer.mjs b/scripts/release/fixtures/provider-consumer.mjs new file mode 100644 index 0000000..edab7c6 --- /dev/null +++ b/scripts/release/fixtures/provider-consumer.mjs @@ -0,0 +1,152 @@ +import { AnthropicClient, AnthropicLanguageModel } from '@humanlayer/effect-ai-anthropic' +import { OpenAiClient, OpenAiLanguageModel } from '@humanlayer/effect-ai-openai' +import { Effect, Layer, Predicate, Redacted } from 'effect' +import { LanguageModel, Prompt } from 'effect/unstable/ai' +import { FetchHttpClient, HttpClient, HttpClientResponse } from 'effect/unstable/http' + +const fail = (message) => { + throw new Error(message) +} + +const assertEqual = (actual, expected, description) => { + if (JSON.stringify(actual) !== JSON.stringify(expected)) + fail(`${description}\nexpected: ${JSON.stringify(expected)}\nreceived: ${JSON.stringify(actual)}`) +} + +const prompt = Prompt.fromMessages([ + Prompt.assistantMessage({ + content: [ + Prompt.toolCallPart({ id: 'call_text', name: 'text_tool', params: {}, providerExecuted: false }), + Prompt.toolCallPart({ id: 'call_image', name: 'image_tool', params: {}, providerExecuted: false }), + ], + }), + Prompt.toolMessage({ + content: [ + Prompt.toolResultPart({ + id: 'call_text', + name: 'text_tool', + result: 'PLAIN_TEXT_SENTINEL\n', + isFailure: false, + providerExecuted: false, + }), + Prompt.toolResultPart({ + id: 'call_image', + name: 'image_tool', + result: [ + Prompt.textPart({ text: 'IMAGE_TEXT_SENTINEL' }), + Prompt.filePart({ mediaType: 'image/png', data: 'iVBORw==' }), + ], + isFailure: false, + providerExecuted: false, + }), + ], + }), +]) + +const openAiResponse = { + id: 'resp_external_consumer_test', + object: 'response', + created_at: 0, + model: 'gpt-test', + status: 'completed', + output: [], + metadata: null, + temperature: null, + top_p: null, + tools: [], + tool_choice: 'auto', + error: null, + incomplete_details: null, + instructions: null, + parallel_tool_calls: true, +} + +const anthropicResponse = { + id: 'msg_external_consumer_test', + type: 'message', + role: 'assistant', + model: 'claude-test', + content: [{ type: 'text', text: 'ok' }], + stop_reason: 'end_turn', + stop_sequence: null, + usage: { + cache_creation: null, + cache_creation_input_tokens: null, + cache_read_input_tokens: null, + inference_geo: null, + input_tokens: 1, + output_tokens: 1, + service_tier: null, + }, +} + +const runOpenAiEncodingCheck = async () => { + const requests = [] + const fetch = async (input, init) => { + const request = input instanceof Request ? input : new Request(String(input), init) + requests.push(JSON.parse(await request.clone().text())) + return new Response(JSON.stringify(openAiResponse), { status: 200 }) + } + const httpLayer = FetchHttpClient.layer.pipe(Layer.provide(Layer.succeed(FetchHttpClient.Fetch, fetch))) + const modelLayer = OpenAiLanguageModel.model('gpt-test').pipe( + Layer.provide(OpenAiClient.layer({ apiKey: Redacted.make('sk-test') }).pipe(Layer.provide(httpLayer))), + ) + + await Effect.runPromise(LanguageModel.generateText({ prompt }).pipe(Effect.provide(modelLayer))) + + const outputs = requests[0]?.input.filter((item) => item.type === 'function_call_output') + const outputFor = (callId) => outputs?.find((item) => item.call_id === callId)?.output + assertEqual(outputFor('call_text'), 'PLAIN_TEXT_SENTINEL\n', 'OpenAI string tool result') + assertEqual( + outputFor('call_image'), + [ + { type: 'input_text', text: 'IMAGE_TEXT_SENTINEL' }, + { type: 'input_image', image_url: 'data:image/png;base64,iVBORw==', detail: 'auto' }, + ], + 'OpenAI multipart tool result', + ) +} + +const runAnthropicEncodingCheck = async () => { + let requestBody + const httpClient = HttpClient.makeWith( + Effect.fnUntraced(function* (requestEffect) { + const request = yield* requestEffect + if (!Predicate.isTagged(request.body, 'Uint8Array')) return yield* Effect.die('Expected request bytes') + requestBody = JSON.parse(new TextDecoder().decode(request.body.body)) + return HttpClientResponse.fromWeb( + request, + new Response(JSON.stringify(anthropicResponse), { + status: 200, + headers: { 'content-type': 'application/json' }, + }), + ) + }), + Effect.succeed, + ) + const clientLayer = AnthropicClient.layer({ apiKey: Redacted.make('sk-test') }).pipe( + Layer.provide(Layer.succeed(HttpClient.HttpClient, httpClient)), + ) + const modelLayer = AnthropicLanguageModel.model('claude-test').pipe(Layer.provide(clientLayer)) + + await Effect.runPromise(LanguageModel.generateText({ prompt }).pipe(Effect.provide(modelLayer))) + + const results = requestBody.messages.flatMap((message) => + message.content.filter((block) => block.type === 'tool_result'), + ) + const outputFor = (callId) => results.find((item) => item.tool_use_id === callId)?.content + assertEqual(outputFor('call_text'), 'PLAIN_TEXT_SENTINEL\n', 'Anthropic string tool result') + assertEqual( + outputFor('call_image'), + [ + { type: 'text', text: 'IMAGE_TEXT_SENTINEL' }, + { type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'iVBORw==' } }, + ], + 'Anthropic multipart tool result', + ) +} + +await import('@humanlayer/effect-ai-openai-compat/OpenAiClient') +await import('@humanlayer/fold-core') +await runOpenAiEncodingCheck() +await runAnthropicEncodingCheck() diff --git a/scripts/release/manifest.ts b/scripts/release/manifest.ts index 6cc92ec..476e29a 100644 --- a/scripts/release/manifest.ts +++ b/scripts/release/manifest.ts @@ -4,6 +4,9 @@ export const root = join(import.meta.dirname, '../..') export const stage = join(root, '.release') export const libraries = [ 'effect-branded-id', + 'effect-ai-openai', + 'effect-ai-anthropic', + 'effect-ai-openai-compat', 'fold-core', 'fold-codex', 'fold-opencode', diff --git a/scripts/release/prepare.ts b/scripts/release/prepare.ts index 3921f44..58bbf04 100644 --- a/scripts/release/prepare.ts +++ b/scripts/release/prepare.ts @@ -8,7 +8,7 @@ const version = parseArgs({ options: { version: { type: 'string' } } }).values.v if (!version?.match(/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/)) throw new Error('A valid --version is required') type DependencyMap = Record -type ExportValue = string | { source: string } +type ExportValue = string | { import?: string; source?: string } | null type PackageManifest = { [key: string]: unknown name?: string @@ -74,11 +74,15 @@ for (const packageDir of libraries) { dependencies(manifest) const rewrite = (value: string) => value.replace(/^\.\/src\//, './dist/').replace(/\.(tsx?|jsx?)$/, '.js') const dts = (value: string) => rewrite(value).replace(/\.js$/, '.d.ts') - const firstExport = Object.values(manifest.exports)[0] - const mainSource = typeof firstExport === 'string' ? firstExport : (firstExport?.source ?? './src/index.ts') + const sourcePath = (value: ExportValue) => (typeof value === 'string' ? value : (value?.source ?? value?.import)) + const isSourceModule = (value: string) => /^\.\/src\/.*\.(?:[cm]?[jt]sx?)$/.test(value) + const mainSource = sourcePath(manifest.exports['.']) + if (mainSource === undefined || !isSourceModule(mainSource)) + throw new Error(`${manifest.name} must provide a TypeScript root export`) for (const [key, value] of Object.entries(manifest.exports)) { - const sourcePath = typeof value === 'string' ? value : value.source - manifest.exports[key] = { types: dts(sourcePath), import: rewrite(sourcePath), default: rewrite(sourcePath) } + const source = sourcePath(value) + if (source === undefined || !isSourceModule(source)) continue + manifest.exports[key] = { types: dts(source), import: rewrite(source), default: rewrite(source) } } manifest.module = rewrite(mainSource) manifest.types = dts(mainSource) @@ -87,7 +91,15 @@ for (const packageDir of libraries) { await mkdir(dest, { recursive: true }) await cp(join(source, 'dist'), join(dest, 'dist'), { recursive: true }) for (const executable of new Set(Object.values(manifest.bin ?? {}))) await chmod(join(dest, executable), 0o755) - for (const file of ['README.md', 'LICENSE', 'NOTICE', 'LICENSE.opencode', 'ATTRIBUTION.md']) + for (const file of [ + 'README.md', + 'LICENSE', + 'NOTICE', + 'LICENSE.opencode', + 'ATTRIBUTION.md', + 'UPSTREAM.md', + 'UPSTREAM.sha256', + ]) if (await Bun.file(join(source, file)).exists()) await cp(join(source, file), join(dest, file)) if (!(await Bun.file(join(dest, 'LICENSE')).exists())) await cp(join(root, 'LICENSE'), join(dest, 'LICENSE')) await Bun.write(join(dest, 'package.json'), `${JSON.stringify(manifest, null, 2)}\n`) diff --git a/scripts/release/validate-manifest.ts b/scripts/release/validate-manifest.ts index a4d5c96..5b3f888 100644 --- a/scripts/release/validate-manifest.ts +++ b/scripts/release/validate-manifest.ts @@ -1,7 +1,216 @@ -import { stat } from 'node:fs/promises' +import { mkdir, mkdtemp, realpath, rm, stat, symlink } from 'node:fs/promises' +import { tmpdir } from 'node:os' import { join } from 'node:path' +import { pathToFileURL } from 'node:url' -import { json, libraries, stage, targetName, targets } from './manifest' +import { json, libraries, root, stage, targetName, targets } from './manifest' + +type ExportValue = string | { types?: string; import?: string; default?: string } | null + +const providerPackages = new Set([ + '@humanlayer/effect-ai-openai', + '@humanlayer/effect-ai-anthropic', + '@humanlayer/effect-ai-openai-compat', +]) + +const providerDependencies = new Map([ + ['@humanlayer/fold-core', ['@humanlayer/effect-ai-anthropic', '@humanlayer/effect-ai-openai']], + ['@humanlayer/fold-codex', ['@humanlayer/effect-ai-openai']], + ['@humanlayer/fold-opencode', ['@humanlayer/effect-ai-openai', '@humanlayer/effect-ai-openai-compat']], + ['@humanlayer/fold-xai', ['@humanlayer/effect-ai-openai-compat']], +]) + +const externalConsumerPackages = [ + 'effect-branded-id', + 'effect-ai-openai', + 'effect-ai-anthropic', + 'effect-ai-openai-compat', + 'fold-core', +] + +const exists = async (path: string) => { + try { + await stat(path) + return true + } catch { + return false + } +} + +const expandGlob = async (directory: string, pattern: string) => { + const matches = Array() + const glob = new Bun.Glob(pattern.replace(/^\.\//, '')) + for await (const file of glob.scan({ cwd: directory, onlyFiles: true })) matches.push(file) + return matches +} + +const assertNodeImport = async (packageName: string, entrypoint: string) => { + const expression = `await import(${JSON.stringify(pathToFileURL(entrypoint).href)})` + const process = Bun.spawn(['node', '--input-type=module', '--eval', expression], { + stdout: 'inherit', + stderr: 'inherit', + }) + if ((await process.exited) !== 0) throw new Error(`${packageName} does not execute with Node.js: ${entrypoint}`) +} + +const run = async (command: Array, cwd: string, captureOutput = false) => { + const child = Bun.spawn(command, { + cwd, + stdout: captureOutput ? 'pipe' : 'inherit', + stderr: 'inherit', + env: { ...process.env, COREPACK_ENABLE_DOWNLOAD_PROMPT: '0' }, + }) + const output = captureOutput ? await new Response(child.stdout).text() : '' + if ((await child.exited) !== 0) throw new Error(`Command failed: ${command.join(' ')}`) + return output +} + +type PackedArchive = { name: string; path: string } +type PackedPackage = { name: string; filename: string } + +const isPackedPackage = (value: unknown): value is PackedPackage => + typeof value === 'object' && + value !== null && + 'name' in value && + typeof value.name === 'string' && + 'filename' in value && + typeof value.filename === 'string' + +const pack = async (directory: string, outputDirectory: string): Promise => { + const output = await run(['npm', 'pack', '--json', '--pack-destination', outputDirectory], directory, true) + const packed: unknown = JSON.parse(output) + const artifact = Array.isArray(packed) + ? packed.find(isPackedPackage) + : typeof packed === 'object' && packed !== null + ? Object.values(packed).find(isPackedPackage) + : undefined + if (artifact === undefined) throw new Error(`npm pack did not produce an archive for ${directory}`) + return { name: artifact.name, path: join(outputDirectory, artifact.filename) } +} + +const validateExternalProviderConsumer = async ( + manager: 'npm' | 'pnpm', + archives: Array, + effectVersion: string, +) => { + const directory = await mkdtemp(join(tmpdir(), `fold-${manager}-provider-consumer-`)) + try { + const overrides = Object.fromEntries(archives.map((artifact) => [artifact.name, `file:${artifact.path}`])) + const manifest = { + name: `fold-${manager}-provider-consumer`, + private: true, + type: 'module', + packageManager: 'pnpm@11.25.0', + } + await Bun.write(join(directory, 'package.json'), `${JSON.stringify(manifest)}\n`) + if (manager === 'pnpm') + await Bun.write( + join(directory, 'pnpm-workspace.yaml'), + `overrides:\n${Object.entries(overrides) + .map(([name, range]) => ` ${JSON.stringify(name)}: ${JSON.stringify(range)}`) + .join('\n')}\n`, + ) + await Bun.write( + join(directory, 'provider-consumer.mjs'), + await Bun.file(join(root, 'scripts/release/fixtures/provider-consumer.mjs')).text(), + ) + const packages = [`effect@${effectVersion}`, ...archives.map((artifact) => artifact.path)] + const install = + manager === 'npm' + ? ['npm', 'install', '--ignore-scripts', '--no-package-lock', ...packages] + : [ + 'npm', + 'exec', + '--yes', + '--package=pnpm@11.25.0', + '--', + 'pnpm', + 'install', + '--ignore-scripts', + '--lockfile=false', + ...packages, + ] + await run(install, directory) + await run(['node', 'provider-consumer.mjs'], directory) + } finally { + await rm(directory, { recursive: true, force: true }) + } +} + +const validateExternalProviderConsumers = async () => { + const archivesDirectory = await mkdtemp(join(tmpdir(), 'fold-provider-archives-')) + try { + const archives = await Promise.all( + externalConsumerPackages.map((name) => pack(join(stage, 'packages', name), archivesDirectory)), + ) + const manifest = await json<{ peerDependencies: { effect: string } }>( + join(stage, 'packages/effect-ai-openai/package.json'), + ) + await validateExternalProviderConsumer('npm', archives, manifest.peerDependencies.effect) + await validateExternalProviderConsumer('pnpm', archives, manifest.peerDependencies.effect) + } finally { + await rm(archivesDirectory, { recursive: true, force: true }) + } +} + +const withEffectPeer = async (directory: string, effect: () => Promise) => { + const nodeModules = join(directory, 'node_modules') + const peer = join(nodeModules, 'effect') + await mkdir(nodeModules, { recursive: true }) + await symlink(await realpath(join(root, 'packages/effect-ai-openai/node_modules/effect')), peer) + try { + await effect() + } finally { + await rm(nodeModules, { recursive: true, force: true }) + } +} + +const validateProviderPackage = async (directory: string, name: string, exports: Record) => { + for (const file of [ + 'package.json', + 'README.md', + 'LICENSE', + 'UPSTREAM.md', + ...(name === '@humanlayer/effect-ai-openai-compat' ? ['UPSTREAM.sha256'] : []), + ]) + if (!(await exists(join(directory, file)))) throw new Error(`${name} is missing ${file}`) + if (await exists(join(directory, 'src'))) throw new Error(`${name} package payload must not contain source files`) + + if (exports['./package.json'] !== './package.json') throw new Error(`${name} must export package.json`) + for (const key of ['./internal/*', './index', './*/index']) + if (exports[key] !== null) throw new Error(`${name} must keep ${key} blocked`) + + const root = exports['.'] + const wildcard = exports['./*'] + if (root === null || typeof root === 'string' || wildcard === null || typeof wildcard === 'string') + throw new Error(`${name} must export root and wildcard ESM/declaration targets`) + for (const [key, value] of [ + ['.', root], + ['./*', wildcard], + ] as const) { + if (value.types === undefined || value.import === undefined || value.default === undefined) + throw new Error(`${name} ${key} must export types, import, and default targets`) + } + + const rootTypes = join(directory, root.types) + const rootImport = join(directory, root.import) + if (!(await exists(rootTypes))) throw new Error(`${name} root declaration does not exist: ${root.types}`) + if (!(await exists(rootImport))) throw new Error(`${name} root ESM does not exist: ${root.import}`) + + const typeFiles = new Set(await expandGlob(directory, wildcard.types)) + const runtimeFiles = await expandGlob(directory, wildcard.import) + if (typeFiles.size === 0 || runtimeFiles.length === 0) + throw new Error(`${name} wildcard export must contain runtime and declaration files`) + await withEffectPeer(directory, async () => { + await assertNodeImport(name, rootImport) + for (const runtimeFile of runtimeFiles) { + const declarationFile = runtimeFile.replace(/\.js$/, '.d.ts') + if (!typeFiles.has(declarationFile)) + throw new Error(`${name} is missing a declaration for wildcard runtime entrypoint ${runtimeFile}`) + await assertNodeImport(name, join(directory, runtimeFile)) + } + }) +} const expectedVersion = process.argv.find((_, index, args) => args[index - 1] === '--version') const manifests = [ @@ -18,7 +227,7 @@ for (const path of manifests) { dependencies?: Record peerDependencies?: Record optionalDependencies?: Record - exports?: unknown + exports?: Record bin?: Record }>(path) if (expectedVersion !== undefined && manifest.version !== expectedVersion) @@ -44,8 +253,21 @@ for (const path of manifests) { throw new Error(`${manifest.name} does not exactly pin ${name}`) } } + for (const provider of providerDependencies.get(manifest.name) ?? []) { + if (manifest.dependencies?.[provider] !== manifest.version) + throw new Error(`${manifest.name} must publish ${provider} as an exact normal dependency`) + if ( + manifest.peerDependencies?.[provider] !== undefined || + manifest.optionalDependencies?.[provider] !== undefined + ) + throw new Error(`${manifest.name} must not publish ${provider} as a peer or optional dependency`) + } if (manifest.exports && JSON.stringify(manifest.exports).includes('/src/')) throw new Error(`${manifest.name} exposes source files`) + if (providerPackages.has(manifest.name)) { + if (manifest.exports === undefined) throw new Error(`${manifest.name} is missing an export map`) + await validateProviderPackage(join(path, '..'), manifest.name, manifest.exports) + } if (manifest.name === '@humanlayer/fold-cli') { if (manifest.bin?.['fold-cli'] !== 'dist/cli.js' || manifest.bin?.foldcode !== 'dist/cli.js') throw new Error('@humanlayer/fold-cli must expose fold-cli and foldcode from the same built entrypoint') @@ -68,3 +290,5 @@ for (const path of manifests) { } console.log(`validated ${manifest.name}@${manifest.version}`) } + +await validateExternalProviderConsumers()