diff --git a/.github/api-breakage-allowlist.txt b/.github/api-breakage-allowlist.txt index e69de29b..f37477df 100644 --- a/.github/api-breakage-allowlist.txt +++ b/.github/api-breakage-allowlist.txt @@ -0,0 +1,29 @@ +API breakage: accessor Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.body.Get() has return type change from OpenAI.Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload? to OpenAI.Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload +API breakage: accessor Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.body.Set() has parameter 0 type change from OpenAI.Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload? to OpenAI.Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload +API breakage: constructor Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.init(body:) has parameter 0 type change from OpenAI.Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload? to OpenAI.Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload +API breakage: constructor Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.init(body:) has removed default argument from parameter 0 +API breakage: enumelement Components.Schemas.CreateTranscriptionRequest.stream has been added as a new enum case +API breakage: typealias Components.Schemas.AutoCodeInterpreterToolParam.ContainerMemoryLimit has been removed +API breakage: typealias Components.Schemas.ComputerCallOutputItemParam.ComputerCallSafetyCheckParam has been removed +API breakage: typealias Components.Schemas.ComputerCallOutputItemParam.FunctionCallItemStatus has been removed +API breakage: typealias Components.Schemas.ContainerAutoParam.ContainerMemoryLimit has been removed +API breakage: typealias Components.Schemas.CreateResponse.Value3Payload.ContextManagementParam has been removed +API breakage: typealias Components.Schemas.CreateResponse.Value3Payload.ConversationParam has been removed +API breakage: typealias Components.Schemas.CreateResponse.Value3Payload.IncludeEnum has been removed +API breakage: typealias Components.Schemas.EasyInputMessage.MessagePhase has been removed +API breakage: typealias Components.Schemas.FileSearchTool.Filters has been removed +API breakage: typealias Components.Schemas.FunctionCallOutputItemParam.FunctionCallItemStatus has been removed +API breakage: typealias Components.Schemas.FunctionShellCallItemParam.FunctionShellCallItemStatus has been removed +API breakage: typealias Components.Schemas.FunctionShellCallOutputItemParam.FunctionShellCallItemStatus has been removed +API breakage: typealias Components.Schemas.FunctionToolParam.EmptyModelParam has been removed +API breakage: typealias Components.Schemas.ImageGenTool.InputFidelity has been removed +API breakage: typealias Components.Schemas.InputImageContentParamAutoParam.DetailEnum has been removed +API breakage: typealias Components.Schemas.MCPListToolsTool.OpenAPIObjectContainer has been removed +API breakage: typealias Components.Schemas.OutputMessage.MessagePhase has been removed +API breakage: typealias Components.Schemas.Response.Value3Payload.Conversation2 has been removed +API breakage: typealias Components.Schemas.ResponseProperties.Reasoning has been removed +API breakage: typealias Components.Schemas.ToolSearchCallItemParam.FunctionCallItemStatus has been removed +API breakage: typealias Components.Schemas.ToolSearchOutputItemParam.FunctionCallItemStatus has been removed +API breakage: typealias Components.Schemas.ToolSearchToolParam.EmptyModelParam has been removed +API breakage: typealias Components.Schemas.WebSearchPreviewTool.ApproximateLocation has been removed +API breakage: var Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.body has declared type change from OpenAI.Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload? to OpenAI.Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload diff --git a/.github/workflows/generation.yml b/.github/workflows/generation.yml new file mode 100644 index 00000000..607eba85 --- /dev/null +++ b/.github/workflows/generation.yml @@ -0,0 +1,48 @@ +# Regenerates Components.swift with `make generate` and fails when the committed file differs, so the +# generated schemas can never drift from what the pipeline in the repository produces. + +name: Generation + +on: + push: + branches: [ "main" ] + pull_request: + branches: [ "main" ] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + regenerate: + name: Components.swift matches make generate + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-python@v7 + with: + python-version: "3.12" + - name: Toolchain + id: toolchain + run: | + swift --version + echo "generator=$(make -s generator-version)" >> "$GITHUB_OUTPUT" + echo "swift=$(swift --version 2>&1 | head -n 1 | tr -c 'A-Za-z0-9.\n' '-')" >> "$GITHUB_OUTPUT" + - name: Cache the built generator + uses: actions/cache@v6 + with: + path: .build/openapi-generator/swift-openapi-generator-${{ steps.toolchain.outputs.generator }} + key: swift-openapi-generator-${{ steps.toolchain.outputs.generator }}-${{ steps.toolchain.outputs.swift }} + - name: Regenerate + run: make generate + - name: Committed file must match the pipeline output + run: | + if ! git diff --exit-code --stat -- Sources/OpenAI/Public/Schemas/Generated/Components.swift; then + echo "::error::Components.swift is out of date. Run 'make generate' and commit the result." + exit 1 + fi + echo "Components.swift matches make generate." diff --git a/.github/workflows/swift.yml b/.github/workflows/swift.yml index 2aab7a33..7e015856 100644 --- a/.github/workflows/swift.yml +++ b/.github/workflows/swift.yml @@ -8,6 +8,7 @@ on: branches: [ "main" ] pull_request: branches: [ "main" ] + workflow_dispatch: permissions: contents: read diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a5d3f8e..21193a3f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,11 @@ Compatibility promise: the public API is additive-only. Anything `public` is dep - CI: the *Swift Build* workflow now builds and tests on Linux with Swift 5.10, 6.0 and 6.3 containers, tests on macOS and the iOS Simulator, and builds for tvOS, watchOS and visionOS with Xcode. Tests written with Swift Testing only exist on toolchains that ship it (Swift 6); the XCTest suite runs everywhere. - CONTRIBUTING.md: API stability policy, including how new endpoint groups are added as namespaces and how generated `Components.Schemas` types are treated. - This changelog. +- CI: a *Generation* workflow runs `make generate` and fails when the committed `Components.swift` differs from the pipeline's output. + +### Changed +- Code generation no longer needs a private fork of Swift OpenAPI Generator. `make generate` clones and builds the stock generator (1.13.1) under `.build/`, and two new scripts replace the fork's patches: `Scripts/transform_openapi.py` collapses OpenAI's `anyOf: [X, {type: 'null'}]` nullability into optional properties and records discriminator wire values, and `Scripts/postprocess_components.py` applies them to the generated Swift and adds the fallback for the `message` value shared by `InputMessage` and `OutputMessage`. `Scripts/fix_recursive_reference.py` now handles any number of `$recursiveRef` occurrences. +- Regenerated `Components.Schemas` with that pipeline from the unchanged vendored spec. Generated-type changes, all listed in `.github/api-breakage-allowlist.txt`: 23 nested typealiases that were artifacts of the fork's nullable handling are gone (for example `OutputMessage.MessagePhase` and `CreateResponse.Value3Payload.IncludeEnum`; the top-level `Components.Schemas` types they aliased are unchanged), `CreateTranscriptionRequest.ChunkingStrategyPayload.body` is no longer optional, and `CreateTranscriptionRequest` gained a `stream` part. Decoding improvements: `ItemResource` accepts input messages, `InputItem` accepts `item_reference`, and nested unions such as `WebSearchToolCall.action` decode by wire value. ### Fixed - Build warning in `ModelResponseEventsStreamInterpreter` when logging a failed stream event decode in debug builds. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3b8f0769..2861c0a0 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -121,10 +121,11 @@ uses handwritten `CreateModelResponseQuery`, `ResponseObject`, and `ResponseStreamEvent` types, while their supporting schemas come from `Components.Schemas`. -The workflow is automated by [`make generate`](Makefile). The Makefile is the -source of truth for prerequisites and the exact commands; in particular, it -documents the required sibling checkout of the project's Swift OpenAPI Generator -fork and the generator changes that fork must contain. +The workflow is automated by [`make generate`](Makefile). It needs a Swift +toolchain, `python3` with `venv`, and network access on the first run. No fork +of the generator and no sibling checkout are required: the Makefile clones and +builds the pinned Swift OpenAPI Generator release under `.build/` and installs +the Python dependency (PyYAML) into a virtualenv there. Before running generation, update [`openapi-generator-config.yaml`](openapi-generator-config.yaml) with every path @@ -136,17 +137,25 @@ make generate The command: -1. prepares a generator-compatible copy of `openapi.yaml` under `.build/`; -2. applies the narrowly scoped workarounds documented in [`Scripts/`](Scripts/); -3. runs Swift OpenAPI Generator with the repository's configuration; and -4. extracts the generated `Components` enum into - `Sources/OpenAI/Public/Schemas/Generated/Components.swift` while preserving - that file's imports and header. - -The source specification is not modified during this process. The final -preparation diff is written to `.build/openapi-generator/openapi.patch`; review -it along with the generated Swift diff. Build the package and run the relevant -tests before submitting the change. +1. applies the conditional, line-based spec fixes in [`Scripts/`](Scripts/) + (`prepare_openapi.py`, `remove_required_properties.py`) and writes their diff + to `.build/openapi-generator/openapi.patch`; +2. runs `Scripts/transform_openapi.py`, which collapses OpenAI's + `anyOf: [X, {type: 'null'}]` nullability into optional properties (the + generator does not support that form, see apple/swift-openapi-generator#906) + and records the wire values of every discriminated union, because the spec's + discriminators have no `mapping` (openai/openai-openapi#542); +3. runs Swift OpenAPI Generator (types only) with the repository's configuration; +4. runs `Scripts/postprocess_components.py`, which re-wraps the generated schemas + under the existing header of `Components.swift`, appends the wire values to + each union's decoder, and adds a fallback for the one value that names two + schemas (`message` in `Item` and `ItemResource`). + +Review `.build/openapi-generator/openapi.patch` and the generated Swift diff, run +`swift package diagnose-api-breaking-changes` against the latest tag (every +regeneration is a public API change, see *API stability*), build the package and +run the tests. The `Generation` workflow in CI runs `make generate` and fails +when the committed `Components.swift` does not match the pipeline's output. Do not edit `Components.swift` by hand. It is deliberately replaceable output, so a later generation would discard such edits. diff --git a/Makefile b/Makefile index 3da5f244..009aa352 100644 --- a/Makefile +++ b/Makefile @@ -1,59 +1,54 @@ -# Requires a local fork of swift-openapi-generator to be checked out as a -# sibling directory named `swift-openapi-generator` (i.e. ../swift-openapi-generator). -# See https://github.com/apple/swift-openapi-generator for the upstream repo. +# Regenerates Sources/OpenAI/Public/Schemas/Generated/Components.swift from openapi.yaml. # -# The fork must include these changes, which are not available in the official -# generator at the time of writing: +# No fork of Swift OpenAPI Generator and no sibling checkout are required. The pinned generator release is +# cloned and built under .build/, and the Python dependency (PyYAML) is installed into a virtualenv there. +# Prerequisites: a Swift toolchain, python3 with venv, and network access on the first run. # -# - Handle OpenAPI 3.1 nullable schemas expressed as -# `anyOf: [, { type: null }]`. The generator must ignore the null -# branch while assigning the Swift type, then make the resulting type -# optional. Without this change, nullable properties are unsupported or are -# generated as an anyOf wrapper instead of the expected optional Swift type. +# Pipeline (details in CONTRIBUTING.md, "Implementing using Code Generation"): +# 1. Scripts/prepare_openapi.py conditional, line-based spec fixes (each script documents its removal +# condition); the combined diff is written to .build/openapi-generator/openapi.patch +# 2. Scripts/remove_required_properties.py `required` entries the live API does not honour (see below) +# 3. Scripts/transform_openapi.py nullable `anyOf` -> optional properties; discriminator wire values recorded +# (replaces the patches that used to live in a private generator fork) +# 4. swift-openapi-generator types only, paths and schemas from openapi-generator-config.yaml +# 5. Scripts/postprocess_components.py re-wraps the output under the existing header, appends the wire values, +# adds the collision fallbacks -> Components.swift # -# - When a oneOf discriminator has no explicit mapping, also match the string -# enum values declared by the referenced schemas' discriminator property. -# The OpenAI spec uses runtime values such as `input_text`, which do not match -# schema names such as `InputTextContent`; without this change, decoding a -# valid response throws unknownOneOfDiscriminator. See -# https://github.com/openai/openai-openapi/issues/542 for the spec issue. -# -# - When inferred discriminator values collide across multiple oneOf schemas, -# fall back to structural decoding for the colliding value instead of -# generating duplicate switch patterns. The OpenAI spec uses `message` for -# both InputMessage and OutputMessage, so the discriminator alone cannot -# select the correct schema. -# -# Expected diagnostic: -# The generator warns that `InputMessageResource/value2` requires `type` even -# though that property is declared by the sibling `InputMessage` schema in the -# same `allOf`. JSON Schema applies both members to the same object, while the -# generator validates each generated allOf payload independently. The property -# remains available through the generated `InputMessage` payload, so this -# warning is intentionally ignored. -GENERATOR_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST))))/../swift-openapi-generator -PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST)))) -TYPES_SWIFT := $(GENERATOR_DIR)/Types.swift -COMPONENTS_SWIFT := $(PROJECT_DIR)/Sources/OpenAI/Public/Schemas/Generated/Components.swift -PREPARED_OPENAPI := $(PROJECT_DIR)/.build/openapi-generator/openapi.yaml -OPENAPI_DIFF := $(PROJECT_DIR)/.build/openapi-generator/openapi.patch +# Expected generator diagnostics: "A property name only appears in the required list, but not in the properties +# map" for InputMessageResource/value2/type and Response/value3/{metadata, model, temperature, tool_choice, tools, +# top_p}. Those properties are declared by a sibling allOf member; the generator validates each member alone and +# the properties remain available through the sibling payload. Harmless. + +PROJECT_DIR := $(shell dirname $(abspath $(lastword $(MAKEFILE_LIST)))) +BUILD_DIR := $(PROJECT_DIR)/.build/openapi-generator + +GENERATOR_VERSION := 1.13.1 +GENERATOR_REPO := https://github.com/apple/swift-openapi-generator +GENERATOR_DIR := $(BUILD_DIR)/swift-openapi-generator-$(GENERATOR_VERSION) +# Override on the command line to use an already built generator: make generate GENERATOR_BIN=/path/to/binary +GENERATOR_BIN ?= $(GENERATOR_DIR)/.build/release/swift-openapi-generator + +VENV := $(BUILD_DIR)/venv +PYTHON := $(VENV)/bin/python + +SPEC := $(PROJECT_DIR)/openapi.yaml +CONFIG := $(PROJECT_DIR)/openapi-generator-config.yaml +COMPONENTS_SWIFT := $(PROJECT_DIR)/Sources/OpenAI/Public/Schemas/Generated/Components.swift +PREPARED_OPENAPI := $(BUILD_DIR)/openapi.prepared.yaml +TRANSFORMED_OPENAPI := $(BUILD_DIR)/openapi.transformed.yaml +DISCRIMINATORS := $(BUILD_DIR)/discriminators.json +OPENAPI_DIFF := $(BUILD_DIR)/openapi.patch +GENERATED_DIR := $(BUILD_DIR)/generated -.PHONY: generate -generate: - # Prepare a working copy with conditional, documented upstream-spec fixes. - # See the scripts called by prepare_openapi.py for each error and its fix. - python3 -B "$(PROJECT_DIR)/Scripts/prepare_openapi.py" \ - "$(PROJECT_DIR)/openapi.yaml" \ - "$(PREPARED_OPENAPI)" - # The LocalShellToolCallOutput, MCP approval response, and response audio - # event removals are required-list entries without matching schema properties. - # They otherwise produce swift-openapi-generator warnings that the names are - # likely typos and will be skipped. - # - # WebSearchActionSearch/query is different: the property is declared, but the - # live API can omit the deprecated singular query and return queries instead. - # It must be optional so valid web-search response items decode successfully. - python3 -B "$(PROJECT_DIR)/Scripts/remove_required_properties.py" \ +.PHONY: generate generator-version clean-generation + +generate: $(PYTHON) $(GENERATOR_BIN) + $(PYTHON) -B "$(PROJECT_DIR)/Scripts/prepare_openapi.py" "$(SPEC)" "$(PREPARED_OPENAPI)" + # LocalShellToolCallOutput, the MCP approval responses and the response audio events list properties as + # required that they never declare; the generator would otherwise warn and skip them. + # WebSearchActionSearch/query is declared but no longer sent by the live API (fixed upstream in July 2026, + # openai/openai-openapi#544); drop this entry when the vendored spec is updated past that fix. + $(PYTHON) -B "$(PROJECT_DIR)/Scripts/remove_required_properties.py" \ "$(PREPARED_OPENAPI)" \ "$(PREPARED_OPENAPI)" \ --remove-required "LocalShellToolCallOutput" "call_id" \ @@ -63,11 +58,26 @@ generate: --remove-required "ResponseAudioTranscriptDeltaEvent" "response_id" \ --remove-required "ResponseAudioTranscriptDoneEvent" "response_id" \ --remove-required "WebSearchActionSearch" "query" \ - --diff-source "$(PROJECT_DIR)/openapi.yaml" \ + --diff-source "$(SPEC)" \ --diff-output "$(OPENAPI_DIFF)" - cd "$(GENERATOR_DIR)" && swift run swift-openapi-generator generate \ - --config "$(PROJECT_DIR)/openapi-generator-config.yaml" \ - "$(PREPARED_OPENAPI)" - python3 -B "$(PROJECT_DIR)/Scripts/extract_components.py" \ - "$(TYPES_SWIFT)" \ - "$(COMPONENTS_SWIFT)" + $(PYTHON) -B "$(PROJECT_DIR)/Scripts/transform_openapi.py" "$(PREPARED_OPENAPI)" "$(TRANSFORMED_OPENAPI)" "$(DISCRIMINATORS)" + rm -rf "$(GENERATED_DIR)" && mkdir -p "$(GENERATED_DIR)" + "$(GENERATOR_BIN)" generate --config "$(CONFIG)" --output-directory "$(GENERATED_DIR)" "$(TRANSFORMED_OPENAPI)" + $(PYTHON) -B "$(PROJECT_DIR)/Scripts/postprocess_components.py" "$(GENERATED_DIR)/Types+Components+Schemas.swift" "$(DISCRIMINATORS)" "$(COMPONENTS_SWIFT)" + +$(PYTHON): $(PROJECT_DIR)/Scripts/requirements.txt + python3 -m venv "$(VENV)" + "$(PYTHON)" -m pip install --quiet --disable-pip-version-check -r "$(PROJECT_DIR)/Scripts/requirements.txt" + touch "$(PYTHON)" + +$(GENERATOR_DIR)/.build/release/swift-openapi-generator: + rm -rf "$(GENERATOR_DIR)" + git clone --quiet --depth 1 --branch "$(GENERATOR_VERSION)" "$(GENERATOR_REPO)" "$(GENERATOR_DIR)" + cd "$(GENERATOR_DIR)" && swift build -c release --product swift-openapi-generator + +# Used by the Generation workflow to key its cache of the built generator. +generator-version: + @echo $(GENERATOR_VERSION) + +clean-generation: + rm -rf "$(BUILD_DIR)" diff --git a/Scripts/extract_components.py b/Scripts/extract_components.py deleted file mode 100644 index e601384b..00000000 --- a/Scripts/extract_components.py +++ /dev/null @@ -1,102 +0,0 @@ -#!/usr/bin/env python3 -""" -Extracts `public enum Components { ... }` from a generated Types.swift and -splices it into Components.swift, preserving the existing file header. -""" - -import sys -import re - -if len(sys.argv) != 3: - print("Usage: extract_components.py ", file=sys.stderr) - sys.exit(1) - -TYPES_SWIFT = sys.argv[1] # path to generated Types.swift -COMPONENTS_SWIFT = sys.argv[2] # path to Components.swift in the project - -# --- Extract the Components enum from Types.swift --- - -with open(TYPES_SWIFT, "r") as f: - lines = f.readlines() - -start_index = None -for i, line in enumerate(lines): - if re.match(r"^public enum Components \{", line): - start_index = i - break - -if start_index is None: - print("ERROR: could not find 'public enum Components {' in " + TYPES_SWIFT, file=sys.stderr) - sys.exit(1) - -depth = 0 -end_index = None -for i in range(start_index, len(lines)): - depth += lines[i].count("{") - lines[i].count("}") - if depth == 0: - end_index = i - break - -if end_index is None: - print("ERROR: could not find closing brace for Components enum", file=sys.stderr) - sys.exit(1) - -# --- Strip typealiases that shadow Swift built-in type names --- -# The generator emits e.g. `public typealias String = Swift.String` inside nested -# types when a schema property clashes with a Swift built-in. These are always -# redundant and cause "redeclaration" build errors. - -SWIFT_BUILTINS = { - "Bool", "String", "Int", "Double", "Float", - "UInt", "Character", - "Int8", "Int16", "Int32", "Int64", - "UInt8", "UInt16", "UInt32", "UInt64", -} -TYPEALIAS_RE = re.compile(r"^\s+public typealias\s+(\w+)\s*=") - -filtered = [] -removed = 0 -for line in lines[start_index : end_index + 1]: - m = TYPEALIAS_RE.match(line) - if m and m.group(1) in SWIFT_BUILTINS: - removed += 1 - continue - filtered.append(line) - -components_block = "".join(filtered) - -# --- Read the existing header from Components.swift (up to and including #endif) --- - -with open(COMPONENTS_SWIFT, "r") as f: - existing = f.readlines() - -header_end = None -for i, line in enumerate(existing): - if line.strip() == "#endif": - header_end = i - break - -if header_end is None: - print("ERROR: could not find '#endif' header boundary in " + COMPONENTS_SWIFT, file=sys.stderr) - sys.exit(1) - -header = "".join(existing[: header_end + 1]) - -# --- Write the result --- - -with open(COMPONENTS_SWIFT, "w") as f: - f.write(header) - f.write("\n") - f.write(components_block) - f.write("\n") - -print(f"Written {len(filtered)} lines of Components enum to {COMPONENTS_SWIFT}") -if removed > 0: - print( - f"Note: stripped {removed} typealias line(s) that shadow Swift built-in type names " - f"(e.g. `public typealias String = Swift.String`). " - f"These are emitted as duplicates by swift-openapi-generator for certain schemas, " - f"causing 'invalid redeclaration' build errors. " - f"Check https://github.com/apple/swift-openapi-generator/issues for a related bug report — " - f"if it has been fixed, this stripping step may no longer be necessary." - ) diff --git a/Scripts/fix_recursive_reference.py b/Scripts/fix_recursive_reference.py index d3c7ea50..1ad43b60 100644 --- a/Scripts/fix_recursive_reference.py +++ b/Scripts/fix_recursive_reference.py @@ -1,54 +1,70 @@ #!/usr/bin/env python3 -"""Replace the unsupported CompoundFilter recursive reference. +"""Replace unsupported `$recursiveRef` references with ordinary component references. Symptom: - Validation warns that CompoundFilter's second item union member contains - nothing but unsupported attributes. + Validation warns that a filter schema's union member contains nothing but + unsupported attributes, and the recursion is lost in the generated types. Cause: Swift OpenAPI Generator does not support JSON Schema `$recursiveRef`. Fix: - Replace the one known `$recursiveRef: '#'` with an ordinary component - reference to `CompoundFilter`, preserving the intended recursion. + Replace every `$recursiveRef: '#'` with `$ref: '#/components/schemas/'`, + where `` is the component schema that contains the reference. The spec + uses this construct only inside self-recursive components (`CompoundFilter`, + and since September 2026 also `BetaCompoundFilter`), so the enclosing + component is the intended target. Semantic limitation: This is not a general equivalent of `$recursiveRef`. `$recursiveRef` can resolve through the active recursive-anchor scope, while `$ref` always - targets the named `CompoundFilter` component. They behave the same for this - self-contained document because CompoundFilter is the only recursive anchor - and the reference represents nested CompoundFilter values. Reassess this - workaround if the schema gains another recursive anchor, an external schema, - or recursive extension/composition. + targets the named component. They behave the same here because each + occurrence sits inside the component it recurses into. Reassess this + workaround if a reference appears outside its own component, in an external + schema, or in recursive extension/composition. Removal condition: Remove this workaround when the generator supports `$recursiveRef`, or when - the upstream spec no longer contains this exact reference. + the upstream spec no longer contains it. With no occurrences it is a no-op. """ from __future__ import annotations import argparse +import re from pathlib import Path OLD_REFERENCE = "$recursiveRef: '#'" -NEW_REFERENCE = "$ref: '#/components/schemas/CompoundFilter'" +COMPONENT_SCHEMA_RE = re.compile(r"^ (?P[^\s][^:]*):(?:\r?\n)?$") def fix_recursive_reference(document: str) -> tuple[str, int]: - count = document.count(OLD_REFERENCE) - if count > 1: - raise ValueError( - "Expected at most one CompoundFilter recursive reference; " - f"found {count}." + """Return the document with each recursive reference pointed at its component.""" + + lines = document.splitlines(keepends=True) + current_component: str | None = None + count = 0 + for index, line in enumerate(lines): + match = COMPONENT_SCHEMA_RE.match(line) + if match is not None: + current_component = match.group("name") + if OLD_REFERENCE not in line: + continue + if current_component is None: + raise ValueError( + f"Cannot fix `$recursiveRef` on line {index + 1}: it is not inside a component schema." + ) + lines[index] = line.replace( + OLD_REFERENCE, f"$ref: '#/components/schemas/{current_component}'" ) - return document.replace(OLD_REFERENCE, NEW_REFERENCE), count + count += 1 + return "".join(lines), count def report_result(replacement_count: int) -> None: if replacement_count: - print("Recursive reference workaround applied: 1 replacement.") + print(f"Recursive reference workaround applied: {replacement_count} replacement(s).") else: print( "Recursive reference workaround not needed. The upstream spec or " diff --git a/Scripts/postprocess_components.py b/Scripts/postprocess_components.py new file mode 100644 index 00000000..2fda607f --- /dev/null +++ b/Scripts/postprocess_components.py @@ -0,0 +1,186 @@ +#!/usr/bin/env python3 +"""Turn the generator's Types+Components+Schemas.swift into the committed Components.swift. + +Swift OpenAPI Generator 1.13 writes one file per namespace. This script takes the schemas file and: + +1. keeps the existing Components.swift header (everything up to and including `#endif`) and re-wraps the + generated `extension Components { public enum Schemas { ... } }` as `public enum Components { ... }`, + adding the empty sibling namespaces the single-file layout used to declare; +2. strips `public typealias String = Swift.String`-style aliases that shadow Swift built-ins; the generator + emits them for some schemas and they cause "invalid redeclaration" errors; +3. applies the discriminator sidecar written by `transform_openapi.py`: for every discriminated union it appends + each member's wire values to the generated `case "Name", "#/components/schemas/Name":` line of that union's + decoder, and for values shared by several members (`message` in `Item` and `ItemResource`) it inserts a + fallback that tries each member in turn. This is what the generator would do with an explicit `mapping`, + minus the enum-case renaming a mapping would cause. + +The wire values are applied per union, never globally: `message` is unique in `OutputItem` but ambiguous in +`Item`, and adding it to `Item`'s `OutputMessage` case would shadow the fallback. + +Usage: + postprocess_components.py +""" + +from __future__ import annotations + +import argparse +import json +import re +from pathlib import Path + +SWIFT_BUILTINS = { + "Bool", "String", "Int", "Double", "Float", "UInt", "Character", + "Int8", "Int16", "Int32", "Int64", "UInt8", "UInt16", "UInt32", "UInt64", +} +SIBLING_NAMESPACES = ("Parameters", "RequestBodies", "Responses", "Headers") + +TYPEALIAS_RE = re.compile(r"^\s+public typealias\s+(\w+)\s*=") +COMPONENTS_START_RE = re.compile(r"^(extension|public enum) Components\s*\{") +CASE_DECL_RE = re.compile(r"^\s*case (\w+)\(Components\.Schemas\.(\w+)\)") +INIT_RE = re.compile(r"public init\(from decoder: any Swift\.Decoder\) throws \{") +DEFAULT_RE = re.compile(r"^\s*default:\s*$") +ERRORS_DECL = "var errors: [any Swift.Error] = []" + + +def block_range(lines: list[str], start_pattern: re.Pattern[str]) -> range | None: + """Return the line range of the first block whose opening line matches, using brace depth.""" + start = next((i for i, line in enumerate(lines) if start_pattern.search(line)), None) + if start is None: + return None + depth = 0 + for offset, line in enumerate(lines[start:]): + depth += line.count("{") - line.count("}") + if depth == 0: + return range(start, start + offset + 1) + return None + + +def union_enum_range(lines: list[str], name: str) -> range | None: + return block_range(lines, re.compile(rf"^\s*@frozen public enum {re.escape(name)}: Codable, Hashable, Sendable \{{")) + + +def component_range(lines: list[str], name: str) -> range | None: + # Component-level types sit directly inside `public enum Schemas {`, at eight spaces of indentation. + return block_range(lines, re.compile(rf"^ (@frozen )?public (struct|enum) {re.escape(name)}[:\s]")) + + +def case_line_pattern(schema: str) -> re.Pattern[str]: + escaped = re.escape(schema) + return re.compile(rf'^(\s*)case "{escaped}", "#/components/schemas/{escaped}":\s*$') + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("schemas_swift", type=Path, help="Generated Types+Components+Schemas.swift") + parser.add_argument("discriminators", type=Path, help="Sidecar written by transform_openapi.py") + parser.add_argument("components_swift", type=Path, help="Components.swift to update in place") + args = parser.parse_args() + + existing = args.components_swift.read_text(encoding="utf-8").splitlines(keepends=True) + header_end = next((i for i, line in enumerate(existing) if line.strip() == "#endif"), None) + if header_end is None: + raise SystemExit(f"error: no '#endif' header boundary in {args.components_swift}") + header = "".join(existing[: header_end + 1]) + + generated = args.schemas_swift.read_text(encoding="utf-8").splitlines(keepends=True) + start = next((i for i, line in enumerate(generated) if COMPONENTS_START_RE.match(line)), None) + if start is None: + raise SystemExit(f"error: no 'extension Components' block in {args.schemas_swift}") + body = generated[start:] + body[0] = COMPONENTS_START_RE.sub("public enum Components {", body[0], count=1) + + stripped = 0 + kept: list[str] = [] + for line in body: + match = TYPEALIAS_RE.match(line) + if match and match.group(1) in SWIFT_BUILTINS: + stripped += 1 + continue + kept.append(line) + body = kept + + discriminators: dict[str, dict[str, dict[str, list[str]]]] = json.loads(args.discriminators.read_text(encoding="utf-8")) + wire_values_added = 0 + fallbacks = 0 + problems: list[str] = [] + + for path, info in discriminators.items(): + owner = path.split("/", 1)[0] + block = union_enum_range(body, path) if "/" not in path else component_range(body, owner) + if block is None: + continue # this union is outside the generated paths + for schema, values in info["values"].items(): + pattern = case_line_pattern(schema) + hits = 0 + for index in block: + if pattern.match(body[index]): + body[index] = re.sub(r":\s*$", ", " + ", ".join(json.dumps(v) for v in values) + ":\n", body[index], count=1) + wire_values_added += len(values) + hits += 1 + if hits == 0 and "/" not in path: + problems.append(f"{path}: no generated case for member {schema}") + + if not info["collisions"]: + continue + if "/" in path: + problems.append(f"{path}: colliding values inside a nested union are not supported") + continue + block_lines = body[block.start:block.stop] + case_names = {m.group(2): m.group(1) for line in block_lines if (m := CASE_DECL_RE.match(line))} + init_index = next((i for i, line in enumerate(block_lines) if INIT_RE.search(line)), None) + if init_index is None: + problems.append(f"{path}: no init(from:) found") + continue + if not any(ERRORS_DECL in line for line in block_lines): + indent = re.match(r"^\s*", block_lines[init_index + 1]).group(0) + block_lines.insert(init_index + 1, f"{indent}{ERRORS_DECL}\n") + for value, members in info["collisions"].items(): + default_index = next((i for i, line in enumerate(block_lines) if DEFAULT_RE.match(line)), None) + if default_index is None: + problems.append(f"{path}: no default: clause in the discriminator switch") + break + indent = re.match(r"^\s*", block_lines[default_index]).group(0) + attempts = [] + for member in members: + case_name = case_names.get(member) + if case_name is None: + problems.append(f"{path}: no enum case for {member}") + break + attempts.append( + f"{indent} do {{\n" + f"{indent} self = .{case_name}(try .init(from: decoder))\n" + f"{indent} return\n" + f"{indent} }} catch {{\n" + f"{indent} errors.append(error)\n" + f"{indent} }}\n" + ) + else: + fallback = ( + f"{indent}case {json.dumps(value)}:\n" + "".join(attempts) + + f"{indent} throw Swift.DecodingError.failedToDecodeOneOfSchema(\n" + + f"{indent} type: Self.self,\n" + + f"{indent} codingPath: decoder.codingPath,\n" + + f"{indent} errors: errors\n" + + f"{indent} )\n" + ) + block_lines.insert(default_index, fallback) + fallbacks += 1 + body[block.start:block.stop] = block_lines + + closing = max(i for i, line in enumerate(body) if re.match(r"^\}\s*$", line)) + for offset, namespace in enumerate(SIBLING_NAMESPACES): + body.insert(closing + offset, f" public enum {namespace} {{}}\n") + + args.components_swift.write_text(header + "\n" + "".join(body) + "\n", encoding="utf-8") + print( + f"Written {len(body)} lines to {args.components_swift.name}: stripped {stripped} shadowing typealiases, " + f"added {wire_values_added} discriminator wire values, inserted {fallbacks} collision fallbacks." + ) + if problems: + for problem in problems: + print(f"error: {problem}") + raise SystemExit(1) + + +if __name__ == "__main__": + main() diff --git a/Scripts/requirements.txt b/Scripts/requirements.txt new file mode 100644 index 00000000..31025b9f --- /dev/null +++ b/Scripts/requirements.txt @@ -0,0 +1 @@ +pyyaml>=6,<7 diff --git a/Scripts/transform_openapi.py b/Scripts/transform_openapi.py new file mode 100644 index 00000000..aa2a6232 --- /dev/null +++ b/Scripts/transform_openapi.py @@ -0,0 +1,226 @@ +#!/usr/bin/env python3 +"""Rewrite the prepared OpenAPI document so the stock Swift OpenAPI Generator produces the types we need. + +This step replaces the patches that used to live in a private fork of swift-openapi-generator. It runs after +`prepare_openapi.py` and `remove_required_properties.py` (which are line-based and keep the document text +intact) and before the generator. It reads and writes YAML through PyYAML, so its output is a working copy +for the generator only and is never committed. + +1. Nullability. + OpenAI expresses "nullable" as `anyOf: [X, {type: 'null'}]`. Swift OpenAPI Generator does not support that + form (apple/swift-openapi-generator#906) and *skips* every such property with "Schema null is not supported". + The upstream maintainer's recommended workaround is applied here: the null branch is dropped, the `anyOf` + collapses to X (or to the remaining `anyOf` when several non-null members exist), and the property is removed + from the enclosing `required` list so it is generated as optional. A property that references a component + which is nullable at its root (for example `ResponseError`) is removed from `required` for the same reason: + `null` is a valid value for it on the wire. + +2. Discriminators. + Every `oneOf` with `discriminator: {propertyName: type}` lacks a `mapping`, so the generator compares the + schema *name* with the wire value and fails to decode real payloads (openai/openai-openapi#542). Adding a + `mapping` is not an option: the generator then names enum cases after the mapping keys, which renames public + API. Instead this script records, for every discriminated union (component-level or nested), each member's + wire values, taken from the member's discriminator property (`enum`, `const`, or `x-stainless-const`, + resolved through `$ref` and `allOf`), and the values that several members share. `postprocess_components.py` + applies them to the generated Swift. + +Usage: + transform_openapi.py +""" + +from __future__ import annotations + +import argparse +import json +from collections import Counter +from pathlib import Path +from typing import Any + +import yaml + +Loader = getattr(yaml, "CSafeLoader", yaml.SafeLoader) +Dumper = getattr(yaml, "CSafeDumper", yaml.SafeDumper) + +REF_PREFIX = "#/components/schemas/" + + +def is_null_schema(member: Any) -> bool: + if not isinstance(member, dict): + return False + # `type: 'null'` is the form OpenAI uses; a bare unquoted `type: null` parses to None. + return member.get("type") == "null" or (list(member) == ["type"] and member["type"] is None) + + +def has_null_member(node: Any) -> bool: + return isinstance(node, dict) and isinstance(node.get("anyOf"), list) and any( + is_null_schema(m) for m in node["anyOf"] + ) + + +def ref_name(node: Any) -> str | None: + if isinstance(node, dict) and isinstance(node.get("$ref"), str) and node["$ref"].startswith(REF_PREFIX): + return node["$ref"][len(REF_PREFIX):] + return None + + +class Transformer: + def __init__(self, schemas: dict[str, Any]) -> None: + self.schemas = schemas + self.stats: Counter[str] = Counter() + self.root_nullable = {name for name, schema in schemas.items() if has_null_member(schema)} + self.stats["root_nullable_schemas"] = len(self.root_nullable) + self.discriminators: dict[str, dict[str, Any]] = {} + + # -- nullability --------------------------------------------------------------------------------------- + + def strip_null(self, node: dict[str, Any]) -> dict[str, Any]: + members = [m for m in node["anyOf"] if not is_null_schema(m)] + if len(members) == len(node["anyOf"]): + return node + self.stats["nullable_anyof"] += 1 + rest = {k: v for k, v in node.items() if k != "anyOf"} + if len(members) == 1: + member = members[0] + if "$ref" in member: + collapsed: dict[str, Any] = {"$ref": member["$ref"]} + if "description" in rest: + collapsed["description"] = rest["description"] + return collapsed + # Inline member: it wins over the wrapper's keys, the wrapper's description/default are kept. + return {**rest, **member} + return {**rest, "anyOf": members} + + def property_is_nullable(self, schema: Any) -> bool: + if not isinstance(schema, dict): + return False + if has_null_member(schema): + return True + if ref_name(schema) in self.root_nullable: + return True + if isinstance(schema.get("anyOf"), list): + members = [m for m in schema["anyOf"] if not is_null_schema(m)] + if len(members) == 1 and ref_name(members[0]) in self.root_nullable: + return True + return False + + def walk(self, node: Any) -> Any: + if isinstance(node, list): + return [self.walk(item) for item in node] + if not isinstance(node, dict): + return node + if isinstance(node.get("anyOf"), list): + node = self.strip_null(node) + properties = node.get("properties") + if isinstance(properties, dict) and isinstance(node.get("required"), list): + nullable = {name for name, schema in properties.items() if self.property_is_nullable(schema)} + if nullable: + before = len(node["required"]) + node = dict(node) + node["required"] = [name for name in node["required"] if name not in nullable] + self.stats["required_relaxed"] += before - len(node["required"]) + if not node["required"]: + del node["required"] + return {key: self.walk(value) for key, value in node.items()} + + # -- discriminators ------------------------------------------------------------------------------------ + + def resolve(self, node: Any) -> Any: + for _ in range(10): + name = ref_name(node) + if name is None: + break + node = self.schemas.get(name) + return node + + def discriminator_values(self, member: Any, property_name: str) -> list[str]: + schema = self.resolve(member) + if not isinstance(schema, dict): + return [] + properties: dict[str, Any] = {} + for part in schema.get("allOf") or []: + resolved = self.resolve(part) + if isinstance(resolved, dict): + properties.update(resolved.get("properties") or {}) + properties.update(schema.get("properties") or {}) + declared = self.resolve(properties.get(property_name)) + if not isinstance(declared, dict): + return [] + if isinstance(declared.get("enum"), list): + return [str(value) for value in declared["enum"]] + for key in ("const", "x-stainless-const"): + if key in declared: + return [str(declared[key])] + return [] + + def collect(self, node: Any, path: str) -> None: + if isinstance(node, list): + for index, item in enumerate(node): + self.collect(item, f"{path}[{index}]") + return + if not isinstance(node, dict): + return + discriminator = node.get("discriminator") + if isinstance(node.get("oneOf"), list) and isinstance(discriminator, dict) and not discriminator.get("mapping"): + property_name = discriminator["propertyName"] + by_value: dict[str, list[str]] = {} + for member in node["oneOf"]: + name = ref_name(member) + if name is None: + continue + for value in self.discriminator_values(member, property_name): + members = by_value.setdefault(value, []) + if name not in members: + members.append(name) + values: dict[str, list[str]] = {} + collisions: dict[str, list[str]] = {} + for value, members in by_value.items(): + if len(members) == 1: + values.setdefault(members[0], []).append(value) + else: + collisions[value] = members + self.stats["unions"] += 1 + self.stats["wire_values"] += sum(len(v) for v in values.values()) + self.stats["collisions"] += len(collisions) + self.discriminators[path] = {"values": values, "collisions": collisions} + for key, value in node.items(): + self.collect(value, f"{path}/{key}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("input", type=Path, help="Prepared OpenAPI document") + parser.add_argument("output", type=Path, help="Transformed working copy for the generator") + parser.add_argument("discriminators", type=Path, help="JSON sidecar consumed by postprocess_components.py") + args = parser.parse_args() + + with args.input.open(encoding="utf-8") as handle: + spec = yaml.load(handle, Loader=Loader) + + transformer = Transformer(spec["components"]["schemas"]) + spec["components"]["schemas"] = transformer.walk(spec["components"]["schemas"]) + transformer.schemas = spec["components"]["schemas"] + for name, schema in spec["components"]["schemas"].items(): + transformer.collect(schema, name) + + args.output.parent.mkdir(parents=True, exist_ok=True) + with args.output.open("w", encoding="utf-8") as handle: + yaml.dump(spec, handle, Dumper=Dumper, sort_keys=False, allow_unicode=True, width=4096) + args.discriminators.write_text(json.dumps(transformer.discriminators, indent=2) + "\n", encoding="utf-8") + + stats = transformer.stats + print( + "Transform applied: " + f"{stats['nullable_anyof']} nullable anyOf collapsed, {stats['required_relaxed']} required entries relaxed " + f"({stats['root_nullable_schemas']} root-nullable components), {stats['unions']} discriminated unions with " + f"{stats['wire_values']} wire values and {stats['collisions']} colliding values." + ) + collisions = { + path: info["collisions"] for path, info in transformer.discriminators.items() if info["collisions"] + } + for path, values in collisions.items(): + for value, members in values.items(): + print(f" collision: {path} value {value!r} -> {' | '.join(members)}") + + +if __name__ == "__main__": + main() diff --git a/Sources/OpenAI/Public/Schemas/Generated/Components.swift b/Sources/OpenAI/Public/Schemas/Generated/Components.swift index 7148cc6e..3fc86ecc 100644 --- a/Sources/OpenAI/Public/Schemas/Generated/Components.swift +++ b/Sources/OpenAI/Public/Schemas/Generated/Components.swift @@ -4,6 +4,10 @@ // // Created by Oleksii Nezhyborets on 31.03.2025. // +// Generated by `make generate` from openapi.yaml with Swift OpenAPI Generator; see the Makefile and +// CONTRIBUTING.md, "Implementing using Code Generation". Do not edit by hand, regenerate instead. +// Everything up to `#endif` is kept by Scripts/postprocess_components.py; everything below it is replaced. +// @_spi(Generated) import OpenAPIRuntime #if os(Linux) @@ -157,6 +161,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/container_id`. public var containerId: Swift.String + /// The code to run, or null if not available. + /// + /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/code`. public var code: Swift.String? /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/OutputsPayload`. @@ -202,6 +209,10 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/outputs`. public typealias OutputsPayload = [Components.Schemas.CodeInterpreterToolCall.OutputsPayloadPayload] + /// The outputs generated by the code interpreter, such as logs or images. + /// Can be null if no outputs are available. + /// + /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/outputs`. public var outputs: Components.Schemas.CodeInterpreterToolCall.OutputsPayload? /// Creates a new `CodeInterpreterToolCall`. @@ -211,8 +222,8 @@ public enum Components { /// - id: The unique ID of the code interpreter tool call. /// - status: The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`. /// - containerId: The ID of the container used to run the code. - /// - code: - /// - outputs: + /// - code: The code to run, or null if not available. + /// - outputs: The outputs generated by the code interpreter, such as logs or images. public init( _type: Components.Schemas.CodeInterpreterToolCall._TypePayload, id: Swift.String, @@ -1072,43 +1083,72 @@ public enum Components { public struct Value3Payload: Codable, Hashable, Sendable { /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/input`. public var input: Components.Schemas.InputParam? - /// - Remark: Generated from `#/components/schemas/IncludeEnum`. - public typealias IncludeEnum = [Components.Schemas.IncludeEnum] + /// Specify additional output data to include in the model response. Currently supported values are: + /// - `web_search_call.action.sources`: Include the sources of the web search tool call. + /// - `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items. + /// - `computer_call_output.output.image_url`: Include image urls from the computer call output. + /// - `file_search_call.results`: Include the search results of the file search tool call. + /// - `message.input_image.image_url`: Include image urls from the input message. + /// - `message.output_text.logprobs`: Include logprobs with assistant messages. + /// - `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). + /// /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/include`. public var include: [Components.Schemas.IncludeEnum]? + /// Whether to allow the model to run tool calls in parallel. + /// + /// /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/parallel_tool_calls`. public var parallelToolCalls: Swift.Bool? + /// Whether to store the generated model response for later retrieval via + /// API. + /// + /// /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/store`. public var store: Swift.Bool? + /// A system (or developer) message inserted into the model's context. + /// + /// When using 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. + /// + /// /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/instructions`. public var instructions: Swift.String? + /// If set to true, the model response data will be streamed to the client + /// as 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). + /// See the [Streaming section below](/docs/api-reference/responses-streaming) + /// for more information. + /// + /// /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/stream`. public var stream: Swift.Bool? /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/stream_options`. public var streamOptions: Components.Schemas.ResponseStreamOptions? - /// - Remark: Generated from `#/components/schemas/ConversationParam`. - public typealias ConversationParam = Components.Schemas.ConversationParam /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/conversation`. public var conversation: Components.Schemas.ConversationParam? - /// - Remark: Generated from `#/components/schemas/ContextManagementParam`. - public typealias ContextManagementParam = [Components.Schemas.ContextManagementParam] + /// Context management configuration for this request. + /// + /// /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/context_management`. public var contextManagement: [Components.Schemas.ContextManagementParam]? + /// 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). + /// + /// /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/max_output_tokens`. public var maxOutputTokens: Swift.Int? /// Creates a new `Value3Payload`. /// /// - Parameters: /// - input: - /// - include: - /// - parallelToolCalls: - /// - store: - /// - instructions: - /// - stream: + /// - include: Specify additional output data to include in the model response. Currently supported values are: + /// - parallelToolCalls: Whether to allow the model to run tool calls in parallel. + /// - store: Whether to store the generated model response for later retrieval via + /// - instructions: A system (or developer) message inserted into the model's context. + /// - stream: If set to true, the model response data will be streamed to the client /// - streamOptions: /// - conversation: - /// - contextManagement: - /// - maxOutputTokens: + /// - contextManagement: Context management configuration for this request. + /// - maxOutputTokens: 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). public init( input: Components.Schemas.InputParam? = nil, include: [Components.Schemas.IncludeEnum]? = nil, @@ -1271,6 +1311,18 @@ public enum Components { } } case timestampGranularities(OpenAPIRuntime.MultipartPart) + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/stream`. + public struct StreamPayload: Sendable, Hashable { + public var body: OpenAPIRuntime.HTTPBody + /// Creates a new `StreamPayload`. + /// + /// - Parameters: + /// - body: + public init(body: OpenAPIRuntime.HTTPBody) { + self.body = body + } + } + case stream(OpenAPIRuntime.MultipartPart) /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/chunking_strategy`. public struct ChunkingStrategyPayload: Sendable, Hashable { /// 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. @@ -1332,12 +1384,12 @@ public enum Components { try self.value2?.encode(to: encoder) } } - public var body: Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload? + public var body: Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload /// Creates a new `ChunkingStrategyPayload`. /// /// - Parameters: /// - body: - public init(body: Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload? = nil) { + public init(body: Components.Schemas.CreateTranscriptionRequest.ChunkingStrategyPayload.BodyPayload) { self.body = body } } @@ -2081,8 +2133,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/EasyInputMessage/content`. public var content: Components.Schemas.EasyInputMessage.ContentPayload - /// - Remark: Generated from `#/components/schemas/MessagePhase`. - public typealias MessagePhase = Components.Schemas.MessagePhase /// - Remark: Generated from `#/components/schemas/EasyInputMessage/phase`. public var phase: Components.Schemas.MessagePhase? /// The type of the message input. Always `message`. @@ -2309,6 +2359,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FileSearchToolCall/results`. public typealias ResultsPayload = [Components.Schemas.FileSearchToolCall.ResultsPayloadPayload] + /// The results of the file search tool call. + /// + /// /// - Remark: Generated from `#/components/schemas/FileSearchToolCall/results`. public var results: Components.Schemas.FileSearchToolCall.ResultsPayload? /// Creates a new `FileSearchToolCall`. @@ -2318,7 +2371,7 @@ public enum Components { /// - _type: The type of the file search tool call. Always `file_search_call`. /// - status: The status of the file search tool call. One of `in_progress`, /// - queries: The queries used to search for files. - /// - results: + /// - results: The results of the file search tool call. public init( id: Swift.String, _type: Components.Schemas.FileSearchToolCall._TypePayload, @@ -2940,8 +2993,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ImageGenTool/background`. public var background: Components.Schemas.ImageGenTool.BackgroundPayload? - /// - Remark: Generated from `#/components/schemas/InputFidelity`. - public typealias InputFidelity = Components.Schemas.InputFidelity /// - Remark: Generated from `#/components/schemas/ImageGenTool/input_fidelity`. public var inputFidelity: Components.Schemas.InputFidelity? /// Optional mask for inpainting. Contains `image_url` @@ -3102,6 +3153,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ImageGenToolCall/status`. public var status: Components.Schemas.ImageGenToolCall.StatusPayload + /// The generated image encoded in base64. + /// + /// /// - Remark: Generated from `#/components/schemas/ImageGenToolCall/result`. public var result: Swift.String? /// Creates a new `ImageGenToolCall`. @@ -3110,7 +3164,7 @@ public enum Components { /// - _type: The type of the image generation call. Always `image_generation_call`. /// - id: The unique ID of the image generation call. /// - status: The status of the image generation call. - /// - result: + /// - result: The generated image encoded in base64. public init( _type: Components.Schemas.ImageGenToolCall._TypePayload, id: Swift.String, @@ -3194,7 +3248,7 @@ public enum Components { self = .easyInputMessage(try .init(from: decoder)) case "Item", "#/components/schemas/Item": self = .item(try .init(from: decoder)) - case "ItemReferenceParam", "#/components/schemas/ItemReferenceParam": + case "ItemReferenceParam", "#/components/schemas/ItemReferenceParam", "item_reference": self = .itemReferenceParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -3659,6 +3713,7 @@ public enum Components { case _type = "type" } public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] let container = try decoder.container(keyedBy: CodingKeys.self) let discriminator = try container.decode( Swift.String.self, @@ -3667,19 +3722,19 @@ public enum Components { switch discriminator { case "InputMessageResource", "#/components/schemas/InputMessageResource": self = .inputMessageResource(try .init(from: decoder)) - case "OutputMessage", "#/components/schemas/OutputMessage", "message": + case "OutputMessage", "#/components/schemas/OutputMessage": self = .outputMessage(try .init(from: decoder)) case "FileSearchToolCall", "#/components/schemas/FileSearchToolCall", "file_search_call": self = .fileSearchToolCall(try .init(from: decoder)) case "ComputerToolCall", "#/components/schemas/ComputerToolCall", "computer_call": self = .computerToolCall(try .init(from: decoder)) - case "ComputerToolCallOutputResource", "#/components/schemas/ComputerToolCallOutputResource": + case "ComputerToolCallOutputResource", "#/components/schemas/ComputerToolCallOutputResource", "computer_call_output": self = .computerToolCallOutputResource(try .init(from: decoder)) case "WebSearchToolCall", "#/components/schemas/WebSearchToolCall", "web_search_call": self = .webSearchToolCall(try .init(from: decoder)) - case "FunctionToolCallResource", "#/components/schemas/FunctionToolCallResource": + case "FunctionToolCallResource", "#/components/schemas/FunctionToolCallResource", "function_call": self = .functionToolCallResource(try .init(from: decoder)) - case "FunctionToolCallOutputResource", "#/components/schemas/FunctionToolCallOutputResource": + case "FunctionToolCallOutputResource", "#/components/schemas/FunctionToolCallOutputResource", "function_call_output": self = .functionToolCallOutputResource(try .init(from: decoder)) case "ToolSearchCall", "#/components/schemas/ToolSearchCall", "tool_search_call": self = .toolSearchCall(try .init(from: decoder)) @@ -3713,10 +3768,28 @@ public enum Components { self = .mcpApprovalResponseResource(try .init(from: decoder)) case "MCPToolCall", "#/components/schemas/MCPToolCall", "mcp_call": self = .mcpToolCall(try .init(from: decoder)) - case "CustomToolCallResource", "#/components/schemas/CustomToolCallResource": + case "CustomToolCallResource", "#/components/schemas/CustomToolCallResource", "custom_tool_call": self = .customToolCallResource(try .init(from: decoder)) - case "CustomToolCallOutputResource", "#/components/schemas/CustomToolCallOutputResource": + case "CustomToolCallOutputResource", "#/components/schemas/CustomToolCallOutputResource", "custom_tool_call_output": self = .customToolCallOutputResource(try .init(from: decoder)) + case "message": + do { + self = .inputMessageResource(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .outputMessage(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) default: throw Swift.DecodingError.unknownOneOfDiscriminator( discriminatorKey: CodingKeys._type, @@ -3890,6 +3963,9 @@ public enum Components { case completed = "completed" case incomplete = "incomplete" } + /// The status of the item. One of `in_progress`, `completed`, or `incomplete`. + /// + /// /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput/status`. public var status: Components.Schemas.LocalShellToolCallOutput.StatusPayload? /// Creates a new `LocalShellToolCallOutput`. @@ -3898,7 +3974,7 @@ public enum Components { /// - _type: The type of the local shell tool call output. Always `local_shell_call_output`. /// - id: The unique ID of the local shell tool call generated by the model. /// - output: A JSON string of the output of the local shell tool call. - /// - status: + /// - status: The status of the item. One of `in_progress`, `completed`, or `incomplete`. public init( _type: Components.Schemas.LocalShellToolCallOutput._TypePayload, id: Swift.String, @@ -4000,6 +4076,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/type`. public var _type: Components.Schemas.MCPApprovalResponse._TypePayload + /// The unique ID of the approval response + /// + /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/id`. public var id: Swift.String? /// The ID of the approval request being answered. @@ -4012,16 +4091,19 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/approve`. public var approve: Swift.Bool + /// Optional reason for the decision. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/reason`. public var reason: Swift.String? /// Creates a new `MCPApprovalResponse`. /// /// - Parameters: /// - _type: The type of the item. Always `mcp_approval_response`. - /// - id: + /// - id: The unique ID of the approval response /// - approvalRequestId: The ID of the approval request being answered. /// - approve: Whether the request was approved. - /// - reason: + /// - reason: Optional reason for the decision. public init( _type: Components.Schemas.MCPApprovalResponse._TypePayload, id: Swift.String? = nil, @@ -4075,6 +4157,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponseResource/approve`. public var approve: Swift.Bool + /// Optional reason for the decision. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponseResource/reason`. public var reason: Swift.String? /// Creates a new `MCPApprovalResponseResource`. @@ -4084,7 +4169,7 @@ public enum Components { /// - id: The unique ID of the approval response /// - approvalRequestId: The ID of the approval request being answered. /// - approve: Whether the request was approved. - /// - reason: + /// - reason: Optional reason for the decision. public init( _type: Components.Schemas.MCPApprovalResponseResource._TypePayload, id: Swift.String, @@ -4138,6 +4223,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPListTools/tools`. public var tools: [Components.Schemas.MCPListToolsTool] + /// Error message if the server could not list tools. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPListTools/error`. public var error: Swift.String? /// Creates a new `MCPListTools`. @@ -4147,7 +4235,7 @@ public enum Components { /// - id: The unique ID of the list. /// - serverLabel: The label of the MCP server. /// - tools: The tools available on the server. - /// - error: + /// - error: Error message if the server could not list tools. public init( _type: Components.Schemas.MCPListTools._TypePayload, id: Swift.String, @@ -4179,6 +4267,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/name`. public var name: Swift.String + /// The description of the tool. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/description`. public var description: Swift.String? /// The JSON schema describing the tool's input. @@ -4186,16 +4277,18 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/input_schema`. public var inputSchema: OpenAPIRuntime.OpenAPIObjectContainer - public typealias OpenAPIObjectContainer = OpenAPIRuntime.OpenAPIObjectContainer + /// Additional annotations about the tool. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/annotations`. public var annotations: OpenAPIRuntime.OpenAPIObjectContainer? /// Creates a new `MCPListToolsTool`. /// /// - Parameters: /// - name: The name of the tool. - /// - description: + /// - description: The description of the tool. /// - inputSchema: The JSON schema describing the tool's input. - /// - annotations: + /// - annotations: Additional annotations about the tool. public init( name: Swift.String, description: Swift.String? = nil, @@ -4320,6 +4413,10 @@ public enum Components { try encoder.encodeAdditionalProperties(additionalProperties) } } + /// Optional HTTP headers to send to the MCP server. Use for authentication + /// or other purposes. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPTool/headers`. public var headers: Components.Schemas.MCPTool.HeadersPayload? /// List of allowed tool names or a filter object. @@ -4362,6 +4459,9 @@ public enum Components { } } } + /// List of allowed tool names or a filter object. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPTool/allowed_tools`. public var allowedTools: Components.Schemas.MCPTool.AllowedToolsPayload? /// Specify which of the MCP server's tools require approval. @@ -4464,6 +4564,8 @@ public enum Components { } } } + /// Specify which of the MCP server's tools require approval. + /// /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval`. public var requireApproval: Components.Schemas.MCPTool.RequireApprovalPayload? /// Whether this MCP tool is deferred and discovered via tool search. @@ -4480,9 +4582,9 @@ public enum Components { /// - connectorId: Identifier for service connectors, like those available in ChatGPT. One of /// - authorization: An OAuth access token that can be used with a remote MCP server, either /// - serverDescription: Optional description of the MCP server, used to provide more context. - /// - headers: - /// - allowedTools: - /// - requireApproval: + /// - headers: Optional HTTP headers to send to the MCP server. Use for authentication + /// - allowedTools: List of allowed tool names or a filter object. + /// - requireApproval: Specify which of the MCP server's tools require approval. /// - deferLoading: Whether this MCP tool is deferred and discovered via tool search. public init( _type: Components.Schemas.MCPTool._TypePayload, @@ -4557,8 +4659,14 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPToolCall/arguments`. public var arguments: Swift.String + /// The output from the tool call. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPToolCall/output`. public var output: Swift.String? + /// The error from the tool call, if any. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPToolCall/error`. public var error: Swift.String? /// The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or `failed`. @@ -4566,6 +4674,10 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPToolCall/status`. public var status: Components.Schemas.MCPToolCallStatus? + /// Unique identifier for the MCP tool call approval request. + /// Include this value in a subsequent `mcp_approval_response` input to approve or reject the corresponding tool call. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPToolCall/approval_request_id`. public var approvalRequestId: Swift.String? /// Creates a new `MCPToolCall`. @@ -4576,10 +4688,10 @@ public enum Components { /// - serverLabel: The label of the MCP server running the tool. /// - name: The name of the tool that was run. /// - arguments: A JSON string of the arguments passed to the tool. - /// - output: - /// - error: + /// - output: The output from the tool call. + /// - error: The error from the tool call, if any. /// - status: The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or `failed`. - /// - approvalRequestId: + /// - approvalRequestId: Unique identifier for the MCP tool call approval request. public init( _type: Components.Schemas.MCPToolCall._TypePayload, id: Swift.String, @@ -4893,10 +5005,28 @@ public enum Components { public struct ModelResponseProperties: Codable, Hashable, Sendable { /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/metadata`. public var metadata: Components.Schemas.Metadata? + /// An integer between 0 and 20 specifying the maximum number of most likely + /// tokens to return at each token position, each with an associated log + /// probability. In some cases, the number of returned tokens may be fewer than + /// requested. + /// + /// /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/top_logprobs`. public var topLogprobs: Swift.Int? + /// 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. + /// We generally recommend altering this or `top_p` but not both. + /// + /// /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/temperature`. public var temperature: Swift.Double? + /// 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. + /// + /// We generally recommend altering this or `temperature` but not both. + /// + /// /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/top_p`. public var topP: Swift.Double? /// This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations. @@ -4928,20 +5058,23 @@ public enum Components { case inMemory = "in_memory" case _24h = "24h" } + /// 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). + /// + /// /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/prompt_cache_retention`. public var promptCacheRetention: Components.Schemas.ModelResponseProperties.PromptCacheRetentionPayload? /// Creates a new `ModelResponseProperties`. /// /// - Parameters: /// - metadata: - /// - topLogprobs: - /// - temperature: - /// - topP: + /// - topLogprobs: An integer between 0 and 20 specifying the maximum number of most likely + /// - temperature: 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. + /// - topP: An alternative to sampling with temperature, called nucleus sampling, /// - user: This field is being replaced by `safety_identifier` and `prompt_cache_key`. Use `prompt_cache_key` instead to maintain caching optimizations. /// - safetyIdentifier: A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies. /// - promptCacheKey: 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). /// - serviceTier: - /// - promptCacheRetention: + /// - promptCacheRetention: 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). public init( metadata: Components.Schemas.Metadata? = nil, topLogprobs: Swift.Int? = nil, @@ -5086,13 +5219,13 @@ public enum Components { self = .fileSearchToolCall(try .init(from: decoder)) case "FunctionToolCall", "#/components/schemas/FunctionToolCall", "function_call": self = .functionToolCall(try .init(from: decoder)) - case "FunctionToolCallOutputResource", "#/components/schemas/FunctionToolCallOutputResource": + case "FunctionToolCallOutputResource", "#/components/schemas/FunctionToolCallOutputResource", "function_call_output": self = .functionToolCallOutputResource(try .init(from: decoder)) case "WebSearchToolCall", "#/components/schemas/WebSearchToolCall", "web_search_call": self = .webSearchToolCall(try .init(from: decoder)) case "ComputerToolCall", "#/components/schemas/ComputerToolCall", "computer_call": self = .computerToolCall(try .init(from: decoder)) - case "ComputerToolCallOutputResource", "#/components/schemas/ComputerToolCallOutputResource": + case "ComputerToolCallOutputResource", "#/components/schemas/ComputerToolCallOutputResource", "computer_call_output": self = .computerToolCallOutputResource(try .init(from: decoder)) case "ReasoningItem", "#/components/schemas/ReasoningItem", "reasoning": self = .reasoningItem(try .init(from: decoder)) @@ -5128,7 +5261,7 @@ public enum Components { self = .mcpApprovalResponseResource(try .init(from: decoder)) case "CustomToolCall", "#/components/schemas/CustomToolCall", "custom_tool_call": self = .customToolCall(try .init(from: decoder)) - case "CustomToolCallOutputResource", "#/components/schemas/CustomToolCallOutputResource": + case "CustomToolCallOutputResource", "#/components/schemas/CustomToolCallOutputResource", "custom_tool_call_output": self = .customToolCallOutputResource(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -5232,8 +5365,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/OutputMessage/content`. public var content: [Components.Schemas.OutputMessageContent] - /// - Remark: Generated from `#/components/schemas/MessagePhase`. - public typealias MessagePhase = Components.Schemas.MessagePhase /// - Remark: Generated from `#/components/schemas/OutputMessage/phase`. public var phase: Components.Schemas.MessagePhase? /// The status of the message input. One of `in_progress`, `completed`, or @@ -5332,6 +5463,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/Prompt/id`. public var id: Swift.String + /// Optional version of the prompt template. + /// /// - Remark: Generated from `#/components/schemas/Prompt/version`. public var version: Swift.String? /// - Remark: Generated from `#/components/schemas/Prompt/variables`. @@ -5340,7 +5473,7 @@ public enum Components { /// /// - Parameters: /// - id: The unique identifier of the prompt template to use. - /// - version: + /// - version: Optional version of the prompt template. /// - variables: public init( id: Swift.String, @@ -5380,6 +5513,13 @@ public enum Components { case concise = "concise" case detailed = "detailed" } + /// A summary of the reasoning performed by the model. This can be + /// useful for debugging and understanding the model's reasoning process. + /// One of `auto`, `concise`, or `detailed`. + /// + /// `concise` is supported for `computer-use-preview` models and all reasoning models after `gpt-5`. + /// + /// /// - Remark: Generated from `#/components/schemas/Reasoning/summary`. public var summary: Components.Schemas.Reasoning.SummaryPayload? /// **Deprecated:** use `summary` instead. @@ -5395,14 +5535,22 @@ public enum Components { case concise = "concise" case detailed = "detailed" } + /// **Deprecated:** use `summary` instead. + /// + /// A summary of the reasoning performed by the model. This can be + /// useful for debugging and understanding the model's reasoning process. + /// One of `auto`, `concise`, or `detailed`. + /// + /// /// - Remark: Generated from `#/components/schemas/Reasoning/generate_summary`. + @available(*, deprecated) public var generateSummary: Components.Schemas.Reasoning.GenerateSummaryPayload? /// Creates a new `Reasoning`. /// /// - Parameters: /// - effort: - /// - summary: - /// - generateSummary: + /// - summary: A summary of the reasoning performed by the model. This can be + /// - generateSummary: **Deprecated:** use `summary` instead. public init( effort: Components.Schemas.ReasoningEffort? = nil, summary: Components.Schemas.Reasoning.SummaryPayload? = nil, @@ -5464,6 +5612,10 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ReasoningItem/id`. public var id: Swift.String + /// The encrypted content of the reasoning item - populated when a response is + /// generated with `reasoning.encrypted_content` in the `include` parameter. + /// + /// /// - Remark: Generated from `#/components/schemas/ReasoningItem/encrypted_content`. public var encryptedContent: Swift.String? /// Reasoning summary content. @@ -5497,7 +5649,7 @@ public enum Components { /// - Parameters: /// - _type: The type of the object. Always `reasoning`. /// - id: The unique identifier of the reasoning content. - /// - encryptedContent: + /// - encryptedContent: The encrypted content of the reasoning item - populated when a response is /// - summary: Reasoning summary content. /// - content: Reasoning text content. /// - status: The status of the item. One of `in_progress`, `completed`, or @@ -5574,6 +5726,10 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/Response/value3/created_at`. public var createdAt: Swift.Double + /// Unix timestamp (in seconds) of when this Response was completed. + /// Only present when the status is `completed`. + /// + /// /// - Remark: Generated from `#/components/schemas/Response/value3/completed_at`. public var completedAt: Swift.Double? /// - Remark: Generated from `#/components/schemas/Response/value3/error`. @@ -5605,6 +5761,9 @@ public enum Components { case reason } } + /// Details about why the response is incomplete. + /// + /// /// - Remark: Generated from `#/components/schemas/Response/value3/incomplete_details`. public var incompleteDetails: Components.Schemas.Response.Value3Payload.IncompleteDetailsPayload? /// An array of content items generated by the model. @@ -5669,8 +5828,20 @@ public enum Components { } } } + /// A system (or developer) message inserted into the model's context. + /// + /// When using 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. + /// + /// /// - Remark: Generated from `#/components/schemas/Response/value3/instructions`. public var instructions: Components.Schemas.Response.Value3Payload.InstructionsPayload? + /// SDK-only convenience property that contains the aggregated text output + /// from all `output_text` items in the `output` array, if any are present. + /// Supported in the Python and JavaScript SDKs. + /// + /// /// - Remark: Generated from `#/components/schemas/Response/value3/output_text`. public var outputText: Swift.String? /// - Remark: Generated from `#/components/schemas/Response/value3/usage`. @@ -5680,10 +5851,11 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/Response/value3/parallel_tool_calls`. public var parallelToolCalls: Swift.Bool - /// - Remark: Generated from `#/components/schemas/Conversation-2`. - public typealias Conversation2 = Components.Schemas.Conversation2 /// - Remark: Generated from `#/components/schemas/Response/value3/conversation`. public var conversation: Components.Schemas.Conversation2? + /// 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). + /// + /// /// - Remark: Generated from `#/components/schemas/Response/value3/max_output_tokens`. public var maxOutputTokens: Swift.Int? /// Creates a new `Value3Payload`. @@ -5693,16 +5865,16 @@ public enum Components { /// - object: The object type of this resource - always set to `response`. /// - status: The status of the response generation. One of `completed`, `failed`, /// - createdAt: Unix timestamp (in seconds) of when this Response was created. - /// - completedAt: + /// - completedAt: Unix timestamp (in seconds) of when this Response was completed. /// - error: - /// - incompleteDetails: + /// - incompleteDetails: Details about why the response is incomplete. /// - output: An array of content items generated by the model. - /// - instructions: - /// - outputText: + /// - instructions: A system (or developer) message inserted into the model's context. + /// - outputText: SDK-only convenience property that contains the aggregated text output /// - usage: /// - parallelToolCalls: Whether to allow the model to run tool calls in parallel. /// - conversation: - /// - maxOutputTokens: + /// - maxOutputTokens: 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). public init( id: Swift.String, object: Components.Schemas.Response.Value3Payload.ObjectPayload, @@ -6646,6 +6818,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/type`. public var _type: Components.Schemas.ResponseErrorEvent._TypePayload + /// The error code. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/code`. public var code: Swift.String? /// The error message. @@ -6653,6 +6828,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/message`. public var message: Swift.String + /// The error parameter. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/param`. public var param: Swift.String? /// The sequence number of this event. @@ -6663,9 +6841,9 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `error`. - /// - code: + /// - code: The error code. /// - message: The error message. - /// - param: + /// - param: The error parameter. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseErrorEvent._TypePayload, @@ -8256,6 +8434,11 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/ResponseProperties`. public struct ResponseProperties: Codable, Hashable, Sendable { + /// 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`. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseProperties/previous_response_id`. public var previousResponseId: Swift.String? /// Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI @@ -8266,12 +8449,17 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseProperties/model`. public var model: Components.Schemas.ModelIdsResponses? - /// - Remark: Generated from `#/components/schemas/Reasoning`. - public typealias Reasoning = Components.Schemas.Reasoning /// - Remark: Generated from `#/components/schemas/ResponseProperties/reasoning`. public var reasoning: Components.Schemas.Reasoning? + /// Whether to run the model response in the background. + /// [Learn more](/docs/guides/background). + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseProperties/background`. public var background: Swift.Bool? + /// 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. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseProperties/max_tool_calls`. public var maxToolCalls: Swift.Int? /// - Remark: Generated from `#/components/schemas/ResponseProperties/text`. @@ -8295,21 +8483,29 @@ public enum Components { case auto = "auto" case disabled = "disabled" } + /// 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. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseProperties/truncation`. public var truncation: Components.Schemas.ResponseProperties.TruncationPayload? /// Creates a new `ResponseProperties`. /// /// - Parameters: - /// - previousResponseId: + /// - previousResponseId: The unique ID of the previous response to the model. Use this to /// - model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI /// - reasoning: - /// - background: - /// - maxToolCalls: + /// - background: Whether to run the model response in the background. + /// - maxToolCalls: 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. /// - text: /// - tools: /// - toolChoice: /// - prompt: - /// - truncation: + /// - truncation: The truncation strategy to use for the model response. public init( previousResponseId: Swift.String? = nil, model: Components.Schemas.ModelIdsResponses? = nil, @@ -10298,6 +10494,13 @@ public enum Components { public var name: Swift.String /// - Remark: Generated from `#/components/schemas/TextResponseFormatJsonSchema/schema`. public var schema: Components.Schemas.ResponseFormatJsonSchemaSchema + /// Whether to enable strict schema adherence when generating the output. + /// If set to true, the model will always follow the exact schema defined + /// in the `schema` field. Only a subset of JSON Schema is supported when + /// `strict` is `true`. To learn more, read the [Structured Outputs + /// guide](/docs/guides/structured-outputs). + /// + /// /// - Remark: Generated from `#/components/schemas/TextResponseFormatJsonSchema/strict`. public var strict: Swift.Bool? /// Creates a new `TextResponseFormatJsonSchema`. @@ -10307,7 +10510,7 @@ public enum Components { /// - description: A description of what the response format is for, used by the model to /// - name: The name of the response format. Must be a-z, A-Z, 0-9, or contain /// - schema: - /// - strict: + /// - strict: Whether to enable strict schema adherence when generating the output. public init( _type: Components.Schemas.TextResponseFormatJsonSchema._TypePayload, description: Swift.String? = nil, @@ -10647,6 +10850,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolChoiceMCP/server_label`. public var serverLabel: Swift.String + /// The name of the tool to call on the server. + /// + /// /// - Remark: Generated from `#/components/schemas/ToolChoiceMCP/name`. public var name: Swift.String? /// Creates a new `ToolChoiceMCP`. @@ -10654,7 +10860,7 @@ public enum Components { /// - Parameters: /// - _type: For MCP tools, the type is always `mcp`. /// - serverLabel: The label of the MCP server to use. - /// - name: + /// - name: The name of the tool to call on the server. public init( _type: Components.Schemas.ToolChoiceMCP._TypePayload, serverLabel: Swift.String, @@ -11678,8 +11884,6 @@ public enum Components { public var _type: Components.Schemas.WebSearchActionOpenPage._TypePayload /// The URL opened by the model. /// - /// The URL opened by the model. - /// /// /// - Remark: Generated from `#/components/schemas/WebSearchActionOpenPage/url`. public var url: Swift.String? @@ -11816,22 +12020,30 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/type`. public var _type: Components.Schemas.WebSearchApproximateLocation._TypePayload? + /// The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`. + /// /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/country`. public var country: Swift.String? + /// Free text input for the region of the user, e.g. `California`. + /// /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/region`. public var region: Swift.String? + /// Free text input for the city of the user, e.g. `San Francisco`. + /// /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/city`. public var city: Swift.String? + /// The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`. + /// /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/timezone`. public var timezone: Swift.String? /// Creates a new `WebSearchApproximateLocation`. /// /// - Parameters: /// - _type: The type of location approximation. Always `approximate`. - /// - country: - /// - region: - /// - city: - /// - timezone: + /// - country: The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`. + /// - region: Free text input for the region of the user, e.g. `California`. + /// - city: Free text input for the city of the user, e.g. `San Francisco`. + /// - timezone: The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`. public init( _type: Components.Schemas.WebSearchApproximateLocation._TypePayload? = nil, country: Swift.String? = nil, @@ -11937,12 +12149,18 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/WebSearchTool/filters`. public struct FiltersPayload: Codable, Hashable, Sendable { + /// Allowed domains for the search. If not provided, all domains are allowed. + /// Subdomains of the provided domains are allowed as well. + /// + /// Example: `["pubmed.ncbi.nlm.nih.gov"]` + /// + /// /// - Remark: Generated from `#/components/schemas/WebSearchTool/filters/allowed_domains`. public var allowedDomains: [Swift.String]? /// Creates a new `FiltersPayload`. /// /// - Parameters: - /// - allowedDomains: + /// - allowedDomains: Allowed domains for the search. If not provided, all domains are allowed. public init(allowedDomains: [Swift.String]? = nil) { self.allowedDomains = allowedDomains } @@ -11950,6 +12168,9 @@ public enum Components { case allowedDomains = "allowed_domains" } } + /// Filters for the search. + /// + /// /// - Remark: Generated from `#/components/schemas/WebSearchTool/filters`. public var filters: Components.Schemas.WebSearchTool.FiltersPayload? /// - Remark: Generated from `#/components/schemas/WebSearchTool/user_location`. @@ -11970,7 +12191,7 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. - /// - filters: + /// - filters: Filters for the search. /// - userLocation: /// - searchContextSize: 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. public init( @@ -12872,8 +13093,12 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/InputImageContent/type`. public var _type: Components.Schemas.InputImageContent._TypePayload + /// The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL. + /// /// - Remark: Generated from `#/components/schemas/InputImageContent/image_url`. public var imageUrl: Swift.String? + /// The ID of the file to be sent to the model. + /// /// - Remark: Generated from `#/components/schemas/InputImageContent/file_id`. public var fileId: Swift.String? /// The detail level of the image to be sent to the model. One of `high`, `low`, `auto`, or `original`. Defaults to `auto`. @@ -12884,8 +13109,8 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the input item. Always `input_image`. - /// - imageUrl: - /// - fileId: + /// - imageUrl: The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL. + /// - fileId: The ID of the file to be sent to the model. /// - detail: The detail level of the image to be sent to the model. One of `high`, `low`, `auto`, or `original`. Defaults to `auto`. public init( _type: Components.Schemas.InputImageContent._TypePayload, @@ -12924,6 +13149,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/InputFileContent/type`. public var _type: Components.Schemas.InputFileContent._TypePayload + /// The ID of the file to be sent to the model. + /// /// - Remark: Generated from `#/components/schemas/InputFileContent/file_id`. public var fileId: Swift.String? /// The name of the file to be sent to the model. @@ -12947,7 +13174,7 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the input item. Always `input_file`. - /// - fileId: + /// - fileId: The ID of the file to be sent to the model. /// - filename: The name of the file to be sent to the model. /// - fileData: The content of the file to be sent to the model. /// - fileUrl: The URL of the file to be sent to the model. @@ -13022,6 +13249,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ClickParam/y`. public var y: Swift.Int + /// The keys being held while clicking. + /// /// - Remark: Generated from `#/components/schemas/ClickParam/keys`. public var keys: [Swift.String]? /// Creates a new `ClickParam`. @@ -13031,7 +13260,7 @@ public enum Components { /// - button: Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`. /// - x: The x-coordinate where the click occurred. /// - y: The y-coordinate where the click occurred. - /// - keys: + /// - keys: The keys being held while clicking. public init( _type: Components.Schemas.ClickParam._TypePayload, button: Components.Schemas.ClickButtonType, @@ -13075,6 +13304,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/DoubleClickAction/y`. public var y: Swift.Int + /// The keys being held while double-clicking. + /// /// - Remark: Generated from `#/components/schemas/DoubleClickAction/keys`. public var keys: [Swift.String]? /// Creates a new `DoubleClickAction`. @@ -13083,7 +13314,7 @@ public enum Components { /// - _type: Specifies the event type. For a double click action, this property is always set to `double_click`. /// - x: The x-coordinate where the double click occurred. /// - y: The y-coordinate where the double click occurred. - /// - keys: + /// - keys: The keys being held while double-clicking. public init( _type: Components.Schemas.DoubleClickAction._TypePayload, x: Swift.Int, @@ -13155,6 +13386,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/DragParam/path`. public var path: [Components.Schemas.CoordParam] + /// The keys being held while dragging the mouse. + /// /// - Remark: Generated from `#/components/schemas/DragParam/keys`. public var keys: [Swift.String]? /// Creates a new `DragParam`. @@ -13162,7 +13395,7 @@ public enum Components { /// - Parameters: /// - _type: Specifies the event type. For a drag action, this property is always set to `drag`. /// - path: An array of coordinates representing the path of the drag action. Coordinates will appear as an array of objects, eg - /// - keys: + /// - keys: The keys being held while dragging the mouse. public init( _type: Components.Schemas.DragParam._TypePayload, path: [Components.Schemas.CoordParam], @@ -13235,6 +13468,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MoveParam/y`. public var y: Swift.Int + /// The keys being held while moving the mouse. + /// /// - Remark: Generated from `#/components/schemas/MoveParam/keys`. public var keys: [Swift.String]? /// Creates a new `MoveParam`. @@ -13243,7 +13478,7 @@ public enum Components { /// - _type: Specifies the event type. For a move action, this property is always set to `move`. /// - x: The x-coordinate to move to. /// - y: The y-coordinate to move to. - /// - keys: + /// - keys: The keys being held while moving the mouse. public init( _type: Components.Schemas.MoveParam._TypePayload, x: Swift.Int, @@ -13317,6 +13552,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ScrollParam/scroll_y`. public var scrollY: Swift.Int + /// The keys being held while scrolling. + /// /// - Remark: Generated from `#/components/schemas/ScrollParam/keys`. public var keys: [Swift.String]? /// Creates a new `ScrollParam`. @@ -13327,7 +13564,7 @@ public enum Components { /// - y: The y-coordinate where the scroll occurred. /// - scrollX: The horizontal scroll distance. /// - scrollY: The vertical scroll distance. - /// - keys: + /// - keys: The keys being held while scrolling. public init( _type: Components.Schemas.ScrollParam._TypePayload, x: Swift.Int, @@ -13420,16 +13657,20 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/id`. public var id: Swift.String + /// The type of the pending safety check. + /// /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/code`. public var code: Swift.String? + /// Details about the pending safety check. + /// /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/message`. public var message: Swift.String? /// Creates a new `ComputerCallSafetyCheckParam`. /// /// - Parameters: /// - id: The ID of the pending safety check. - /// - code: - /// - message: + /// - code: The type of the pending safety check. + /// - message: Details about the pending safety check. public init( id: Swift.String, code: Swift.String? = nil, @@ -13472,6 +13713,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolSearchCall/id`. public var id: Swift.String + /// The unique ID of the tool search call generated by the model. + /// /// - Remark: Generated from `#/components/schemas/ToolSearchCall/call_id`. public var callId: Swift.String? /// Whether tool search was executed by the server or by the client. @@ -13495,7 +13738,7 @@ public enum Components { /// - Parameters: /// - _type: The type of the item. Always `tool_search_call`. /// - id: The unique ID of the tool search call item. - /// - callId: + /// - callId: The unique ID of the tool search call generated by the model. /// - execution: Whether tool search was executed by the server or by the client. /// - arguments: Arguments used for the tool search call. /// - status: The status of the tool search call item that was recorded. @@ -13545,6 +13788,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionTool/name`. public var name: Swift.String + /// A description of the function. Used by the model to determine whether or not to call the function. + /// /// - Remark: Generated from `#/components/schemas/FunctionTool/description`. public var description: Swift.String? /// A JSON schema object describing the parameters of the function. @@ -13567,8 +13812,12 @@ public enum Components { try encoder.encodeAdditionalProperties(additionalProperties) } } + /// A JSON schema object describing the parameters of the function. + /// /// - Remark: Generated from `#/components/schemas/FunctionTool/parameters`. public var parameters: Components.Schemas.FunctionTool.ParametersPayload? + /// Whether to enforce strict parameter validation. Default `true`. + /// /// - Remark: Generated from `#/components/schemas/FunctionTool/strict`. public var strict: Swift.Bool? /// Whether this function is deferred and loaded via tool search. @@ -13580,9 +13829,9 @@ public enum Components { /// - Parameters: /// - _type: The type of the function tool. Always `function`. /// - name: The name of the function to call. - /// - description: - /// - parameters: - /// - strict: + /// - description: A description of the function. Used by the model to determine whether or not to call the function. + /// - parameters: A JSON schema object describing the parameters of the function. + /// - strict: Whether to enforce strict parameter validation. Default `true`. /// - deferLoading: Whether this function is deferred and loaded via tool search. public init( _type: Components.Schemas.FunctionTool._TypePayload, @@ -13746,8 +13995,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FileSearchTool/ranking_options`. public var rankingOptions: Components.Schemas.RankingOptions? - /// - Remark: Generated from `#/components/schemas/Filters`. - public typealias Filters = Components.Schemas.Filters /// - Remark: Generated from `#/components/schemas/FileSearchTool/filters`. public var filters: Components.Schemas.Filters? /// Creates a new `FileSearchTool`. @@ -13888,8 +14135,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/AutoCodeInterpreterToolParam/file_ids`. public var fileIds: [Swift.String]? - /// - Remark: Generated from `#/components/schemas/ContainerMemoryLimit`. - public typealias ContainerMemoryLimit = Components.Schemas.ContainerMemoryLimit /// - Remark: Generated from `#/components/schemas/AutoCodeInterpreterToolParam/memory_limit`. public var memoryLimit: Components.Schemas.ContainerMemoryLimit? /// Network access policy for the container. @@ -14014,8 +14259,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/file_ids`. public var fileIds: [Swift.String]? - /// - Remark: Generated from `#/components/schemas/ContainerMemoryLimit`. - public typealias ContainerMemoryLimit = Components.Schemas.ContainerMemoryLimit /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/memory_limit`. public var memoryLimit: Components.Schemas.ContainerMemoryLimit? /// Network access policy for the container. @@ -14491,8 +14734,6 @@ public enum Components { public var name: Swift.String /// - Remark: Generated from `#/components/schemas/FunctionToolParam/description`. public var description: Swift.String? - /// - Remark: Generated from `#/components/schemas/EmptyModelParam`. - public typealias EmptyModelParam = Components.Schemas.EmptyModelParam /// - Remark: Generated from `#/components/schemas/FunctionToolParam/parameters`. public var parameters: Components.Schemas.EmptyModelParam? /// - Remark: Generated from `#/components/schemas/FunctionToolParam/strict`. @@ -14652,10 +14893,10 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolSearchToolParam/execution`. public var execution: Components.Schemas.ToolSearchExecutionType? + /// Description shown to the model for a client-executed tool search tool. + /// /// - Remark: Generated from `#/components/schemas/ToolSearchToolParam/description`. public var description: Swift.String? - /// - Remark: Generated from `#/components/schemas/EmptyModelParam`. - public typealias EmptyModelParam = Components.Schemas.EmptyModelParam /// - Remark: Generated from `#/components/schemas/ToolSearchToolParam/parameters`. public var parameters: Components.Schemas.EmptyModelParam? /// Creates a new `ToolSearchToolParam`. @@ -14663,7 +14904,7 @@ public enum Components { /// - Parameters: /// - _type: The type of the tool. Always `tool_search`. /// - execution: Whether tool search is executed by the server or by the client. - /// - description: + /// - description: Description shown to the model for a client-executed tool search tool. /// - parameters: public init( _type: Components.Schemas.ToolSearchToolParam._TypePayload, @@ -14695,22 +14936,30 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApproximateLocation/type`. public var _type: Components.Schemas.ApproximateLocation._TypePayload + /// The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`. + /// /// - Remark: Generated from `#/components/schemas/ApproximateLocation/country`. public var country: Swift.String? + /// Free text input for the region of the user, e.g. `California`. + /// /// - Remark: Generated from `#/components/schemas/ApproximateLocation/region`. public var region: Swift.String? + /// Free text input for the city of the user, e.g. `San Francisco`. + /// /// - Remark: Generated from `#/components/schemas/ApproximateLocation/city`. public var city: Swift.String? + /// The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`. + /// /// - Remark: Generated from `#/components/schemas/ApproximateLocation/timezone`. public var timezone: Swift.String? /// Creates a new `ApproximateLocation`. /// /// - Parameters: /// - _type: The type of location approximation. Always `approximate`. - /// - country: - /// - region: - /// - city: - /// - timezone: + /// - country: The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`. + /// - region: Free text input for the region of the user, e.g. `California`. + /// - city: Free text input for the city of the user, e.g. `San Francisco`. + /// - timezone: The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`. public init( _type: Components.Schemas.ApproximateLocation._TypePayload, country: Swift.String? = nil, @@ -14758,8 +15007,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/type`. public var _type: Components.Schemas.WebSearchPreviewTool._TypePayload - /// - Remark: Generated from `#/components/schemas/ApproximateLocation`. - public typealias ApproximateLocation = Components.Schemas.ApproximateLocation /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/user_location`. public var userLocation: Components.Schemas.ApproximateLocation? /// 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. @@ -14834,6 +15081,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/id`. public var id: Swift.String + /// The unique ID of the tool search call generated by the model. + /// /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/call_id`. public var callId: Swift.String? /// Whether tool search was executed by the server or by the client. @@ -14857,7 +15106,7 @@ public enum Components { /// - Parameters: /// - _type: The type of the item. Always `tool_search_output`. /// - id: The unique ID of the tool search output item. - /// - callId: + /// - callId: The unique ID of the tool search call generated by the model. /// - execution: Whether tool search was executed by the server or by the client. /// - tools: The loaded tool definitions returned by tool search. /// - status: The status of the tool search output item that was recorded. @@ -15028,8 +15277,12 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/command`. public var command: [Swift.String] + /// Optional timeout in milliseconds for the command. + /// /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/timeout_ms`. public var timeoutMs: Swift.Int? + /// Optional working directory to run the command in. + /// /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/working_directory`. public var workingDirectory: Swift.String? /// Environment variables to set for the command. @@ -15056,6 +15309,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/env`. public var env: Components.Schemas.LocalShellExecAction.EnvPayload + /// Optional user to run the command as. + /// /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/user`. public var user: Swift.String? /// Creates a new `LocalShellExecAction`. @@ -15063,10 +15318,10 @@ public enum Components { /// - Parameters: /// - _type: The type of the local shell action. Always `exec`. /// - command: The command to run. - /// - timeoutMs: - /// - workingDirectory: + /// - timeoutMs: Optional timeout in milliseconds for the command. + /// - workingDirectory: Optional working directory to run the command in. /// - env: Environment variables to set for the command. - /// - user: + /// - user: Optional user to run the command as. public init( _type: Components.Schemas.LocalShellExecAction._TypePayload, command: [Swift.String], @@ -15097,16 +15352,20 @@ public enum Components { public struct FunctionShellAction: Codable, Hashable, Sendable { /// - Remark: Generated from `#/components/schemas/FunctionShellAction/commands`. public var commands: [Swift.String] + /// Optional timeout in milliseconds for the commands. + /// /// - Remark: Generated from `#/components/schemas/FunctionShellAction/timeout_ms`. public var timeoutMs: Swift.Int? + /// Optional maximum number of characters to return from each command. + /// /// - Remark: Generated from `#/components/schemas/FunctionShellAction/max_output_length`. public var maxOutputLength: Swift.Int? /// Creates a new `FunctionShellAction`. /// /// - Parameters: /// - commands: - /// - timeoutMs: - /// - maxOutputLength: + /// - timeoutMs: Optional timeout in milliseconds for the commands. + /// - maxOutputLength: Optional maximum number of characters to return from each command. public init( commands: [Swift.String], timeoutMs: Swift.Int? = nil, @@ -15476,6 +15735,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/output`. public var output: [Components.Schemas.FunctionShellCallOutputContent] + /// The maximum length of the shell command output. This is generated by the model and should be passed back with the raw output. + /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/max_output_length`. public var maxOutputLength: Swift.Int? /// The identifier of the actor that created the item. @@ -15490,7 +15751,7 @@ public enum Components { /// - callId: The unique ID of the shell tool call generated by the model. /// - status: The status of the shell call output. One of `in_progress`, `completed`, or `incomplete`. /// - output: An array of shell call output contents - /// - maxOutputLength: + /// - maxOutputLength: The maximum length of the shell command output. This is generated by the model and should be passed back with the raw output. /// - createdBy: The identifier of the actor that created the item. public init( _type: Components.Schemas.FunctionShellCallOutput._TypePayload, @@ -15788,6 +16049,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/status`. public var status: Components.Schemas.ApplyPatchCallOutputStatus + /// Optional textual output returned by the apply patch tool. + /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/output`. public var output: Swift.String? /// The ID of the entity that created this tool call output. @@ -15801,7 +16064,7 @@ public enum Components { /// - id: The unique ID of the apply patch tool call output. Populated when this item is returned via API. /// - callId: The unique ID of the apply patch tool call generated by the model. /// - status: The status of the apply patch tool call output. One of `completed` or `failed`. - /// - output: + /// - output: Optional textual output returned by the apply patch tool. /// - createdBy: The ID of the entity that created this tool call output. public init( _type: Components.Schemas.ApplyPatchToolCallOutput._TypePayload, @@ -15852,6 +16115,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam`. public struct ComputerCallOutputItemParam: Codable, Hashable, Sendable { + /// The ID of the computer tool call output. + /// /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/id`. public var id: Swift.String? /// The ID of the computer tool call that produced the output. @@ -15870,22 +16135,20 @@ public enum Components { public var _type: Components.Schemas.ComputerCallOutputItemParam._TypePayload /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/output`. public var output: Components.Schemas.ComputerScreenshotImage - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam`. - public typealias ComputerCallSafetyCheckParam = [Components.Schemas.ComputerCallSafetyCheckParam] + /// The safety checks reported by the API that have been acknowledged by the developer. + /// /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/acknowledged_safety_checks`. public var acknowledgedSafetyChecks: [Components.Schemas.ComputerCallSafetyCheckParam]? - /// - Remark: Generated from `#/components/schemas/FunctionCallItemStatus`. - public typealias FunctionCallItemStatus = Components.Schemas.FunctionCallItemStatus /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/status`. public var status: Components.Schemas.FunctionCallItemStatus? /// Creates a new `ComputerCallOutputItemParam`. /// /// - Parameters: - /// - id: + /// - id: The ID of the computer tool call output. /// - callId: The ID of the computer tool call that produced the output. /// - _type: The type of the computer tool call output. Always `computer_call_output`. /// - output: - /// - acknowledgedSafetyChecks: + /// - acknowledgedSafetyChecks: The safety checks reported by the API that have been acknowledged by the developer. /// - status: public init( id: Swift.String? = nil, @@ -15960,20 +16223,22 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/type`. public var _type: Components.Schemas.InputImageContentParamAutoParam._TypePayload + /// The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL. + /// /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/image_url`. public var imageUrl: Swift.String? + /// The ID of the file to be sent to the model. + /// /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/file_id`. public var fileId: Swift.String? - /// - Remark: Generated from `#/components/schemas/DetailEnum`. - public typealias DetailEnum = Components.Schemas.DetailEnum /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/detail`. public var detail: Components.Schemas.DetailEnum? /// Creates a new `InputImageContentParamAutoParam`. /// /// - Parameters: /// - _type: The type of the input item. Always `input_image`. - /// - imageUrl: - /// - fileId: + /// - imageUrl: The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL. + /// - fileId: The ID of the file to be sent to the model. /// - detail: public init( _type: Components.Schemas.InputImageContentParamAutoParam._TypePayload, @@ -16012,12 +16277,20 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/InputFileContentParam/type`. public var _type: Components.Schemas.InputFileContentParam._TypePayload + /// The ID of the file to be sent to the model. + /// /// - Remark: Generated from `#/components/schemas/InputFileContentParam/file_id`. public var fileId: Swift.String? + /// The name of the file to be sent to the model. + /// /// - Remark: Generated from `#/components/schemas/InputFileContentParam/filename`. public var filename: Swift.String? + /// The base64-encoded data of the file to be sent to the model. + /// /// - Remark: Generated from `#/components/schemas/InputFileContentParam/file_data`. public var fileData: Swift.String? + /// The URL of the file to be sent to the model. + /// /// - Remark: Generated from `#/components/schemas/InputFileContentParam/file_url`. public var fileUrl: Swift.String? /// 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`. @@ -16028,10 +16301,10 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the input item. Always `input_file`. - /// - fileId: - /// - filename: - /// - fileData: - /// - fileUrl: + /// - fileId: The ID of the file to be sent to the model. + /// - filename: The name of the file to be sent to the model. + /// - fileData: The base64-encoded data of the file to be sent to the model. + /// - fileUrl: The URL of the file to be sent to the model. /// - detail: 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`. public init( _type: Components.Schemas.InputFileContentParam._TypePayload, @@ -16061,6 +16334,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam`. public struct FunctionCallOutputItemParam: Codable, Hashable, Sendable { + /// The unique ID of the function tool call output. Populated when this item is returned via API. + /// /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/id`. public var id: Swift.String? /// The unique ID of the function tool call generated by the model. @@ -16171,14 +16446,12 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output`. public var output: Components.Schemas.FunctionCallOutputItemParam.OutputPayload - /// - Remark: Generated from `#/components/schemas/FunctionCallItemStatus`. - public typealias FunctionCallItemStatus = Components.Schemas.FunctionCallItemStatus /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/status`. public var status: Components.Schemas.FunctionCallItemStatus? /// Creates a new `FunctionCallOutputItemParam`. /// /// - Parameters: - /// - id: + /// - id: The unique ID of the function tool call output. Populated when this item is returned via API. /// - callId: The unique ID of the function tool call generated by the model. /// - _type: The type of the function tool call output. Always `function_call_output`. /// - output: Text, image, or file output of the function tool call. @@ -16206,8 +16479,12 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam`. public struct ToolSearchCallItemParam: Codable, Hashable, Sendable { + /// The unique ID of this tool search call. + /// /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/id`. public var id: Swift.String? + /// The unique ID of the tool search call generated by the model. + /// /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/call_id`. public var callId: Swift.String? /// The item type. Always `tool_search_call`. @@ -16228,15 +16505,13 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/arguments`. public var arguments: Components.Schemas.EmptyModelParam - /// - Remark: Generated from `#/components/schemas/FunctionCallItemStatus`. - public typealias FunctionCallItemStatus = Components.Schemas.FunctionCallItemStatus /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/status`. public var status: Components.Schemas.FunctionCallItemStatus? /// Creates a new `ToolSearchCallItemParam`. /// /// - Parameters: - /// - id: - /// - callId: + /// - id: The unique ID of this tool search call. + /// - callId: The unique ID of the tool search call generated by the model. /// - _type: The item type. Always `tool_search_call`. /// - execution: Whether tool search was executed by the server or by the client. /// - arguments: The arguments supplied to the tool search call. @@ -16267,8 +16542,12 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam`. public struct ToolSearchOutputItemParam: Codable, Hashable, Sendable { + /// The unique ID of this tool search output. + /// /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/id`. public var id: Swift.String? + /// The unique ID of the tool search call generated by the model. + /// /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/call_id`. public var callId: Swift.String? /// The item type. Always `tool_search_output`. @@ -16289,15 +16568,13 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/tools`. public var tools: [Components.Schemas.Tool] - /// - Remark: Generated from `#/components/schemas/FunctionCallItemStatus`. - public typealias FunctionCallItemStatus = Components.Schemas.FunctionCallItemStatus /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/status`. public var status: Components.Schemas.FunctionCallItemStatus? /// Creates a new `ToolSearchOutputItemParam`. /// /// - Parameters: - /// - id: - /// - callId: + /// - id: The unique ID of this tool search output. + /// - callId: The unique ID of the tool search call generated by the model. /// - _type: The item type. Always `tool_search_output`. /// - execution: Whether tool search was executed by the server or by the client. /// - tools: The loaded tool definitions returned by the tool search output. @@ -16330,6 +16607,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/CompactionSummaryItemParam`. public struct CompactionSummaryItemParam: Codable, Hashable, Sendable { + /// The ID of the compaction item. + /// /// - Remark: Generated from `#/components/schemas/CompactionSummaryItemParam/id`. public var id: Swift.String? /// The type of the item. Always `compaction`. @@ -16349,7 +16628,7 @@ public enum Components { /// Creates a new `CompactionSummaryItemParam`. /// /// - Parameters: - /// - id: + /// - id: The ID of the compaction item. /// - _type: The type of the item. Always `compaction`. /// - encryptedContent: The encrypted content of the compaction summary. public init( @@ -16375,16 +16654,20 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/commands`. public var commands: [Swift.String] + /// Maximum wall-clock time in milliseconds to allow the shell commands to run. + /// /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/timeout_ms`. public var timeoutMs: Swift.Int? + /// Maximum number of UTF-8 characters to capture from combined stdout and stderr output. + /// /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/max_output_length`. public var maxOutputLength: Swift.Int? /// Creates a new `FunctionShellActionParam`. /// /// - Parameters: /// - commands: Ordered shell commands for the execution environment to run. - /// - timeoutMs: - /// - maxOutputLength: + /// - timeoutMs: Maximum wall-clock time in milliseconds to allow the shell commands to run. + /// - maxOutputLength: Maximum number of UTF-8 characters to capture from combined stdout and stderr output. public init( commands: [Swift.String], timeoutMs: Swift.Int? = nil, @@ -16412,6 +16695,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam`. public struct FunctionShellCallItemParam: Codable, Hashable, Sendable { + /// The unique ID of the shell tool call. Populated when this item is returned via API. + /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/id`. public var id: Swift.String? /// The unique ID of the shell tool call generated by the model. @@ -16432,8 +16717,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/action`. public var action: Components.Schemas.FunctionShellActionParam - /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemStatus`. - public typealias FunctionShellCallItemStatus = Components.Schemas.FunctionShellCallItemStatus /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/status`. public var status: Components.Schemas.FunctionShellCallItemStatus? /// The environment to execute the shell commands in. @@ -16475,17 +16758,19 @@ public enum Components { } } } + /// The environment to execute the shell commands in. + /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/environment`. public var environment: Components.Schemas.FunctionShellCallItemParam.EnvironmentPayload? /// Creates a new `FunctionShellCallItemParam`. /// /// - Parameters: - /// - id: + /// - id: The unique ID of the shell tool call. Populated when this item is returned via API. /// - callId: The unique ID of the shell tool call generated by the model. /// - _type: The type of the item. Always `shell_call`. /// - action: The shell commands and limits that describe how to run the tool call. /// - status: - /// - environment: + /// - environment: The environment to execute the shell commands in. public init( id: Swift.String? = nil, callId: Swift.String, @@ -16650,6 +16935,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam`. public struct FunctionShellCallOutputItemParam: Codable, Hashable, Sendable { + /// The unique ID of the shell tool call output. Populated when this item is returned via API. + /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/id`. public var id: Swift.String? /// The unique ID of the shell tool call generated by the model. @@ -16670,21 +16957,21 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/output`. public var output: [Components.Schemas.FunctionShellCallOutputContentParam] - /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemStatus`. - public typealias FunctionShellCallItemStatus = Components.Schemas.FunctionShellCallItemStatus /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/status`. public var status: Components.Schemas.FunctionShellCallItemStatus? + /// The maximum number of UTF-8 characters captured for this shell call's combined output. + /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/max_output_length`. public var maxOutputLength: Swift.Int? /// Creates a new `FunctionShellCallOutputItemParam`. /// /// - Parameters: - /// - id: + /// - id: The unique ID of the shell tool call output. Populated when this item is returned via API. /// - callId: The unique ID of the shell tool call generated by the model. /// - _type: The type of the item. Always `shell_call_output`. /// - output: Captured chunks of stdout and stderr output, along with their associated outcomes. /// - status: - /// - maxOutputLength: + /// - maxOutputLength: The maximum number of UTF-8 characters captured for this shell call's combined output. public init( id: Swift.String? = nil, callId: Swift.String, @@ -16896,6 +17183,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallItemParam/type`. public var _type: Components.Schemas.ApplyPatchToolCallItemParam._TypePayload + /// The unique ID of the apply patch tool call. Populated when this item is returned via API. + /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallItemParam/id`. public var id: Swift.String? /// The unique ID of the apply patch tool call generated by the model. @@ -16914,7 +17203,7 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the item. Always `apply_patch_call`. - /// - id: + /// - id: The unique ID of the apply patch tool call. Populated when this item is returned via API. /// - callId: The unique ID of the apply patch tool call generated by the model. /// - status: The status of the apply patch tool call. One of `in_progress` or `completed`. /// - operation: The specific create, delete, or update instruction for the apply_patch tool call. @@ -16960,6 +17249,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/type`. public var _type: Components.Schemas.ApplyPatchToolCallOutputItemParam._TypePayload + /// The unique ID of the apply patch tool call output. Populated when this item is returned via API. + /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/id`. public var id: Swift.String? /// The unique ID of the apply patch tool call generated by the model. @@ -16970,16 +17261,18 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/status`. public var status: Components.Schemas.ApplyPatchCallOutputStatusParam + /// Optional human-readable log text from the apply patch tool (e.g., patch results or errors). + /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/output`. public var output: Swift.String? /// Creates a new `ApplyPatchToolCallOutputItemParam`. /// /// - Parameters: /// - _type: The type of the item. Always `apply_patch_call_output`. - /// - id: + /// - id: The unique ID of the apply patch tool call output. Populated when this item is returned via API. /// - callId: The unique ID of the apply patch tool call generated by the model. /// - status: The status of the apply patch tool call output. One of `completed` or `failed`. - /// - output: + /// - output: Optional human-readable log text from the apply patch tool (e.g., patch results or errors). public init( _type: Components.Schemas.ApplyPatchToolCallOutputItemParam._TypePayload, id: Swift.String? = nil, @@ -17011,6 +17304,8 @@ public enum Components { @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { case itemReference = "item_reference" } + /// The type of item to reference. Always `item_reference`. + /// /// - Remark: Generated from `#/components/schemas/ItemReferenceParam/type`. public var _type: Components.Schemas.ItemReferenceParam._TypePayload? /// The ID of the item to reference. @@ -17020,7 +17315,7 @@ public enum Components { /// Creates a new `ItemReferenceParam`. /// /// - Parameters: - /// - _type: + /// - _type: The type of item to reference. Always `item_reference`. /// - id: The ID of the item to reference. public init( _type: Components.Schemas.ItemReferenceParam._TypePayload? = nil, @@ -17109,13 +17404,15 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ContextManagementParam/type`. public var _type: Swift.String + /// Token threshold at which compaction should be triggered for this entry. + /// /// - Remark: Generated from `#/components/schemas/ContextManagementParam/compact_threshold`. public var compactThreshold: Swift.Int? /// Creates a new `ContextManagementParam`. /// /// - Parameters: /// - _type: The context management entry type. Currently only 'compaction' is supported. - /// - compactThreshold: + /// - compactThreshold: Token threshold at which compaction should be triggered for this entry. public init( _type: Swift.String, compactThreshold: Swift.Int? = nil @@ -17148,13 +17445,9 @@ public enum Components { } } } - /// Types generated from the `#/components/parameters` section of the OpenAPI document. public enum Parameters {} - /// Types generated from the `#/components/requestBodies` section of the OpenAPI document. public enum RequestBodies {} - /// Types generated from the `#/components/responses` section of the OpenAPI document. public enum Responses {} - /// Types generated from the `#/components/headers` section of the OpenAPI document. public enum Headers {} } diff --git a/Tests/OpenAITests/ItemCodingTests.swift b/Tests/OpenAITests/ItemCodingTests.swift index 6a249fa0..334dbfa7 100644 --- a/Tests/OpenAITests/ItemCodingTests.swift +++ b/Tests/OpenAITests/ItemCodingTests.swift @@ -53,6 +53,50 @@ struct ItemCodingTests { #expect(item.webSearchQueries == ["baseball in Ukraine"]) } + // The generated decoders match wire values (`message`, `item_reference`) rather than schema names. These two + // cases were undecodable with the previous generator patches, which did not resolve the values of + // allOf-based resources or of nullable `type` properties. + + @Test func itemResourceMessageWithUserRoleDecodesAsInputMessageResource() throws { + let item = try JSONDecoder().decode( + Components.Schemas.ItemResource.self, + from: Data( + """ + { + "id": "msg_123", + "type": "message", + "role": "user", + "content": [] + } + """.utf8 + ) + ) + + guard case .inputMessageResource = item else { + Issue.record("Expected inputMessageResource, got \(item)") + return + } + } + + @Test func inputItemDecodesItemReferenceByWireValue() throws { + let item = try JSONDecoder().decode( + Components.Schemas.InputItem.self, + from: Data( + """ + { + "type": "item_reference", + "id": "msg_123" + } + """.utf8 + ) + ) + + guard case .itemReferenceParam = item else { + Issue.record("Expected itemReferenceParam, got \(item)") + return + } + } + private func decode(_ json: String) throws -> Components.Schemas.Item { try JSONDecoder().decode(Components.Schemas.Item.self, from: Data(json.utf8)) }