From 4dbb288e6b599c35ab537e69ec11f0a7211c385b Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 15 May 2026 20:27:09 +0300 Subject: [PATCH 01/31] Update Components.swift from new OpenAI OpenAPI spec Co-Authored-By: Claude Sonnet 4.6 --- .../Public/Schemas/Generated/Components.swift | 13222 +++++++++++----- 1 file changed, 8883 insertions(+), 4339 deletions(-) diff --git a/Sources/OpenAI/Public/Schemas/Generated/Components.swift b/Sources/OpenAI/Public/Schemas/Generated/Components.swift index 8f7dce6d..5b8c1e39 100644 --- a/Sources/OpenAI/Public/Schemas/Generated/Components.swift +++ b/Sources/OpenAI/Public/Schemas/Generated/Components.swift @@ -82,7 +82,7 @@ import struct Foundation.Date public enum Components { /// Types generated from the `#/components/schemas` section of the OpenAPI document. public enum Schemas { - /// The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, or `vtt`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`. + /// The format of the output, in one of these options: `json`, `text`, `srt`, `verbose_json`, `vtt`, or `diarized_json`. For `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported format is `json`. For `gpt-4o-transcribe-diarize`, the supported formats are `json`, `text`, and `diarized_json`, with `diarized_json` required to receive speaker annotations. /// /// /// - Remark: Generated from `#/components/schemas/AudioResponseFormat`. @@ -92,182 +92,7 @@ public enum Components { case srt = "srt" case verboseJson = "verbose_json" case vtt = "vtt" - } - /// A click action. - /// - /// - /// - Remark: Generated from `#/components/schemas/Click`. - public struct Click: Codable, Hashable, Sendable { - /// Specifies the event type. For a click action, this property is - /// always set to `click`. - /// - /// - /// - Remark: Generated from `#/components/schemas/Click/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case click = "click" - } - /// Specifies the event type. For a click action, this property is - /// always set to `click`. - /// - /// - /// - Remark: Generated from `#/components/schemas/Click/type`. - public var _type: Components.Schemas.Click._TypePayload - /// Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`. - /// - /// - /// - Remark: Generated from `#/components/schemas/Click/button`. - @frozen public enum ButtonPayload: String, Codable, Hashable, Sendable, CaseIterable { - case left = "left" - case right = "right" - case wheel = "wheel" - case back = "back" - case forward = "forward" - } - /// Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`. - /// - /// - /// - Remark: Generated from `#/components/schemas/Click/button`. - public var button: Components.Schemas.Click.ButtonPayload - /// The x-coordinate where the click occurred. - /// - /// - /// - Remark: Generated from `#/components/schemas/Click/x`. - public var x: Swift.Int - /// The y-coordinate where the click occurred. - /// - /// - /// - Remark: Generated from `#/components/schemas/Click/y`. - public var y: Swift.Int - /// Creates a new `Click`. - /// - /// - Parameters: - /// - _type: Specifies the event type. For a click action, this property is - /// - 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. - public init( - _type: Components.Schemas.Click._TypePayload, - button: Components.Schemas.Click.ButtonPayload, - x: Swift.Int, - y: Swift.Int - ) { - self._type = _type - self.button = button - self.x = x - self.y = y - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case button - case x - case y - } - } - /// The output of a code interpreter tool call that is a file. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterFileOutput`. - public struct CodeInterpreterFileOutput: Codable, Hashable, Sendable { - /// The type of the code interpreter file output. Always `files`. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterFileOutput/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case files = "files" - } - /// The type of the code interpreter file output. Always `files`. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterFileOutput/type`. - public var _type: Components.Schemas.CodeInterpreterFileOutput._TypePayload - /// - Remark: Generated from `#/components/schemas/CodeInterpreterFileOutput/FilesPayload`. - public struct FilesPayloadPayload: Codable, Hashable, Sendable { - /// The MIME type of the file. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterFileOutput/FilesPayload/mime_type`. - public var mimeType: Swift.String - /// The ID of the file. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterFileOutput/FilesPayload/file_id`. - public var fileId: Swift.String - /// Creates a new `FilesPayloadPayload`. - /// - /// - Parameters: - /// - mimeType: The MIME type of the file. - /// - fileId: The ID of the file. - public init( - mimeType: Swift.String, - fileId: Swift.String - ) { - self.mimeType = mimeType - self.fileId = fileId - } - public enum CodingKeys: String, CodingKey { - case mimeType = "mime_type" - case fileId = "file_id" - } - } - /// - Remark: Generated from `#/components/schemas/CodeInterpreterFileOutput/files`. - public typealias FilesPayload = [Components.Schemas.CodeInterpreterFileOutput.FilesPayloadPayload] - /// - Remark: Generated from `#/components/schemas/CodeInterpreterFileOutput/files`. - public var files: Components.Schemas.CodeInterpreterFileOutput.FilesPayload - /// Creates a new `CodeInterpreterFileOutput`. - /// - /// - Parameters: - /// - _type: The type of the code interpreter file output. Always `files`. - /// - files: - public init( - _type: Components.Schemas.CodeInterpreterFileOutput._TypePayload, - files: Components.Schemas.CodeInterpreterFileOutput.FilesPayload - ) { - self._type = _type - self.files = files - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case files - } - } - /// The output of a code interpreter tool call that is text. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterTextOutput`. - public struct CodeInterpreterTextOutput: Codable, Hashable, Sendable { - /// The type of the code interpreter text output. Always `logs`. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterTextOutput/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case logs = "logs" - } - /// The type of the code interpreter text output. Always `logs`. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterTextOutput/type`. - public var _type: Components.Schemas.CodeInterpreterTextOutput._TypePayload - /// The logs of the code interpreter tool call. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterTextOutput/logs`. - public var logs: Swift.String - /// Creates a new `CodeInterpreterTextOutput`. - /// - /// - Parameters: - /// - _type: The type of the code interpreter text output. Always `logs`. - /// - logs: The logs of the code interpreter tool call. - public init( - _type: Components.Schemas.CodeInterpreterTextOutput._TypePayload, - logs: Swift.String - ) { - self._type = _type - self.logs = logs - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case logs - } + case diarizedJson = "diarized_json" } /// A tool that runs Python code to help generate a response to a prompt. /// @@ -287,42 +112,50 @@ public enum Components { /// - Remark: Generated from `#/components/schemas/CodeInterpreterTool/type`. public var _type: Components.Schemas.CodeInterpreterTool._TypePayload /// The code interpreter container. Can be a container ID or an object that - /// specifies uploaded file IDs to make available to your code. + /// specifies uploaded file IDs to make available to your code, along with an + /// optional `memory_limit` setting. /// /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterTool/container`. @frozen public enum ContainerPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/CodeInterpreterTool/container/CodeInterpreterToolAuto`. - case codeInterpreterToolAuto(Components.Schemas.CodeInterpreterToolAuto) - public enum CodingKeys: String, CodingKey { - case _type = "type" - } - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let discriminator = try container.decode( - Swift.String.self, - forKey: ._type - ) - switch discriminator { - case "CodeInterpreterToolAuto", "#/components/schemas/CodeInterpreterToolAuto": - self = .codeInterpreterToolAuto(try .init(from: decoder)) - default: - throw Swift.DecodingError.unknownOneOfDiscriminator( - discriminatorKey: CodingKeys._type, - discriminatorValue: discriminator, - codingPath: decoder.codingPath - ) + /// The container ID. + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterTool/container/case1`. + case case1(Swift.String) + /// - Remark: Generated from `#/components/schemas/CodeInterpreterTool/container/case2`. + case AutoCodeInterpreterToolParam(Components.Schemas.AutoCodeInterpreterToolParam) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self = .case1(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .AutoCodeInterpreterToolParam(try .init(from: decoder)) + return + } catch { + errors.append(error) } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { - case let .codeInterpreterToolAuto(value): + case let .case1(value): + try encoder.encodeToSingleValueContainer(value) + case let .AutoCodeInterpreterToolParam(value): try value.encode(to: encoder) } } } /// The code interpreter container. Can be a container ID or an object that - /// specifies uploaded file IDs to make available to your code. + /// specifies uploaded file IDs to make available to your code, along with an + /// optional `memory_limit` setting. /// /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterTool/container`. @@ -344,54 +177,11 @@ public enum Components { case container } } - /// Configuration for a code interpreter container. Optionally specify the IDs - /// of the files to run the code on. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolAuto`. - public struct CodeInterpreterToolAuto: Codable, Hashable, Sendable { - /// Always `auto`. - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolAuto/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case auto = "auto" - } - /// Always `auto`. - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolAuto/type`. - public var _type: Components.Schemas.CodeInterpreterToolAuto._TypePayload - /// An optional list of uploaded files to make available to your code. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolAuto/file_ids`. - public var fileIds: [Swift.String]? - /// Creates a new `CodeInterpreterToolAuto`. - /// - /// - Parameters: - /// - _type: Always `auto`. - /// - fileIds: An optional list of uploaded files to make available to your code. - public init( - _type: Components.Schemas.CodeInterpreterToolAuto._TypePayload, - fileIds: [Swift.String]? = nil - ) { - self._type = _type - self.fileIds = fileIds - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case fileIds = "file_ids" - } - } /// A tool call to run code. /// /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall`. public struct CodeInterpreterToolCall: Codable, Hashable, Sendable { - /// The unique ID of the code interpreter tool call. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/id`. - public var id: Swift.String /// The type of the code interpreter tool call. Always `code_interpreter_call`. /// /// @@ -404,106 +194,111 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/type`. public var _type: Components.Schemas.CodeInterpreterToolCall._TypePayload - /// The ID of the container used to run the code. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/container_id`. - public var containerId: Swift.String? - /// The code to run. + /// The unique ID of the code interpreter tool call. /// /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/code`. - public var code: Swift.String - /// The status of the code interpreter tool call. + /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/id`. + public var id: Swift.String + /// The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`. /// /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/status`. @frozen public enum StatusPayload: String, Codable, Hashable, Sendable, CaseIterable { case inProgress = "in_progress" - case interpreting = "interpreting" case completed = "completed" + case incomplete = "incomplete" + case interpreting = "interpreting" + case failed = "failed" } - /// The status of the code interpreter tool call. + /// The status of the code interpreter tool call. Valid values are `in_progress`, `completed`, `incomplete`, `interpreting`, and `failed`. /// /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/status`. public var status: Components.Schemas.CodeInterpreterToolCall.StatusPayload - /// The results of the code interpreter tool call. + /// The ID of the container used to run the code. + /// + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/container_id`. + public var containerId: Swift.String + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/code`. + public var code: Swift.String? + /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/OutputsPayload`. + @frozen public enum OutputsPayloadPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/OutputsPayload/CodeInterpreterOutputLogs`. + case codeInterpreterOutputLogs(Components.Schemas.CodeInterpreterOutputLogs) + /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/OutputsPayload/CodeInterpreterOutputImage`. + case codeInterpreterOutputImage(Components.Schemas.CodeInterpreterOutputImage) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "CodeInterpreterOutputLogs", "#/components/schemas/CodeInterpreterOutputLogs": + self = .codeInterpreterOutputLogs(try .init(from: decoder)) + case "CodeInterpreterOutputImage", "#/components/schemas/CodeInterpreterOutputImage": + self = .codeInterpreterOutputImage(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .codeInterpreterOutputLogs(value): + try value.encode(to: encoder) + case let .codeInterpreterOutputImage(value): + try value.encode(to: encoder) + } + } + } + /// 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/results`. - public var results: [Components.Schemas.CodeInterpreterToolOutput] + /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/outputs`. + public typealias OutputsPayload = [Components.Schemas.CodeInterpreterToolCall.OutputsPayloadPayload] + /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/outputs`. + public var outputs: Components.Schemas.CodeInterpreterToolCall.OutputsPayload? /// Creates a new `CodeInterpreterToolCall`. /// /// - Parameters: - /// - id: The unique ID of the code interpreter tool call. /// - _type: The type of the code interpreter tool call. Always `code_interpreter_call`. + /// - 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: The code to run. - /// - status: The status of the code interpreter tool call. - /// - results: The results of the code interpreter tool call. + /// - code: + /// - outputs: public init( - id: Swift.String, _type: Components.Schemas.CodeInterpreterToolCall._TypePayload, - containerId: Swift.String? = nil, - code: Swift.String, + id: Swift.String, status: Components.Schemas.CodeInterpreterToolCall.StatusPayload, - results: [Components.Schemas.CodeInterpreterToolOutput] + containerId: Swift.String, + code: Swift.String? = nil, + outputs: Components.Schemas.CodeInterpreterToolCall.OutputsPayload? = nil ) { - self.id = id self._type = _type + self.id = id + self.status = status self.containerId = containerId self.code = code - self.status = status - self.results = results + self.outputs = outputs } public enum CodingKeys: String, CodingKey { - case id case _type = "type" + case id + case status case containerId = "container_id" case code - case status - case results - } - } - /// The output of a code interpreter tool. - /// - /// - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolOutput`. - @frozen public enum CodeInterpreterToolOutput: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolOutput/CodeInterpreterTextOutput`. - case codeInterpreterTextOutput(Components.Schemas.CodeInterpreterTextOutput) - /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolOutput/CodeInterpreterFileOutput`. - case codeInterpreterFileOutput(Components.Schemas.CodeInterpreterFileOutput) - public enum CodingKeys: String, CodingKey { - case _type = "type" - } - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - let discriminator = try container.decode( - Swift.String.self, - forKey: ._type - ) - switch discriminator { - case "CodeInterpreterTextOutput", "#/components/schemas/CodeInterpreterTextOutput": - self = .codeInterpreterTextOutput(try .init(from: decoder)) - case "CodeInterpreterFileOutput", "#/components/schemas/CodeInterpreterFileOutput": - self = .codeInterpreterFileOutput(try .init(from: decoder)) - default: - throw Swift.DecodingError.unknownOneOfDiscriminator( - discriminatorKey: CodingKeys._type, - discriminatorValue: discriminator, - codingPath: decoder.codingPath - ) - } - } - public func encode(to encoder: any Encoder) throws { - switch self { - case let .codeInterpreterTextOutput(value): - try value.encode(to: encoder) - case let .codeInterpreterFileOutput(value): - try value.encode(to: encoder) - } + case outputs } } /// A filter used to compare a specified attribute key to a given value using a defined comparison operation. @@ -511,13 +306,15 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ComparisonFilter`. public struct ComparisonFilter: Codable, Hashable, Sendable { - /// Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. + /// Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`. /// - `eq`: equals /// - `ne`: not equal /// - `gt`: greater than /// - `gte`: greater than or equal /// - `lt`: less than /// - `lte`: less than or equal + /// - `in`: in + /// - `nin`: not in /// /// /// - Remark: Generated from `#/components/schemas/ComparisonFilter/type`. @@ -528,14 +325,18 @@ public enum Components { case gte = "gte" case lt = "lt" case lte = "lte" + case _in = "in" + case nin = "nin" } - /// Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. + /// Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`. /// - `eq`: equals /// - `ne`: not equal /// - `gt`: greater than /// - `gte`: greater than or equal /// - `lt`: less than /// - `lte`: less than or equal + /// - `in`: in + /// - `nin`: not in /// /// /// - Remark: Generated from `#/components/schemas/ComparisonFilter/type`. @@ -554,9 +355,48 @@ public enum Components { case case2(Swift.Double) /// - Remark: Generated from `#/components/schemas/ComparisonFilter/value/case3`. case case3(Swift.Bool) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { + /// - Remark: Generated from `#/components/schemas/ComparisonFilter/value/Case4Payload`. + @frozen public enum Case4PayloadPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/ComparisonFilter/value/Case4Payload/case1`. + case case1(Swift.String) + /// - Remark: Generated from `#/components/schemas/ComparisonFilter/value/Case4Payload/case2`. + case case2(Swift.Double) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self = .case1(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .case2(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .case1(value): + try encoder.encodeToSingleValueContainer(value) + case let .case2(value): + try encoder.encodeToSingleValueContainer(value) + } + } + } + /// - Remark: Generated from `#/components/schemas/ComparisonFilter/value/case4`. + public typealias Case4Payload = [Components.Schemas.ComparisonFilter.ValuePayload.Case4PayloadPayload] + /// - Remark: Generated from `#/components/schemas/ComparisonFilter/value/case4`. + case case4(Components.Schemas.ComparisonFilter.ValuePayload.Case4Payload) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { self = .case1(try decoder.decodeFromSingleValueContainer()) return } catch { @@ -574,13 +414,19 @@ public enum Components { } catch { errors.append(error) } + do { + self = .case4(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } throw Swift.DecodingError.failedToDecodeOneOfSchema( type: Self.self, codingPath: decoder.codingPath, errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .case1(value): try encoder.encodeToSingleValueContainer(value) @@ -588,6 +434,8 @@ public enum Components { try encoder.encodeToSingleValueContainer(value) case let .case3(value): try encoder.encodeToSingleValueContainer(value) + case let .case4(value): + try encoder.encodeToSingleValueContainer(value) } } } @@ -598,7 +446,7 @@ public enum Components { /// Creates a new `ComparisonFilter`. /// /// - Parameters: - /// - _type: Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`. + /// - _type: Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, `lte`, `in`, `nin`. /// - key: The key to compare against the value. /// - value: The value to compare against the attribute key; supports string, number, or boolean types. public init( @@ -615,7 +463,7 @@ public enum Components { case key case value } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self._type = try container.decode( Components.Schemas.ComparisonFilter._TypePayload.self, @@ -653,35 +501,31 @@ public enum Components { public var _type: Components.Schemas.CompoundFilter._TypePayload /// - Remark: Generated from `#/components/schemas/CompoundFilter/FiltersPayload`. @frozen public enum FiltersPayloadPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/CompoundFilter/FiltersPayload/case1`. - case ComparisonFilter(Components.Schemas.ComparisonFilter) - /// - Remark: Generated from `#/components/schemas/CompoundFilter/FiltersPayload/case2`. - case case2(OpenAPIRuntime.OpenAPIValueContainer) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self = .ComparisonFilter(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .case2(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - throw Swift.DecodingError.failedToDecodeOneOfSchema( - type: Self.self, - codingPath: decoder.codingPath, - errors: errors + /// - Remark: Generated from `#/components/schemas/CompoundFilter/FiltersPayload/ComparisonFilter`. + case comparisonFilter(Components.Schemas.ComparisonFilter) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type ) + switch discriminator { + case "ComparisonFilter", "#/components/schemas/ComparisonFilter": + self = .comparisonFilter(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { - case let .ComparisonFilter(value): - try value.encode(to: encoder) - case let .case2(value): + case let .comparisonFilter(value): try value.encode(to: encoder) } } @@ -710,7 +554,7 @@ public enum Components { case _type = "type" case filters } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self._type = try container.decode( Components.Schemas.CompoundFilter._TypePayload.self, @@ -728,109 +572,89 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/ComputerAction`. @frozen public enum ComputerAction: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/ComputerAction/case1`. - case Click(Components.Schemas.Click) - /// - Remark: Generated from `#/components/schemas/ComputerAction/case2`. - case DoubleClick(Components.Schemas.DoubleClick) - /// - Remark: Generated from `#/components/schemas/ComputerAction/case3`. - case Drag(Components.Schemas.Drag) - /// - Remark: Generated from `#/components/schemas/ComputerAction/case4`. - case KeyPress(Components.Schemas.KeyPress) - /// - Remark: Generated from `#/components/schemas/ComputerAction/case5`. - case Move(Components.Schemas.Move) - /// - Remark: Generated from `#/components/schemas/ComputerAction/case6`. - case Screenshot(Components.Schemas.Screenshot) - /// - Remark: Generated from `#/components/schemas/ComputerAction/case7`. - case Scroll(Components.Schemas.Scroll) - /// - Remark: Generated from `#/components/schemas/ComputerAction/case8`. - case _Type(Components.Schemas._Type) - /// - Remark: Generated from `#/components/schemas/ComputerAction/case9`. - case Wait(Components.Schemas.Wait) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self = .Click(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .DoubleClick(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .Drag(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .KeyPress(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .Move(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .Screenshot(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .Scroll(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = ._Type(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .Wait(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - throw Swift.DecodingError.failedToDecodeOneOfSchema( - type: Self.self, - codingPath: decoder.codingPath, - errors: errors + /// - Remark: Generated from `#/components/schemas/ComputerAction/ClickParam`. + case clickParam(Components.Schemas.ClickParam) + /// - Remark: Generated from `#/components/schemas/ComputerAction/DoubleClickAction`. + case doubleClickAction(Components.Schemas.DoubleClickAction) + /// - Remark: Generated from `#/components/schemas/ComputerAction/DragParam`. + case dragParam(Components.Schemas.DragParam) + /// - Remark: Generated from `#/components/schemas/ComputerAction/KeyPressAction`. + case keyPressAction(Components.Schemas.KeyPressAction) + /// - Remark: Generated from `#/components/schemas/ComputerAction/MoveParam`. + case moveParam(Components.Schemas.MoveParam) + /// - Remark: Generated from `#/components/schemas/ComputerAction/ScreenshotParam`. + case screenshotParam(Components.Schemas.ScreenshotParam) + /// - Remark: Generated from `#/components/schemas/ComputerAction/ScrollParam`. + case scrollParam(Components.Schemas.ScrollParam) + /// - Remark: Generated from `#/components/schemas/ComputerAction/TypeParam`. + case typeParam(Components.Schemas.TypeParam) + /// - Remark: Generated from `#/components/schemas/ComputerAction/WaitParam`. + case waitParam(Components.Schemas.WaitParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type ) + switch discriminator { + case "ClickParam", "#/components/schemas/ClickParam": + self = .clickParam(try .init(from: decoder)) + case "DoubleClickAction", "#/components/schemas/DoubleClickAction": + self = .doubleClickAction(try .init(from: decoder)) + case "DragParam", "#/components/schemas/DragParam": + self = .dragParam(try .init(from: decoder)) + case "KeyPressAction", "#/components/schemas/KeyPressAction": + self = .keyPressAction(try .init(from: decoder)) + case "MoveParam", "#/components/schemas/MoveParam": + self = .moveParam(try .init(from: decoder)) + case "ScreenshotParam", "#/components/schemas/ScreenshotParam": + self = .screenshotParam(try .init(from: decoder)) + case "ScrollParam", "#/components/schemas/ScrollParam": + self = .scrollParam(try .init(from: decoder)) + case "TypeParam", "#/components/schemas/TypeParam": + self = .typeParam(try .init(from: decoder)) + case "WaitParam", "#/components/schemas/WaitParam": + self = .waitParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { - case let .Click(value): + case let .clickParam(value): try value.encode(to: encoder) - case let .DoubleClick(value): + case let .doubleClickAction(value): try value.encode(to: encoder) - case let .Drag(value): + case let .dragParam(value): try value.encode(to: encoder) - case let .KeyPress(value): + case let .keyPressAction(value): try value.encode(to: encoder) - case let .Move(value): + case let .moveParam(value): try value.encode(to: encoder) - case let .Screenshot(value): + case let .screenshotParam(value): try value.encode(to: encoder) - case let .Scroll(value): + case let .scrollParam(value): try value.encode(to: encoder) - case let ._Type(value): + case let .typeParam(value): try value.encode(to: encoder) - case let .Wait(value): + case let .waitParam(value): try value.encode(to: encoder) } } } + /// Flattened batched actions for `computer_use`. Each action includes an + /// `type` discriminator and action-specific fields. + /// + /// + /// - Remark: Generated from `#/components/schemas/ComputerActionList`. + public typealias ComputerActionList = [Components.Schemas.ComputerAction] /// A computer screenshot image used with the computer use tool. /// /// @@ -905,12 +729,14 @@ public enum Components { /// - Remark: Generated from `#/components/schemas/ComputerToolCall/call_id`. public var callId: Swift.String /// - Remark: Generated from `#/components/schemas/ComputerToolCall/action`. - public var action: Components.Schemas.ComputerAction + public var action: Components.Schemas.ComputerAction? + /// - Remark: Generated from `#/components/schemas/ComputerToolCall/actions`. + public var actions: Components.Schemas.ComputerActionList? /// The pending safety checks for the computer call. /// /// /// - Remark: Generated from `#/components/schemas/ComputerToolCall/pending_safety_checks`. - public var pendingSafetyChecks: [Components.Schemas.ComputerToolCallSafetyCheck] + public var pendingSafetyChecks: [Components.Schemas.ComputerCallSafetyCheckParam] /// The status of the item. One of `in_progress`, `completed`, or /// `incomplete`. Populated when items are returned via API. /// @@ -934,20 +760,23 @@ public enum Components { /// - id: The unique ID of the computer call. /// - callId: An identifier used when responding to the tool call with output. /// - action: + /// - actions: /// - pendingSafetyChecks: The pending safety checks for the computer call. /// - status: The status of the item. One of `in_progress`, `completed`, or public init( _type: Components.Schemas.ComputerToolCall._TypePayload, id: Swift.String, callId: Swift.String, - action: Components.Schemas.ComputerAction, - pendingSafetyChecks: [Components.Schemas.ComputerToolCallSafetyCheck], + action: Components.Schemas.ComputerAction? = nil, + actions: Components.Schemas.ComputerActionList? = nil, + pendingSafetyChecks: [Components.Schemas.ComputerCallSafetyCheckParam], status: Components.Schemas.ComputerToolCall.StatusPayload ) { self._type = _type self.id = id self.callId = callId self.action = action + self.actions = actions self.pendingSafetyChecks = pendingSafetyChecks self.status = status } @@ -956,6 +785,7 @@ public enum Components { case id case callId = "call_id" case action + case actions case pendingSafetyChecks = "pending_safety_checks" case status } @@ -992,7 +822,7 @@ public enum Components { /// /// /// - Remark: Generated from `#/components/schemas/ComputerToolCallOutput/acknowledged_safety_checks`. - public var acknowledgedSafetyChecks: [Components.Schemas.ComputerToolCallSafetyCheck]? + public var acknowledgedSafetyChecks: [Components.Schemas.ComputerCallSafetyCheckParam]? /// - Remark: Generated from `#/components/schemas/ComputerToolCallOutput/output`. public var output: Components.Schemas.ComputerScreenshotImage /// The status of the message input. One of `in_progress`, `completed`, or @@ -1024,7 +854,7 @@ public enum Components { _type: Components.Schemas.ComputerToolCallOutput._TypePayload, id: Swift.String? = nil, callId: Swift.String, - acknowledgedSafetyChecks: [Components.Schemas.ComputerToolCallSafetyCheck]? = nil, + acknowledgedSafetyChecks: [Components.Schemas.ComputerCallSafetyCheckParam]? = nil, output: Components.Schemas.ComputerScreenshotImage, status: Components.Schemas.ComputerToolCallOutput.StatusPayload? = nil ) { @@ -1055,15 +885,36 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ComputerToolCallOutputResource/value2/id`. public var id: Swift.String + /// The status of the message input. One of `in_progress`, `completed`, or + /// `incomplete`. Populated when input items are returned via API. + /// + /// + /// - Remark: Generated from `#/components/schemas/ComputerToolCallOutputResource/value2/status`. + public var status: Components.Schemas.ComputerCallOutputStatus + /// The identifier of the actor that created the item. + /// + /// + /// - Remark: Generated from `#/components/schemas/ComputerToolCallOutputResource/value2/created_by`. + public var createdBy: Swift.String? /// Creates a new `Value2Payload`. /// /// - Parameters: /// - id: The unique ID of the computer call tool output. - public init(id: Swift.String) { + /// - status: The status of the message input. One of `in_progress`, `completed`, or + /// - createdBy: The identifier of the actor that created the item. + public init( + id: Swift.String, + status: Components.Schemas.ComputerCallOutputStatus, + createdBy: Swift.String? = nil + ) { self.id = id + self.status = status + self.createdBy = createdBy } public enum CodingKeys: String, CodingKey { case id + case status + case createdBy = "created_by" } } /// - Remark: Generated from `#/components/schemas/ComputerToolCallOutputResource/value2`. @@ -1080,101 +931,101 @@ public enum Components { self.value1 = value1 self.value2 = value2 } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { self.value1 = try .init(from: decoder) self.value2 = try .init(from: decoder) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try self.value1.encode(to: encoder) try self.value2.encode(to: encoder) } } - /// A pending safety check for the computer call. - /// - /// - /// - Remark: Generated from `#/components/schemas/ComputerToolCallSafetyCheck`. - public struct ComputerToolCallSafetyCheck: Codable, Hashable, Sendable { - /// The ID of the pending safety check. - /// - /// - Remark: Generated from `#/components/schemas/ComputerToolCallSafetyCheck/id`. - public var id: Swift.String - /// The type of the pending safety check. - /// - /// - Remark: Generated from `#/components/schemas/ComputerToolCallSafetyCheck/code`. - public var code: Swift.String - /// Details about the pending safety check. - /// - /// - Remark: Generated from `#/components/schemas/ComputerToolCallSafetyCheck/message`. - public var message: Swift.String - /// Creates a new `ComputerToolCallSafetyCheck`. - /// - /// - Parameters: - /// - id: The ID of the pending safety check. - /// - code: The type of the pending safety check. - /// - message: Details about the pending safety check. - public init( - id: Swift.String, - code: Swift.String, - message: Swift.String - ) { - self.id = id - self.code = code - self.message = message - } - public enum CodingKeys: String, CodingKey { - case id - case code - case message - } - } - /// An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`. + /// The conversation that this response belongs to. Items from this conversation are prepended to `input_items` for this response request. + /// Input items and output items from this response are automatically added to this conversation after this response completes. /// /// - /// - Remark: Generated from `#/components/schemas/Coordinate`. - public struct Coordinate: Codable, Hashable, Sendable { - /// The x-coordinate. - /// - /// - /// - Remark: Generated from `#/components/schemas/Coordinate/x`. - public var x: Swift.Int - /// The y-coordinate. - /// + /// - Remark: Generated from `#/components/schemas/ConversationParam`. + @frozen public enum ConversationParam: Codable, Hashable, Sendable { + /// The unique ID of the conversation. /// - /// - Remark: Generated from `#/components/schemas/Coordinate/y`. - public var y: Swift.Int - /// Creates a new `Coordinate`. /// - /// - Parameters: - /// - x: The x-coordinate. - /// - y: The y-coordinate. - public init( - x: Swift.Int, - y: Swift.Int - ) { - self.x = x - self.y = y + /// - Remark: Generated from `#/components/schemas/ConversationParam/case1`. + case case1(Swift.String) + /// - Remark: Generated from `#/components/schemas/ConversationParam/case2`. + case ConversationParam2(Components.Schemas.ConversationParam2) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self = .case1(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .ConversationParam2(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) } - public enum CodingKeys: String, CodingKey { - case x - case y + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .case1(value): + try encoder.encodeToSingleValueContainer(value) + case let .ConversationParam2(value): + try value.encode(to: encoder) + } } } /// - Remark: Generated from `#/components/schemas/CreateModelResponseProperties`. public struct CreateModelResponseProperties: Codable, Hashable, Sendable { /// - Remark: Generated from `#/components/schemas/CreateModelResponseProperties/value1`. public var value1: Components.Schemas.ModelResponseProperties + /// - Remark: Generated from `#/components/schemas/CreateModelResponseProperties/value2`. + public struct Value2Payload: Codable, Hashable, Sendable { + /// An integer between 0 and 20 specifying the number of most likely tokens to + /// return at each token position, each with an associated log probability. + /// + /// + /// - Remark: Generated from `#/components/schemas/CreateModelResponseProperties/value2/top_logprobs`. + public var topLogprobs: Swift.Int? + /// Creates a new `Value2Payload`. + /// + /// - Parameters: + /// - topLogprobs: An integer between 0 and 20 specifying the number of most likely tokens to + public init(topLogprobs: Swift.Int? = nil) { + self.topLogprobs = topLogprobs + } + public enum CodingKeys: String, CodingKey { + case topLogprobs = "top_logprobs" + } + } + /// - Remark: Generated from `#/components/schemas/CreateModelResponseProperties/value2`. + public var value2: Components.Schemas.CreateModelResponseProperties.Value2Payload /// Creates a new `CreateModelResponseProperties`. /// /// - Parameters: /// - value1: - public init(value1: Components.Schemas.ModelResponseProperties) { + /// - value2: + public init( + value1: Components.Schemas.ModelResponseProperties, + value2: Components.Schemas.CreateModelResponseProperties.Value2Payload + ) { self.value1 = value1 + self.value2 = value2 } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { self.value1 = try .init(from: decoder) + self.value2 = try .init(from: decoder) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try self.value1.encode(to: encoder) + try self.value2.encode(to: encoder) } } /// - Remark: Generated from `#/components/schemas/CreateResponse`. @@ -1185,132 +1036,61 @@ public enum Components { public var value2: Components.Schemas.ResponseProperties /// - Remark: Generated from `#/components/schemas/CreateResponse/value3`. public struct Value3Payload: Codable, Hashable, Sendable { - /// Text, image, or file inputs to the model, used to generate a response. - /// - /// Learn more: - /// - [Text inputs and outputs](/docs/guides/text) - /// - [Image inputs](/docs/guides/images) - /// - [File inputs](/docs/guides/pdf-files) - /// - [Conversation state](/docs/guides/conversation-state) - /// - [Function calling](/docs/guides/function-calling) - /// - /// /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/input`. - @frozen public enum InputPayload: Codable, Hashable, Sendable { - /// A text input to the model, equivalent to a text input with the - /// `user` role. - /// - /// - /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/input/case1`. - case case1(Swift.String) - /// A list of one or many input items to the model, containing - /// different content types. - /// - /// - /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/input/case2`. - case case2([Components.Schemas.InputItem]) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self = .case1(try decoder.decodeFromSingleValueContainer()) - return - } catch { - errors.append(error) - } - do { - self = .case2(try decoder.decodeFromSingleValueContainer()) - return - } catch { - errors.append(error) - } - throw Swift.DecodingError.failedToDecodeOneOfSchema( - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - switch self { - case let .case1(value): - try encoder.encodeToSingleValueContainer(value) - case let .case2(value): - try encoder.encodeToSingleValueContainer(value) - } - } - } - /// Text, image, or file inputs to the model, used to generate a response. - /// - /// Learn more: - /// - [Text inputs and outputs](/docs/guides/text) - /// - [Image inputs](/docs/guides/images) - /// - [File inputs](/docs/guides/pdf-files) - /// - [Conversation state](/docs/guides/conversation-state) - /// - [Function calling](/docs/guides/function-calling) - /// - /// - /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/input`. - public var input: Components.Schemas.CreateResponse.Value3Payload.InputPayload? - /// Specify additional output data to include in the model response. Currently - /// supported values are: - /// - `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. - /// - `computer_call_output.output.image_url`: Include image urls from the computer call output. - /// - `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). - /// - `code_interpreter_call.outputs`: Includes the outputs of python code execution - /// in code interpreter tool call items. - /// - /// + public var input: Components.Schemas.InputParam? + /// - Remark: Generated from `#/components/schemas/IncludeEnum`. + public typealias IncludeEnum = [Components.Schemas.IncludeEnum] /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/include`. - public var include: [Components.Schemas.Includable]? - /// Whether to allow the model to run tool calls in parallel. - /// - /// + public var include: [Components.Schemas.IncludeEnum]? + public typealias Bool = Swift.Bool /// - 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. - /// - /// + public typealias Bool = Swift.Bool /// - 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. - /// - /// + public typealias String = Swift.String /// - 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. - /// - /// + public typealias Bool = Swift.Bool /// - 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] + /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/context_management`. + public var contextManagement: [Components.Schemas.ContextManagementParam]? + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/max_output_tokens`. + public var maxOutputTokens: Swift.Int? /// Creates a new `Value3Payload`. /// /// - Parameters: - /// - input: Text, image, or file inputs to the model, used to generate a response. - /// - include: Specify additional output data to include in the model response. Currently - /// - 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 + /// - input: + /// - include: + /// - parallelToolCalls: + /// - store: + /// - instructions: + /// - stream: + /// - streamOptions: + /// - conversation: + /// - contextManagement: + /// - maxOutputTokens: public init( - input: Components.Schemas.CreateResponse.Value3Payload.InputPayload? = nil, - include: [Components.Schemas.Includable]? = nil, + input: Components.Schemas.InputParam? = nil, + include: [Components.Schemas.IncludeEnum]? = nil, parallelToolCalls: Swift.Bool? = nil, store: Swift.Bool? = nil, instructions: Swift.String? = nil, - stream: Swift.Bool? = nil + stream: Swift.Bool? = nil, + streamOptions: Components.Schemas.ResponseStreamOptions? = nil, + conversation: Components.Schemas.ConversationParam? = nil, + contextManagement: [Components.Schemas.ContextManagementParam]? = nil, + maxOutputTokens: Swift.Int? = nil ) { self.input = input self.include = include @@ -1318,6 +1098,10 @@ public enum Components { self.store = store self.instructions = instructions self.stream = stream + self.streamOptions = streamOptions + self.conversation = conversation + self.contextManagement = contextManagement + self.maxOutputTokens = maxOutputTokens } public enum CodingKeys: String, CodingKey { case input @@ -1326,6 +1110,10 @@ public enum Components { case store case instructions case stream + case streamOptions = "stream_options" + case conversation + case contextManagement = "context_management" + case maxOutputTokens = "max_output_tokens" } } /// - Remark: Generated from `#/components/schemas/CreateResponse/value3`. @@ -1345,12 +1133,12 @@ public enum Components { self.value2 = value2 self.value3 = value3 } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { self.value1 = try .init(from: decoder) self.value2 = try .init(from: decoder) self.value3 = try .init(from: decoder) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try self.value1.encode(to: encoder) try self.value2.encode(to: encoder) try self.value3.encode(to: encoder) @@ -1430,22 +1218,10 @@ public enum Components { } } case temperature(OpenAPIRuntime.MultipartPart) - /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/include[]`. - public struct Include_lbrack__rbrack_Payload: Sendable, Hashable { - public var body: OpenAPIRuntime.HTTPBody - /// Creates a new `Include_lbrack__rbrack_Payload`. - /// - /// - Parameters: - /// - body: - public init(body: OpenAPIRuntime.HTTPBody) { - self.body = body - } - } - case include_lbrack__rbrack_(OpenAPIRuntime.MultipartPart) - /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/timestamp_granularities[]`. - public struct TimestampGranularities_lbrack__rbrack_Payload: Sendable, Hashable { + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/include`. + public struct IncludePayload: Sendable, Hashable { public var body: OpenAPIRuntime.HTTPBody - /// Creates a new `TimestampGranularities_lbrack__rbrack_Payload`. + /// Creates a new `IncludePayload`. /// /// - Parameters: /// - body: @@ -1453,11 +1229,11 @@ public enum Components { self.body = body } } - case timestampGranularities_lbrack__rbrack_(OpenAPIRuntime.MultipartPart) - /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/stream`. - public struct StreamPayload: Sendable, Hashable { + case include(OpenAPIRuntime.MultipartPart) + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/timestamp_granularities`. + public struct TimestampGranularitiesPayload: Sendable, Hashable { public var body: OpenAPIRuntime.HTTPBody - /// Creates a new `StreamPayload`. + /// Creates a new `TimestampGranularitiesPayload`. /// /// - Parameters: /// - body: @@ -1465,10 +1241,10 @@ public enum Components { self.body = body } } - case stream(OpenAPIRuntime.MultipartPart) + case timestampGranularities(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. + /// 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. /// /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/chunking_strategy/content/body`. public struct BodyPayload: Codable, Hashable, Sendable { @@ -1498,8 +1274,8 @@ public enum Components { self.value1 = value1 self.value2 = value2 } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self.value1 = try decoder.decodeFromSingleValueContainer() } catch { @@ -1520,7 +1296,7 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try encoder.encodeFirstNonNilValueToSingleValueContainer([ self.value1 ]) @@ -1537,6 +1313,129 @@ public enum Components { } } case chunkingStrategy(OpenAPIRuntime.MultipartPart) + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/known_speaker_names`. + public struct KnownSpeakerNamesPayload: Sendable, Hashable { + public var body: OpenAPIRuntime.HTTPBody + /// Creates a new `KnownSpeakerNamesPayload`. + /// + /// - Parameters: + /// - body: + public init(body: OpenAPIRuntime.HTTPBody) { + self.body = body + } + } + case knownSpeakerNames(OpenAPIRuntime.MultipartPart) + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionRequest/known_speaker_references`. + public struct KnownSpeakerReferencesPayload: Sendable, Hashable { + public var body: OpenAPIRuntime.HTTPBody + /// Creates a new `KnownSpeakerReferencesPayload`. + /// + /// - Parameters: + /// - body: + public init(body: OpenAPIRuntime.HTTPBody) { + self.body = body + } + } + case knownSpeakerReferences(OpenAPIRuntime.MultipartPart) + } + /// Represents a diarized transcription response returned by the model, including the combined transcript and speaker-segment annotations. + /// + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson`. + public struct CreateTranscriptionResponseDiarizedJson: Codable, Hashable, Sendable { + /// The type of task that was run. Always `transcribe`. + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson/task`. + @frozen public enum TaskPayload: String, Codable, Hashable, Sendable, CaseIterable { + case transcribe = "transcribe" + } + /// The type of task that was run. Always `transcribe`. + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson/task`. + public var task: Components.Schemas.CreateTranscriptionResponseDiarizedJson.TaskPayload + /// Duration of the input audio in seconds. + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson/duration`. + public var duration: Swift.Double + /// The concatenated transcript text for the entire audio input. + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson/text`. + public var text: Swift.String + /// Segments of the transcript annotated with timestamps and speaker labels. + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson/segments`. + public var segments: [Components.Schemas.TranscriptionDiarizedSegment] + /// Token or duration usage statistics for the request. + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson/usage`. + @frozen public enum UsagePayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson/usage/TranscriptTextUsageTokens`. + case transcriptTextUsageTokens(Components.Schemas.TranscriptTextUsageTokens) + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson/usage/TranscriptTextUsageDuration`. + case transcriptTextUsageDuration(Components.Schemas.TranscriptTextUsageDuration) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "TranscriptTextUsageTokens", "#/components/schemas/TranscriptTextUsageTokens": + self = .transcriptTextUsageTokens(try .init(from: decoder)) + case "TranscriptTextUsageDuration", "#/components/schemas/TranscriptTextUsageDuration": + self = .transcriptTextUsageDuration(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .transcriptTextUsageTokens(value): + try value.encode(to: encoder) + case let .transcriptTextUsageDuration(value): + try value.encode(to: encoder) + } + } + } + /// Token or duration usage statistics for the request. + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseDiarizedJson/usage`. + public var usage: Components.Schemas.CreateTranscriptionResponseDiarizedJson.UsagePayload? + /// Creates a new `CreateTranscriptionResponseDiarizedJson`. + /// + /// - Parameters: + /// - task: The type of task that was run. Always `transcribe`. + /// - duration: Duration of the input audio in seconds. + /// - text: The concatenated transcript text for the entire audio input. + /// - segments: Segments of the transcript annotated with timestamps and speaker labels. + /// - usage: Token or duration usage statistics for the request. + public init( + task: Components.Schemas.CreateTranscriptionResponseDiarizedJson.TaskPayload, + duration: Swift.Double, + text: Swift.String, + segments: [Components.Schemas.TranscriptionDiarizedSegment], + usage: Components.Schemas.CreateTranscriptionResponseDiarizedJson.UsagePayload? = nil + ) { + self.task = task + self.duration = duration + self.text = text + self.segments = segments + self.usage = usage + } + public enum CodingKeys: String, CodingKey { + case task + case duration + case text + case segments + case usage + } } /// Represents a transcription response returned by model, based on the provided input. /// @@ -1591,43 +1490,93 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseJson/logprobs`. public var logprobs: Components.Schemas.CreateTranscriptionResponseJson.LogprobsPayload? + /// Token usage statistics for the request. + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseJson/usage`. + @frozen public enum UsagePayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseJson/usage/case1`. + case TranscriptTextUsageTokens(Components.Schemas.TranscriptTextUsageTokens) + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseJson/usage/case2`. + case TranscriptTextUsageDuration(Components.Schemas.TranscriptTextUsageDuration) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self = .TranscriptTextUsageTokens(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .TranscriptTextUsageDuration(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .TranscriptTextUsageTokens(value): + try value.encode(to: encoder) + case let .TranscriptTextUsageDuration(value): + try value.encode(to: encoder) + } + } + } + /// Token usage statistics for the request. + /// + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseJson/usage`. + public var usage: Components.Schemas.CreateTranscriptionResponseJson.UsagePayload? /// Creates a new `CreateTranscriptionResponseJson`. /// /// - Parameters: /// - text: The transcribed text. /// - logprobs: The log probabilities of the tokens in the transcription. Only returned with the models `gpt-4o-transcribe` and `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` array. + /// - usage: Token usage statistics for the request. public init( text: Swift.String, - logprobs: Components.Schemas.CreateTranscriptionResponseJson.LogprobsPayload? = nil + logprobs: Components.Schemas.CreateTranscriptionResponseJson.LogprobsPayload? = nil, + usage: Components.Schemas.CreateTranscriptionResponseJson.UsagePayload? = nil ) { self.text = text self.logprobs = logprobs + self.usage = usage } public enum CodingKeys: String, CodingKey { case text case logprobs + case usage } } /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseStreamEvent`. public struct CreateTranscriptionResponseStreamEvent: Codable, Hashable, Sendable { /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseStreamEvent/value1`. - public var value1: Components.Schemas.TranscriptTextDeltaEvent? + public var value1: Components.Schemas.TranscriptTextSegmentEvent? /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseStreamEvent/value2`. - public var value2: Components.Schemas.TranscriptTextDoneEvent? + public var value2: Components.Schemas.TranscriptTextDeltaEvent? + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseStreamEvent/value3`. + public var value3: Components.Schemas.TranscriptTextDoneEvent? /// Creates a new `CreateTranscriptionResponseStreamEvent`. /// /// - Parameters: /// - value1: /// - value2: + /// - value3: public init( - value1: Components.Schemas.TranscriptTextDeltaEvent? = nil, - value2: Components.Schemas.TranscriptTextDoneEvent? = nil + value1: Components.Schemas.TranscriptTextSegmentEvent? = nil, + value2: Components.Schemas.TranscriptTextDeltaEvent? = nil, + value3: Components.Schemas.TranscriptTextDoneEvent? = nil ) { self.value1 = value1 self.value2 = value2 + self.value3 = value3 } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self.value1 = try .init(from: decoder) } catch { @@ -1638,19 +1587,26 @@ public enum Components { } catch { errors.append(error) } + do { + self.value3 = try .init(from: decoder) + } catch { + errors.append(error) + } try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( [ self.value1, - self.value2 + self.value2, + self.value3 ], type: Self.self, codingPath: decoder.codingPath, errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try self.value1?.encode(to: encoder) try self.value2?.encode(to: encoder) + try self.value3?.encode(to: encoder) } } /// Represents a verbose json transcription response returned by model, based on the provided input. @@ -1677,6 +1633,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseVerboseJson/segments`. public var segments: [Components.Schemas.TranscriptionSegment]? + /// - Remark: Generated from `#/components/schemas/CreateTranscriptionResponseVerboseJson/usage`. + public var usage: Components.Schemas.TranscriptTextUsageDuration? /// Creates a new `CreateTranscriptionResponseVerboseJson`. /// /// - Parameters: @@ -1685,18 +1643,21 @@ public enum Components { /// - text: The transcribed text. /// - words: Extracted words and their corresponding timestamps. /// - segments: Segments of the transcribed text and their corresponding details. + /// - usage: public init( language: Swift.String, duration: Swift.Double, text: Swift.String, words: [Components.Schemas.TranscriptionWord]? = nil, - segments: [Components.Schemas.TranscriptionSegment]? = nil + segments: [Components.Schemas.TranscriptionSegment]? = nil, + usage: Components.Schemas.TranscriptTextUsageDuration? = nil ) { self.language = language self.duration = duration self.text = text self.words = words self.segments = segments + self.usage = usage } public enum CodingKeys: String, CodingKey { case language @@ -1704,147 +1665,129 @@ public enum Components { case text case words case segments + case usage } } - /// A double click action. + /// A call to a custom tool created by the model. /// /// - /// - Remark: Generated from `#/components/schemas/DoubleClick`. - public struct DoubleClick: Codable, Hashable, Sendable { - /// Specifies the event type. For a double click action, this property is - /// always set to `double_click`. + /// - Remark: Generated from `#/components/schemas/CustomToolCall`. + public struct CustomToolCall: Codable, Hashable, Sendable { + /// The type of the custom tool call. Always `custom_tool_call`. /// /// - /// - Remark: Generated from `#/components/schemas/DoubleClick/type`. + /// - Remark: Generated from `#/components/schemas/CustomToolCall/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case doubleClick = "double_click" + case customToolCall = "custom_tool_call" } - /// Specifies the event type. For a double click action, this property is - /// always set to `double_click`. - /// + /// The type of the custom tool call. Always `custom_tool_call`. /// - /// - Remark: Generated from `#/components/schemas/DoubleClick/type`. - public var _type: Components.Schemas.DoubleClick._TypePayload - /// The x-coordinate where the double click occurred. /// + /// - Remark: Generated from `#/components/schemas/CustomToolCall/type`. + public var _type: Components.Schemas.CustomToolCall._TypePayload + /// The unique ID of the custom tool call in the OpenAI platform. /// - /// - Remark: Generated from `#/components/schemas/DoubleClick/x`. - public var x: Swift.Int - /// The y-coordinate where the double click occurred. /// + /// - Remark: Generated from `#/components/schemas/CustomToolCall/id`. + public var id: Swift.String? + /// An identifier used to map this custom tool call to a tool call output. /// - /// - Remark: Generated from `#/components/schemas/DoubleClick/y`. - public var y: Swift.Int - /// Creates a new `DoubleClick`. /// - /// - Parameters: - /// - _type: Specifies the event type. For a double click action, this property is - /// - x: The x-coordinate where the double click occurred. - /// - y: The y-coordinate where the double click occurred. - public init( - _type: Components.Schemas.DoubleClick._TypePayload, - x: Swift.Int, - y: Swift.Int - ) { - self._type = _type - self.x = x - self.y = y - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case x - case y - } - } - /// A drag action. - /// - /// - /// - Remark: Generated from `#/components/schemas/Drag`. - public struct Drag: Codable, Hashable, Sendable { - /// Specifies the event type. For a drag action, this property is - /// always set to `drag`. + /// - Remark: Generated from `#/components/schemas/CustomToolCall/call_id`. + public var callId: Swift.String + /// The namespace of the custom tool being called. /// /// - /// - Remark: Generated from `#/components/schemas/Drag/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case drag = "drag" - } - /// Specifies the event type. For a drag action, this property is - /// always set to `drag`. + /// - Remark: Generated from `#/components/schemas/CustomToolCall/namespace`. + public var namespace: Swift.String? + /// The name of the custom tool being called. /// /// - /// - Remark: Generated from `#/components/schemas/Drag/type`. - public var _type: Components.Schemas.Drag._TypePayload - /// An array of coordinates representing the path of the drag action. Coordinates will appear as an array - /// of objects, eg - /// ``` - /// [ - /// { x: 100, y: 200 }, - /// { x: 200, y: 300 } - /// ] - /// ``` + /// - Remark: Generated from `#/components/schemas/CustomToolCall/name`. + public var name: Swift.String + /// The input for the custom tool call generated by the model. /// /// - /// - Remark: Generated from `#/components/schemas/Drag/path`. - public var path: [Components.Schemas.Coordinate] - /// Creates a new `Drag`. + /// - Remark: Generated from `#/components/schemas/CustomToolCall/input`. + public var input: Swift.String + /// Creates a new `CustomToolCall`. /// /// - Parameters: - /// - _type: Specifies the event type. For a drag action, this property is - /// - path: An array of coordinates representing the path of the drag action. Coordinates will appear as an array + /// - _type: The type of the custom tool call. Always `custom_tool_call`. + /// - id: The unique ID of the custom tool call in the OpenAI platform. + /// - callId: An identifier used to map this custom tool call to a tool call output. + /// - namespace: The namespace of the custom tool being called. + /// - name: The name of the custom tool being called. + /// - input: The input for the custom tool call generated by the model. public init( - _type: Components.Schemas.Drag._TypePayload, - path: [Components.Schemas.Coordinate] + _type: Components.Schemas.CustomToolCall._TypePayload, + id: Swift.String? = nil, + callId: Swift.String, + namespace: Swift.String? = nil, + name: Swift.String, + input: Swift.String ) { self._type = _type - self.path = path + self.id = id + self.callId = callId + self.namespace = namespace + self.name = name + self.input = input } public enum CodingKeys: String, CodingKey { case _type = "type" - case path + case id + case callId = "call_id" + case namespace + case name + case input } } - /// A message input to the model with a role indicating instruction following - /// hierarchy. Instructions given with the `developer` or `system` role take - /// precedence over instructions given with the `user` role. Messages with the - /// `assistant` role are presumed to have been generated by the model in previous - /// interactions. + /// The output of a custom tool call from your code, being sent back to the model. /// /// - /// - Remark: Generated from `#/components/schemas/EasyInputMessage`. - public struct EasyInputMessage: Codable, Hashable, Sendable { - /// The role of the message input. One of `user`, `assistant`, `system`, or - /// `developer`. + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutput`. + public struct CustomToolCallOutput: Codable, Hashable, Sendable { + /// The type of the custom tool call output. Always `custom_tool_call_output`. /// /// - /// - Remark: Generated from `#/components/schemas/EasyInputMessage/role`. - @frozen public enum RolePayload: String, Codable, Hashable, Sendable, CaseIterable { - case user = "user" - case assistant = "assistant" - case system = "system" - case developer = "developer" + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutput/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case customToolCallOutput = "custom_tool_call_output" } - /// The role of the message input. One of `user`, `assistant`, `system`, or - /// `developer`. + /// The type of the custom tool call output. Always `custom_tool_call_output`. /// /// - /// - Remark: Generated from `#/components/schemas/EasyInputMessage/role`. - public var role: Components.Schemas.EasyInputMessage.RolePayload - /// Text, image, or audio input to the model, used to generate a response. - /// Can also contain previous assistant responses. + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutput/type`. + public var _type: Components.Schemas.CustomToolCallOutput._TypePayload + /// The unique ID of the custom tool call output in the OpenAI platform. /// /// - /// - Remark: Generated from `#/components/schemas/EasyInputMessage/content`. - @frozen public enum ContentPayload: Codable, Hashable, Sendable { - /// A text input to the model. + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutput/id`. + public var id: Swift.String? + /// The call ID, used to map this custom tool call output to a custom tool call. + /// + /// + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutput/call_id`. + public var callId: Swift.String + /// The output from the custom tool call generated by your code. + /// Can be a string or an list of output content. + /// + /// + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutput/output`. + @frozen public enum OutputPayload: Codable, Hashable, Sendable { + /// A string of the output of the custom tool call. /// /// - /// - Remark: Generated from `#/components/schemas/EasyInputMessage/content/case1`. + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutput/output/case1`. case case1(Swift.String) - /// - Remark: Generated from `#/components/schemas/EasyInputMessage/content/case2`. - case InputMessageContentList(Components.Schemas.InputMessageContentList) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + /// Text, image, or file output of the custom tool call. + /// + /// + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutput/output/case2`. + case case2([Components.Schemas.FunctionAndCustomToolCallOutput]) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self = .case1(try decoder.decodeFromSingleValueContainer()) return @@ -1852,7 +1795,7 @@ public enum Components { errors.append(error) } do { - self = .InputMessageContentList(try decoder.decodeFromSingleValueContainer()) + self = .case2(try decoder.decodeFromSingleValueContainer()) return } catch { errors.append(error) @@ -1863,60 +1806,301 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .case1(value): try encoder.encodeToSingleValueContainer(value) - case let .InputMessageContentList(value): + case let .case2(value): try encoder.encodeToSingleValueContainer(value) } } } - /// Text, image, or audio input to the model, used to generate a response. - /// Can also contain previous assistant responses. - /// - /// - /// - Remark: Generated from `#/components/schemas/EasyInputMessage/content`. - public var content: Components.Schemas.EasyInputMessage.ContentPayload - /// The type of the message input. Always `message`. - /// - /// - /// - Remark: Generated from `#/components/schemas/EasyInputMessage/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case message = "message" - } - /// The type of the message input. Always `message`. + /// The output from the custom tool call generated by your code. + /// Can be a string or an list of output content. /// /// - /// - Remark: Generated from `#/components/schemas/EasyInputMessage/type`. - public var _type: Components.Schemas.EasyInputMessage._TypePayload? - /// Creates a new `EasyInputMessage`. + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutput/output`. + public var output: Components.Schemas.CustomToolCallOutput.OutputPayload + /// Creates a new `CustomToolCallOutput`. /// /// - Parameters: - /// - role: The role of the message input. One of `user`, `assistant`, `system`, or - /// - content: Text, image, or audio input to the model, used to generate a response. - /// - _type: The type of the message input. Always `message`. + /// - _type: The type of the custom tool call output. Always `custom_tool_call_output`. + /// - id: The unique ID of the custom tool call output in the OpenAI platform. + /// - callId: The call ID, used to map this custom tool call output to a custom tool call. + /// - output: The output from the custom tool call generated by your code. public init( - role: Components.Schemas.EasyInputMessage.RolePayload, - content: Components.Schemas.EasyInputMessage.ContentPayload, - _type: Components.Schemas.EasyInputMessage._TypePayload? = nil + _type: Components.Schemas.CustomToolCallOutput._TypePayload, + id: Swift.String? = nil, + callId: Swift.String, + output: Components.Schemas.CustomToolCallOutput.OutputPayload ) { - self.role = role - self.content = content self._type = _type + self.id = id + self.callId = callId + self.output = output } public enum CodingKeys: String, CodingKey { - case role - case content case _type = "type" - } + case id + case callId = "call_id" + case output + } + } + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutputResource`. + public struct CustomToolCallOutputResource: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutputResource/value1`. + public var value1: Components.Schemas.CustomToolCallOutput + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutputResource/value2`. + public struct Value2Payload: Codable, Hashable, Sendable { + /// The unique ID of the custom tool call output item. + /// + /// + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutputResource/value2/id`. + public var id: Swift.String + /// The status of the item. One of `in_progress`, `completed`, or + /// `incomplete`. Populated when items are returned via API. + /// + /// + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutputResource/value2/status`. + public var status: Components.Schemas.FunctionCallOutputStatusEnum + /// The identifier of the actor that created the item. + /// + /// + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutputResource/value2/created_by`. + public var createdBy: Swift.String? + /// Creates a new `Value2Payload`. + /// + /// - Parameters: + /// - id: The unique ID of the custom tool call output item. + /// - status: The status of the item. One of `in_progress`, `completed`, or + /// - createdBy: The identifier of the actor that created the item. + public init( + id: Swift.String, + status: Components.Schemas.FunctionCallOutputStatusEnum, + createdBy: Swift.String? = nil + ) { + self.id = id + self.status = status + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case id + case status + case createdBy = "created_by" + } + } + /// - Remark: Generated from `#/components/schemas/CustomToolCallOutputResource/value2`. + public var value2: Components.Schemas.CustomToolCallOutputResource.Value2Payload + /// Creates a new `CustomToolCallOutputResource`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Components.Schemas.CustomToolCallOutput, + value2: Components.Schemas.CustomToolCallOutputResource.Value2Payload + ) { + self.value1 = value1 + self.value2 = value2 + } + public init(from decoder: any Swift.Decoder) throws { + self.value1 = try .init(from: decoder) + self.value2 = try .init(from: decoder) + } + public func encode(to encoder: any Swift.Encoder) throws { + try self.value1.encode(to: encoder) + try self.value2.encode(to: encoder) + } + } + /// - Remark: Generated from `#/components/schemas/CustomToolCallResource`. + public struct CustomToolCallResource: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/CustomToolCallResource/value1`. + public var value1: Components.Schemas.CustomToolCall + /// - Remark: Generated from `#/components/schemas/CustomToolCallResource/value2`. + public struct Value2Payload: Codable, Hashable, Sendable { + /// The unique ID of the custom tool call item. + /// + /// + /// - Remark: Generated from `#/components/schemas/CustomToolCallResource/value2/id`. + public var id: Swift.String + /// The status of the item. One of `in_progress`, `completed`, or + /// `incomplete`. Populated when items are returned via API. + /// + /// + /// - Remark: Generated from `#/components/schemas/CustomToolCallResource/value2/status`. + public var status: Components.Schemas.FunctionCallStatus + /// The identifier of the actor that created the item. + /// + /// + /// - Remark: Generated from `#/components/schemas/CustomToolCallResource/value2/created_by`. + public var createdBy: Swift.String? + /// Creates a new `Value2Payload`. + /// + /// - Parameters: + /// - id: The unique ID of the custom tool call item. + /// - status: The status of the item. One of `in_progress`, `completed`, or + /// - createdBy: The identifier of the actor that created the item. + public init( + id: Swift.String, + status: Components.Schemas.FunctionCallStatus, + createdBy: Swift.String? = nil + ) { + self.id = id + self.status = status + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case id + case status + case createdBy = "created_by" + } + } + /// - Remark: Generated from `#/components/schemas/CustomToolCallResource/value2`. + public var value2: Components.Schemas.CustomToolCallResource.Value2Payload + /// Creates a new `CustomToolCallResource`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Components.Schemas.CustomToolCall, + value2: Components.Schemas.CustomToolCallResource.Value2Payload + ) { + self.value1 = value1 + self.value2 = value2 + } + public init(from decoder: any Swift.Decoder) throws { + self.value1 = try .init(from: decoder) + self.value2 = try .init(from: decoder) + } + public func encode(to encoder: any Swift.Encoder) throws { + try self.value1.encode(to: encoder) + try self.value2.encode(to: encoder) + } + } + /// A message input to the model with a role indicating instruction following + /// hierarchy. Instructions given with the `developer` or `system` role take + /// precedence over instructions given with the `user` role. Messages with the + /// `assistant` role are presumed to have been generated by the model in previous + /// interactions. + /// + /// + /// - Remark: Generated from `#/components/schemas/EasyInputMessage`. + public struct EasyInputMessage: Codable, Hashable, Sendable { + /// The role of the message input. One of `user`, `assistant`, `system`, or + /// `developer`. + /// + /// + /// - Remark: Generated from `#/components/schemas/EasyInputMessage/role`. + @frozen public enum RolePayload: String, Codable, Hashable, Sendable, CaseIterable { + case user = "user" + case assistant = "assistant" + case system = "system" + case developer = "developer" + } + /// The role of the message input. One of `user`, `assistant`, `system`, or + /// `developer`. + /// + /// + /// - Remark: Generated from `#/components/schemas/EasyInputMessage/role`. + public var role: Components.Schemas.EasyInputMessage.RolePayload + /// Text, image, or audio input to the model, used to generate a response. + /// Can also contain previous assistant responses. + /// + /// + /// - Remark: Generated from `#/components/schemas/EasyInputMessage/content`. + @frozen public enum ContentPayload: Codable, Hashable, Sendable { + /// A text input to the model. + /// + /// + /// - Remark: Generated from `#/components/schemas/EasyInputMessage/content/case1`. + case case1(Swift.String) + /// - Remark: Generated from `#/components/schemas/EasyInputMessage/content/case2`. + case InputMessageContentList(Components.Schemas.InputMessageContentList) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self = .case1(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .InputMessageContentList(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .case1(value): + try encoder.encodeToSingleValueContainer(value) + case let .InputMessageContentList(value): + try encoder.encodeToSingleValueContainer(value) + } + } + } + /// Text, image, or audio input to the model, used to generate a response. + /// Can also contain previous assistant responses. + /// + /// + /// - 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`. + /// + /// + /// - Remark: Generated from `#/components/schemas/EasyInputMessage/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case message = "message" + } + /// The type of the message input. Always `message`. + /// + /// + /// - Remark: Generated from `#/components/schemas/EasyInputMessage/type`. + public var _type: Components.Schemas.EasyInputMessage._TypePayload? + /// Creates a new `EasyInputMessage`. + /// + /// - Parameters: + /// - role: The role of the message input. One of `user`, `assistant`, `system`, or + /// - content: Text, image, or audio input to the model, used to generate a response. + /// - phase: + /// - _type: The type of the message input. Always `message`. + public init( + role: Components.Schemas.EasyInputMessage.RolePayload, + content: Components.Schemas.EasyInputMessage.ContentPayload, + phase: Components.Schemas.MessagePhase? = nil, + _type: Components.Schemas.EasyInputMessage._TypePayload? = nil + ) { + self.role = role + self.content = content + self.phase = phase + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case role + case content + case phase + case _type = "type" + } } /// - Remark: Generated from `#/components/schemas/Error`. public struct _Error: Codable, Hashable, Sendable { + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/Error/code`. public var code: Swift.String? /// - Remark: Generated from `#/components/schemas/Error/message`. public var message: Swift.String + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/Error/param`. public var param: Swift.String? /// - Remark: Generated from `#/components/schemas/Error/type`. @@ -2098,9 +2282,6 @@ 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`. @@ -2110,7 +2291,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: The results of the file search tool call. + /// - results: public init( id: Swift.String, _type: Components.Schemas.FileSearchToolCall._TypePayload, @@ -2132,6 +2313,49 @@ public enum Components { case results } } + /// - Remark: Generated from `#/components/schemas/FunctionAndCustomToolCallOutput`. + @frozen public enum FunctionAndCustomToolCallOutput: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/FunctionAndCustomToolCallOutput/InputTextContent`. + case inputTextContent(Components.Schemas.InputTextContent) + /// - Remark: Generated from `#/components/schemas/FunctionAndCustomToolCallOutput/InputImageContent`. + case inputImageContent(Components.Schemas.InputImageContent) + /// - Remark: Generated from `#/components/schemas/FunctionAndCustomToolCallOutput/InputFileContent`. + case inputFileContent(Components.Schemas.InputFileContent) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "InputTextContent", "#/components/schemas/InputTextContent": + self = .inputTextContent(try .init(from: decoder)) + case "InputImageContent", "#/components/schemas/InputImageContent": + self = .inputImageContent(try .init(from: decoder)) + case "InputFileContent", "#/components/schemas/InputFileContent": + self = .inputFileContent(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .inputTextContent(value): + try value.encode(to: encoder) + case let .inputImageContent(value): + try value.encode(to: encoder) + case let .inputFileContent(value): + try value.encode(to: encoder) + } + } + } /// A tool call to run a function. See the /// [function calling guide](/docs/guides/function-calling) for more information. /// @@ -2160,6 +2384,11 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionToolCall/call_id`. public var callId: Swift.String + /// The namespace of the function to run. + /// + /// + /// - Remark: Generated from `#/components/schemas/FunctionToolCall/namespace`. + public var namespace: Swift.String? /// The name of the function to run. /// /// @@ -2192,6 +2421,7 @@ public enum Components { /// - id: The unique ID of the function tool call. /// - _type: The type of the function tool call. Always `function_call`. /// - callId: The unique ID of the function tool call generated by the model. + /// - namespace: The namespace of the function to run. /// - name: The name of the function to run. /// - arguments: A JSON string of the arguments to pass to the function. /// - status: The status of the item. One of `in_progress`, `completed`, or @@ -2199,6 +2429,7 @@ public enum Components { id: Swift.String? = nil, _type: Components.Schemas.FunctionToolCall._TypePayload, callId: Swift.String, + namespace: Swift.String? = nil, name: Swift.String, arguments: Swift.String, status: Components.Schemas.FunctionToolCall.StatusPayload? = nil @@ -2206,6 +2437,7 @@ public enum Components { self.id = id self._type = _type self.callId = callId + self.namespace = namespace self.name = name self.arguments = arguments self.status = status @@ -2214,6 +2446,7 @@ public enum Components { case id case _type = "type" case callId = "call_id" + case namespace case name case arguments case status @@ -2247,11 +2480,57 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionToolCallOutput/call_id`. public var callId: Swift.String - /// A JSON string of the output of the function tool call. + /// The output from the function call generated by your code. + /// Can be a string or an list of output content. /// /// /// - Remark: Generated from `#/components/schemas/FunctionToolCallOutput/output`. - public var output: Swift.String + @frozen public enum OutputPayload: Codable, Hashable, Sendable { + /// A string of the output of the function call. + /// + /// + /// - Remark: Generated from `#/components/schemas/FunctionToolCallOutput/output/case1`. + case case1(Swift.String) + /// Text, image, or file output of the function call. + /// + /// + /// - Remark: Generated from `#/components/schemas/FunctionToolCallOutput/output/case2`. + case case2([Components.Schemas.FunctionAndCustomToolCallOutput]) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self = .case1(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .case2(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .case1(value): + try encoder.encodeToSingleValueContainer(value) + case let .case2(value): + try encoder.encodeToSingleValueContainer(value) + } + } + } + /// The output from the function call generated by your code. + /// Can be a string or an list of output content. + /// + /// + /// - Remark: Generated from `#/components/schemas/FunctionToolCallOutput/output`. + public var output: Components.Schemas.FunctionToolCallOutput.OutputPayload /// The status of the item. One of `in_progress`, `completed`, or /// `incomplete`. Populated when items are returned via API. /// @@ -2274,13 +2553,13 @@ public enum Components { /// - id: The unique ID of the function tool call output. Populated when this item /// - _type: The type of the function tool call output. Always `function_call_output`. /// - callId: The unique ID of the function tool call generated by the model. - /// - output: A JSON string of the output of the function tool call. + /// - output: The output from the function call generated by your code. /// - status: The status of the item. One of `in_progress`, `completed`, or public init( id: Swift.String? = nil, _type: Components.Schemas.FunctionToolCallOutput._TypePayload, callId: Swift.String, - output: Swift.String, + output: Components.Schemas.FunctionToolCallOutput.OutputPayload, status: Components.Schemas.FunctionToolCallOutput.StatusPayload? = nil ) { self.id = id @@ -2308,15 +2587,36 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionToolCallOutputResource/value2/id`. public var id: Swift.String + /// The status of the item. One of `in_progress`, `completed`, or + /// `incomplete`. Populated when items are returned via API. + /// + /// + /// - Remark: Generated from `#/components/schemas/FunctionToolCallOutputResource/value2/status`. + public var status: Components.Schemas.FunctionCallOutputStatusEnum + /// The identifier of the actor that created the item. + /// + /// + /// - Remark: Generated from `#/components/schemas/FunctionToolCallOutputResource/value2/created_by`. + public var createdBy: Swift.String? /// Creates a new `Value2Payload`. /// /// - Parameters: /// - id: The unique ID of the function call tool output. - public init(id: Swift.String) { - self.id = id - } + /// - status: The status of the item. One of `in_progress`, `completed`, or + /// - createdBy: The identifier of the actor that created the item. + public init( + id: Swift.String, + status: Components.Schemas.FunctionCallOutputStatusEnum, + createdBy: Swift.String? = nil + ) { + self.id = id + self.status = status + self.createdBy = createdBy + } public enum CodingKeys: String, CodingKey { case id + case status + case createdBy = "created_by" } } /// - Remark: Generated from `#/components/schemas/FunctionToolCallOutputResource/value2`. @@ -2333,11 +2633,11 @@ public enum Components { self.value1 = value1 self.value2 = value2 } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { self.value1 = try .init(from: decoder) self.value2 = try .init(from: decoder) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try self.value1.encode(to: encoder) try self.value2.encode(to: encoder) } @@ -2353,15 +2653,36 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionToolCallResource/value2/id`. public var id: Swift.String + /// The status of the item. One of `in_progress`, `completed`, or + /// `incomplete`. Populated when items are returned via API. + /// + /// + /// - Remark: Generated from `#/components/schemas/FunctionToolCallResource/value2/status`. + public var status: Components.Schemas.FunctionCallStatus + /// The identifier of the actor that created the item. + /// + /// + /// - Remark: Generated from `#/components/schemas/FunctionToolCallResource/value2/created_by`. + public var createdBy: Swift.String? /// Creates a new `Value2Payload`. /// /// - Parameters: /// - id: The unique ID of the function tool call. - public init(id: Swift.String) { + /// - status: The status of the item. One of `in_progress`, `completed`, or + /// - createdBy: The identifier of the actor that created the item. + public init( + id: Swift.String, + status: Components.Schemas.FunctionCallStatus, + createdBy: Swift.String? = nil + ) { self.id = id + self.status = status + self.createdBy = createdBy } public enum CodingKeys: String, CodingKey { case id + case status + case createdBy = "created_by" } } /// - Remark: Generated from `#/components/schemas/FunctionToolCallResource/value2`. @@ -2378,16 +2699,16 @@ public enum Components { self.value1 = value1 self.value2 = value2 } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { self.value1 = try .init(from: decoder) self.value2 = try .init(from: decoder) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try self.value1.encode(to: encoder) try self.value2.encode(to: encoder) } } - /// A tool that generates images using a model like `gpt-image-1`. + /// A tool that generates images using the GPT image models. /// /// /// - Remark: Generated from `#/components/schemas/ImageGenTool`. @@ -2404,16 +2725,65 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ImageGenTool/type`. public var _type: Components.Schemas.ImageGenTool._TypePayload - /// The image generation model to use. Default: `gpt-image-1`. - /// - /// /// - Remark: Generated from `#/components/schemas/ImageGenTool/model`. - @frozen public enum ModelPayload: String, Codable, Hashable, Sendable, CaseIterable { - case gptImage1 = "gpt-image-1" + public struct ModelPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/ImageGenTool/model/value1`. + public var value1: Swift.String? + /// The image generation model to use. Default: `gpt-image-1`. + /// + /// + /// - Remark: Generated from `#/components/schemas/ImageGenTool/model/value2`. + @frozen public enum Value2Payload: String, Codable, Hashable, Sendable, CaseIterable { + case gptImage1 = "gpt-image-1" + case gptImage1Mini = "gpt-image-1-mini" + case gptImage1_5 = "gpt-image-1.5" + } + /// The image generation model to use. Default: `gpt-image-1`. + /// + /// + /// - Remark: Generated from `#/components/schemas/ImageGenTool/model/value2`. + public var value2: Components.Schemas.ImageGenTool.ModelPayload.Value2Payload? + /// Creates a new `ModelPayload`. + /// + /// - Parameters: + /// - value1: + /// - value2: The image generation model to use. Default: `gpt-image-1`. + public init( + value1: Swift.String? = nil, + value2: Components.Schemas.ImageGenTool.ModelPayload.Value2Payload? = nil + ) { + self.value1 = value1 + self.value2 = value2 + } + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self.value1 = try decoder.decodeFromSingleValueContainer() + } catch { + errors.append(error) + } + do { + self.value2 = try decoder.decodeFromSingleValueContainer() + } catch { + errors.append(error) + } + try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( + [ + self.value1, + self.value2 + ], + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Swift.Encoder) throws { + try encoder.encodeFirstNonNilValueToSingleValueContainer([ + self.value1, + self.value2 + ]) + } } - /// The image generation model to use. Default: `gpt-image-1`. - /// - /// /// - Remark: Generated from `#/components/schemas/ImageGenTool/model`. public var model: Components.Schemas.ImageGenTool.ModelPayload? /// The quality of the generated image. One of `low`, `medium`, `high`, @@ -2500,6 +2870,10 @@ 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` /// (string, optional) and `file_id` (string, optional). /// @@ -2532,7 +2906,7 @@ public enum Components { case imageUrl = "image_url" case fileId = "file_id" } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.imageUrl = try container.decodeIfPresent( Swift.String.self, @@ -2559,19 +2933,26 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ImageGenTool/partial_images`. public var partialImages: Swift.Int? + /// Whether to generate a new image or edit an existing image. Default: `auto`. + /// + /// + /// - Remark: Generated from `#/components/schemas/ImageGenTool/action`. + public var action: Components.Schemas.ImageGenActionEnum? /// Creates a new `ImageGenTool`. /// /// - Parameters: /// - _type: The type of the image generation tool. Always `image_generation`. - /// - model: The image generation model to use. Default: `gpt-image-1`. + /// - model: /// - quality: The quality of the generated image. One of `low`, `medium`, `high`, /// - size: The size of the generated image. One of `1024x1024`, `1024x1536`, /// - outputFormat: The output format of the generated image. One of `png`, `webp`, or /// - outputCompression: Compression level for the output image. Default: 100. /// - moderation: Moderation level for the generated image. Default: `auto`. /// - background: Background type for the generated image. One of `transparent`, + /// - inputFidelity: /// - inputImageMask: Optional mask for inpainting. Contains `image_url` /// - partialImages: Number of partial images to generate in streaming mode, from 0 (default value) to 3. + /// - action: Whether to generate a new image or edit an existing image. Default: `auto`. public init( _type: Components.Schemas.ImageGenTool._TypePayload, model: Components.Schemas.ImageGenTool.ModelPayload? = nil, @@ -2581,8 +2962,10 @@ public enum Components { outputCompression: Swift.Int? = nil, moderation: Components.Schemas.ImageGenTool.ModerationPayload? = nil, background: Components.Schemas.ImageGenTool.BackgroundPayload? = nil, + inputFidelity: Components.Schemas.InputFidelity? = nil, inputImageMask: Components.Schemas.ImageGenTool.InputImageMaskPayload? = nil, - partialImages: Swift.Int? = nil + partialImages: Swift.Int? = nil, + action: Components.Schemas.ImageGenActionEnum? = nil ) { self._type = _type self.model = model @@ -2592,8 +2975,10 @@ public enum Components { self.outputCompression = outputCompression self.moderation = moderation self.background = background + self.inputFidelity = inputFidelity self.inputImageMask = inputImageMask self.partialImages = partialImages + self.action = action } public enum CodingKeys: String, CodingKey { case _type = "type" @@ -2604,8 +2989,10 @@ public enum Components { case outputCompression = "output_compression" case moderation case background + case inputFidelity = "input_fidelity" case inputImageMask = "input_image_mask" case partialImages = "partial_images" + case action } } /// An image generation request made by the model. @@ -2645,9 +3032,7 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ImageGenToolCall/status`. public var status: Components.Schemas.ImageGenToolCall.StatusPayload - /// The generated image encoded in base64. - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ImageGenToolCall/result`. public var result: Swift.String? /// Creates a new `ImageGenToolCall`. @@ -2656,7 +3041,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: The generated image encoded in base64. + /// - result: public init( _type: Components.Schemas.ImageGenToolCall._TypePayload, id: Swift.String, @@ -2675,70 +3060,45 @@ public enum Components { case result } } - /// Specify additional output data to include in the model response. Currently - /// supported values are: - /// - `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. - /// - `computer_call_output.output.image_url`: Include image urls from the computer call output. - /// - `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). - /// - `code_interpreter_call.outputs`: Includes the outputs of python code execution - /// in code interpreter tool call items. - /// - /// - /// - Remark: Generated from `#/components/schemas/Includable`. - @frozen public enum Includable: String, Codable, Hashable, Sendable, CaseIterable { - case fileSearchCall_results = "file_search_call.results" - case message_inputImage_imageUrl = "message.input_image.image_url" - case computerCallOutput_output_imageUrl = "computer_call_output.output.image_url" - case reasoning_encryptedContent = "reasoning.encrypted_content" - case codeInterpreterCall_outputs = "code_interpreter_call.outputs" - } /// - Remark: Generated from `#/components/schemas/InputContent`. @frozen public enum InputContent: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/InputContent/case1`. - case InputTextContent(Components.Schemas.InputTextContent) - /// - Remark: Generated from `#/components/schemas/InputContent/case2`. - case InputImageContent(Components.Schemas.InputImageContent) - /// - Remark: Generated from `#/components/schemas/InputContent/case3`. - case InputFileContent(Components.Schemas.InputFileContent) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self = .InputTextContent(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .InputImageContent(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .InputFileContent(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - throw Swift.DecodingError.failedToDecodeOneOfSchema( - type: Self.self, - codingPath: decoder.codingPath, - errors: errors + /// - Remark: Generated from `#/components/schemas/InputContent/InputTextContent`. + case inputTextContent(Components.Schemas.InputTextContent) + /// - Remark: Generated from `#/components/schemas/InputContent/InputImageContent`. + case inputImageContent(Components.Schemas.InputImageContent) + /// - Remark: Generated from `#/components/schemas/InputContent/InputFileContent`. + case inputFileContent(Components.Schemas.InputFileContent) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type ) + switch discriminator { + case "InputTextContent", "#/components/schemas/InputTextContent": + self = .inputTextContent(try .init(from: decoder)) + case "InputImageContent", "#/components/schemas/InputImageContent": + self = .inputImageContent(try .init(from: decoder)) + case "InputFileContent", "#/components/schemas/InputFileContent": + self = .inputFileContent(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { - case let .InputTextContent(value): + case let .inputTextContent(value): try value.encode(to: encoder) - case let .InputImageContent(value): + case let .inputImageContent(value): try value.encode(to: encoder) - case let .InputFileContent(value): + case let .inputFileContent(value): try value.encode(to: encoder) } } @@ -2754,7 +3114,7 @@ public enum Components { public enum CodingKeys: String, CodingKey { case _type = "type" } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let discriminator = try container.decode( Swift.String.self, @@ -2775,7 +3135,7 @@ public enum Components { ) } } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .easyInputMessage(value): try value.encode(to: encoder) @@ -2904,15 +3264,68 @@ public enum Components { self.value1 = value1 self.value2 = value2 } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { self.value1 = try .init(from: decoder) self.value2 = try .init(from: decoder) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try self.value1.encode(to: encoder) try self.value2.encode(to: encoder) } } + /// Text, image, or file inputs to the model, used to generate a response. + /// + /// Learn more: + /// - [Text inputs and outputs](/docs/guides/text) + /// - [Image inputs](/docs/guides/images) + /// - [File inputs](/docs/guides/pdf-files) + /// - [Conversation state](/docs/guides/conversation-state) + /// - [Function calling](/docs/guides/function-calling) + /// + /// + /// - Remark: Generated from `#/components/schemas/InputParam`. + @frozen public enum InputParam: Codable, Hashable, Sendable { + /// A text input to the model, equivalent to a text input with the + /// `user` role. + /// + /// + /// - Remark: Generated from `#/components/schemas/InputParam/case1`. + case case1(Swift.String) + /// A list of one or many input items to the model, containing + /// different content types. + /// + /// + /// - Remark: Generated from `#/components/schemas/InputParam/case2`. + case case2([Components.Schemas.InputItem]) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self = .case1(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .case2(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .case1(value): + try encoder.encodeToSingleValueContainer(value) + case let .case2(value): + try encoder.encodeToSingleValueContainer(value) + } + } + } /// Content item used to generate a response. /// /// @@ -2934,8 +3347,14 @@ public enum Components { case functionToolCall(Components.Schemas.FunctionToolCall) /// - Remark: Generated from `#/components/schemas/Item/FunctionCallOutputItemParam`. case functionCallOutputItemParam(Components.Schemas.FunctionCallOutputItemParam) + /// - Remark: Generated from `#/components/schemas/Item/ToolSearchCallItemParam`. + case toolSearchCallItemParam(Components.Schemas.ToolSearchCallItemParam) + /// - Remark: Generated from `#/components/schemas/Item/ToolSearchOutputItemParam`. + case toolSearchOutputItemParam(Components.Schemas.ToolSearchOutputItemParam) /// - Remark: Generated from `#/components/schemas/Item/ReasoningItem`. case reasoningItem(Components.Schemas.ReasoningItem) + /// - Remark: Generated from `#/components/schemas/Item/CompactionSummaryItemParam`. + case compactionSummaryItemParam(Components.Schemas.CompactionSummaryItemParam) /// - Remark: Generated from `#/components/schemas/Item/ImageGenToolCall`. case imageGenToolCall(Components.Schemas.ImageGenToolCall) /// - Remark: Generated from `#/components/schemas/Item/CodeInterpreterToolCall`. @@ -2944,6 +3363,14 @@ public enum Components { case localShellToolCall(Components.Schemas.LocalShellToolCall) /// - Remark: Generated from `#/components/schemas/Item/LocalShellToolCallOutput`. case localShellToolCallOutput(Components.Schemas.LocalShellToolCallOutput) + /// - Remark: Generated from `#/components/schemas/Item/FunctionShellCallItemParam`. + case functionShellCallItemParam(Components.Schemas.FunctionShellCallItemParam) + /// - Remark: Generated from `#/components/schemas/Item/FunctionShellCallOutputItemParam`. + case functionShellCallOutputItemParam(Components.Schemas.FunctionShellCallOutputItemParam) + /// - Remark: Generated from `#/components/schemas/Item/ApplyPatchToolCallItemParam`. + case applyPatchToolCallItemParam(Components.Schemas.ApplyPatchToolCallItemParam) + /// - Remark: Generated from `#/components/schemas/Item/ApplyPatchToolCallOutputItemParam`. + case applyPatchToolCallOutputItemParam(Components.Schemas.ApplyPatchToolCallOutputItemParam) /// - Remark: Generated from `#/components/schemas/Item/MCPListTools`. case mcpListTools(Components.Schemas.MCPListTools) /// - Remark: Generated from `#/components/schemas/Item/MCPApprovalRequest`. @@ -2952,10 +3379,14 @@ public enum Components { case mcpApprovalResponse(Components.Schemas.MCPApprovalResponse) /// - Remark: Generated from `#/components/schemas/Item/MCPToolCall`. case mcpToolCall(Components.Schemas.MCPToolCall) + /// - Remark: Generated from `#/components/schemas/Item/CustomToolCallOutput`. + case customToolCallOutput(Components.Schemas.CustomToolCallOutput) + /// - Remark: Generated from `#/components/schemas/Item/CustomToolCall`. + case customToolCall(Components.Schemas.CustomToolCall) public enum CodingKeys: String, CodingKey { case _type = "type" } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let discriminator = try container.decode( Swift.String.self, @@ -2978,8 +3409,14 @@ public enum Components { self = .functionToolCall(try .init(from: decoder)) case "FunctionCallOutputItemParam", "#/components/schemas/FunctionCallOutputItemParam": self = .functionCallOutputItemParam(try .init(from: decoder)) + case "ToolSearchCallItemParam", "#/components/schemas/ToolSearchCallItemParam": + self = .toolSearchCallItemParam(try .init(from: decoder)) + case "ToolSearchOutputItemParam", "#/components/schemas/ToolSearchOutputItemParam": + self = .toolSearchOutputItemParam(try .init(from: decoder)) case "ReasoningItem", "#/components/schemas/ReasoningItem": self = .reasoningItem(try .init(from: decoder)) + case "CompactionSummaryItemParam", "#/components/schemas/CompactionSummaryItemParam": + self = .compactionSummaryItemParam(try .init(from: decoder)) case "ImageGenToolCall", "#/components/schemas/ImageGenToolCall": self = .imageGenToolCall(try .init(from: decoder)) case "CodeInterpreterToolCall", "#/components/schemas/CodeInterpreterToolCall": @@ -2988,6 +3425,14 @@ public enum Components { self = .localShellToolCall(try .init(from: decoder)) case "LocalShellToolCallOutput", "#/components/schemas/LocalShellToolCallOutput": self = .localShellToolCallOutput(try .init(from: decoder)) + case "FunctionShellCallItemParam", "#/components/schemas/FunctionShellCallItemParam": + self = .functionShellCallItemParam(try .init(from: decoder)) + case "FunctionShellCallOutputItemParam", "#/components/schemas/FunctionShellCallOutputItemParam": + self = .functionShellCallOutputItemParam(try .init(from: decoder)) + case "ApplyPatchToolCallItemParam", "#/components/schemas/ApplyPatchToolCallItemParam": + self = .applyPatchToolCallItemParam(try .init(from: decoder)) + case "ApplyPatchToolCallOutputItemParam", "#/components/schemas/ApplyPatchToolCallOutputItemParam": + self = .applyPatchToolCallOutputItemParam(try .init(from: decoder)) case "MCPListTools", "#/components/schemas/MCPListTools": self = .mcpListTools(try .init(from: decoder)) case "MCPApprovalRequest", "#/components/schemas/MCPApprovalRequest": @@ -2996,6 +3441,10 @@ public enum Components { self = .mcpApprovalResponse(try .init(from: decoder)) case "MCPToolCall", "#/components/schemas/MCPToolCall": self = .mcpToolCall(try .init(from: decoder)) + case "CustomToolCallOutput", "#/components/schemas/CustomToolCallOutput": + self = .customToolCallOutput(try .init(from: decoder)) + case "CustomToolCall", "#/components/schemas/CustomToolCall": + self = .customToolCall(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( discriminatorKey: CodingKeys._type, @@ -3004,7 +3453,7 @@ public enum Components { ) } } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .inputMessage(value): try value.encode(to: encoder) @@ -3022,8 +3471,14 @@ public enum Components { try value.encode(to: encoder) case let .functionCallOutputItemParam(value): try value.encode(to: encoder) + case let .toolSearchCallItemParam(value): + try value.encode(to: encoder) + case let .toolSearchOutputItemParam(value): + try value.encode(to: encoder) case let .reasoningItem(value): try value.encode(to: encoder) + case let .compactionSummaryItemParam(value): + try value.encode(to: encoder) case let .imageGenToolCall(value): try value.encode(to: encoder) case let .codeInterpreterToolCall(value): @@ -3032,6 +3487,14 @@ public enum Components { try value.encode(to: encoder) case let .localShellToolCallOutput(value): try value.encode(to: encoder) + case let .functionShellCallItemParam(value): + try value.encode(to: encoder) + case let .functionShellCallOutputItemParam(value): + try value.encode(to: encoder) + case let .applyPatchToolCallItemParam(value): + try value.encode(to: encoder) + case let .applyPatchToolCallOutputItemParam(value): + try value.encode(to: encoder) case let .mcpListTools(value): try value.encode(to: encoder) case let .mcpApprovalRequest(value): @@ -3040,6 +3503,10 @@ public enum Components { try value.encode(to: encoder) case let .mcpToolCall(value): try value.encode(to: encoder) + case let .customToolCallOutput(value): + try value.encode(to: encoder) + case let .customToolCall(value): + try value.encode(to: encoder) } } } @@ -3064,6 +3531,14 @@ public enum Components { case functionToolCallResource(Components.Schemas.FunctionToolCallResource) /// - Remark: Generated from `#/components/schemas/ItemResource/FunctionToolCallOutputResource`. case functionToolCallOutputResource(Components.Schemas.FunctionToolCallOutputResource) + /// - Remark: Generated from `#/components/schemas/ItemResource/ToolSearchCall`. + case toolSearchCall(Components.Schemas.ToolSearchCall) + /// - Remark: Generated from `#/components/schemas/ItemResource/ToolSearchOutput`. + case toolSearchOutput(Components.Schemas.ToolSearchOutput) + /// - Remark: Generated from `#/components/schemas/ItemResource/ReasoningItem`. + case reasoningItem(Components.Schemas.ReasoningItem) + /// - Remark: Generated from `#/components/schemas/ItemResource/CompactionBody`. + case compactionBody(Components.Schemas.CompactionBody) /// - Remark: Generated from `#/components/schemas/ItemResource/ImageGenToolCall`. case imageGenToolCall(Components.Schemas.ImageGenToolCall) /// - Remark: Generated from `#/components/schemas/ItemResource/CodeInterpreterToolCall`. @@ -3072,6 +3547,14 @@ public enum Components { case localShellToolCall(Components.Schemas.LocalShellToolCall) /// - Remark: Generated from `#/components/schemas/ItemResource/LocalShellToolCallOutput`. case localShellToolCallOutput(Components.Schemas.LocalShellToolCallOutput) + /// - Remark: Generated from `#/components/schemas/ItemResource/FunctionShellCall`. + case functionShellCall(Components.Schemas.FunctionShellCall) + /// - Remark: Generated from `#/components/schemas/ItemResource/FunctionShellCallOutput`. + case functionShellCallOutput(Components.Schemas.FunctionShellCallOutput) + /// - Remark: Generated from `#/components/schemas/ItemResource/ApplyPatchToolCall`. + case applyPatchToolCall(Components.Schemas.ApplyPatchToolCall) + /// - Remark: Generated from `#/components/schemas/ItemResource/ApplyPatchToolCallOutput`. + case applyPatchToolCallOutput(Components.Schemas.ApplyPatchToolCallOutput) /// - Remark: Generated from `#/components/schemas/ItemResource/MCPListTools`. case mcpListTools(Components.Schemas.MCPListTools) /// - Remark: Generated from `#/components/schemas/ItemResource/MCPApprovalRequest`. @@ -3080,10 +3563,14 @@ public enum Components { case mcpApprovalResponseResource(Components.Schemas.MCPApprovalResponseResource) /// - Remark: Generated from `#/components/schemas/ItemResource/MCPToolCall`. case mcpToolCall(Components.Schemas.MCPToolCall) + /// - Remark: Generated from `#/components/schemas/ItemResource/CustomToolCallResource`. + case customToolCallResource(Components.Schemas.CustomToolCallResource) + /// - Remark: Generated from `#/components/schemas/ItemResource/CustomToolCallOutputResource`. + case customToolCallOutputResource(Components.Schemas.CustomToolCallOutputResource) public enum CodingKeys: String, CodingKey { case _type = "type" } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let discriminator = try container.decode( Swift.String.self, @@ -3106,6 +3593,14 @@ public enum Components { self = .functionToolCallResource(try .init(from: decoder)) case "FunctionToolCallOutputResource", "#/components/schemas/FunctionToolCallOutputResource": self = .functionToolCallOutputResource(try .init(from: decoder)) + case "ToolSearchCall", "#/components/schemas/ToolSearchCall": + self = .toolSearchCall(try .init(from: decoder)) + case "ToolSearchOutput", "#/components/schemas/ToolSearchOutput": + self = .toolSearchOutput(try .init(from: decoder)) + case "ReasoningItem", "#/components/schemas/ReasoningItem": + self = .reasoningItem(try .init(from: decoder)) + case "CompactionBody", "#/components/schemas/CompactionBody": + self = .compactionBody(try .init(from: decoder)) case "ImageGenToolCall", "#/components/schemas/ImageGenToolCall": self = .imageGenToolCall(try .init(from: decoder)) case "CodeInterpreterToolCall", "#/components/schemas/CodeInterpreterToolCall": @@ -3114,6 +3609,14 @@ public enum Components { self = .localShellToolCall(try .init(from: decoder)) case "LocalShellToolCallOutput", "#/components/schemas/LocalShellToolCallOutput": self = .localShellToolCallOutput(try .init(from: decoder)) + case "FunctionShellCall", "#/components/schemas/FunctionShellCall": + self = .functionShellCall(try .init(from: decoder)) + case "FunctionShellCallOutput", "#/components/schemas/FunctionShellCallOutput": + self = .functionShellCallOutput(try .init(from: decoder)) + case "ApplyPatchToolCall", "#/components/schemas/ApplyPatchToolCall": + self = .applyPatchToolCall(try .init(from: decoder)) + case "ApplyPatchToolCallOutput", "#/components/schemas/ApplyPatchToolCallOutput": + self = .applyPatchToolCallOutput(try .init(from: decoder)) case "MCPListTools", "#/components/schemas/MCPListTools": self = .mcpListTools(try .init(from: decoder)) case "MCPApprovalRequest", "#/components/schemas/MCPApprovalRequest": @@ -3122,6 +3625,10 @@ public enum Components { self = .mcpApprovalResponseResource(try .init(from: decoder)) case "MCPToolCall", "#/components/schemas/MCPToolCall": self = .mcpToolCall(try .init(from: decoder)) + case "CustomToolCallResource", "#/components/schemas/CustomToolCallResource": + self = .customToolCallResource(try .init(from: decoder)) + case "CustomToolCallOutputResource", "#/components/schemas/CustomToolCallOutputResource": + self = .customToolCallOutputResource(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( discriminatorKey: CodingKeys._type, @@ -3130,7 +3637,7 @@ public enum Components { ) } } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .inputMessageResource(value): try value.encode(to: encoder) @@ -3148,6 +3655,14 @@ public enum Components { try value.encode(to: encoder) case let .functionToolCallOutputResource(value): try value.encode(to: encoder) + case let .toolSearchCall(value): + try value.encode(to: encoder) + case let .toolSearchOutput(value): + try value.encode(to: encoder) + case let .reasoningItem(value): + try value.encode(to: encoder) + case let .compactionBody(value): + try value.encode(to: encoder) case let .imageGenToolCall(value): try value.encode(to: encoder) case let .codeInterpreterToolCall(value): @@ -3156,6 +3671,14 @@ public enum Components { try value.encode(to: encoder) case let .localShellToolCallOutput(value): try value.encode(to: encoder) + case let .functionShellCall(value): + try value.encode(to: encoder) + case let .functionShellCallOutput(value): + try value.encode(to: encoder) + case let .applyPatchToolCall(value): + try value.encode(to: encoder) + case let .applyPatchToolCallOutput(value): + try value.encode(to: encoder) case let .mcpListTools(value): try value.encode(to: encoder) case let .mcpApprovalRequest(value): @@ -3164,273 +3687,113 @@ public enum Components { try value.encode(to: encoder) case let .mcpToolCall(value): try value.encode(to: encoder) + case let .customToolCallResource(value): + try value.encode(to: encoder) + case let .customToolCallOutputResource(value): + try value.encode(to: encoder) } } } - /// A collection of keypresses the model would like to perform. + /// A tool call to run a command on the local shell. /// /// - /// - Remark: Generated from `#/components/schemas/KeyPress`. - public struct KeyPress: Codable, Hashable, Sendable { - /// Specifies the event type. For a keypress action, this property is - /// always set to `keypress`. + /// - Remark: Generated from `#/components/schemas/LocalShellToolCall`. + public struct LocalShellToolCall: Codable, Hashable, Sendable { + /// The type of the local shell call. Always `local_shell_call`. /// /// - /// - Remark: Generated from `#/components/schemas/KeyPress/type`. + /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case keypress = "keypress" + case localShellCall = "local_shell_call" } - /// Specifies the event type. For a keypress action, this property is - /// always set to `keypress`. + /// The type of the local shell call. Always `local_shell_call`. /// /// - /// - Remark: Generated from `#/components/schemas/KeyPress/type`. - public var _type: Components.Schemas.KeyPress._TypePayload - /// The combination of keys the model is requesting to be pressed. This is an - /// array of strings, each representing a key. + /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/type`. + public var _type: Components.Schemas.LocalShellToolCall._TypePayload + /// The unique ID of the local shell call. /// /// - /// - Remark: Generated from `#/components/schemas/KeyPress/keys`. - public var keys: [Swift.String] - /// Creates a new `KeyPress`. + /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/id`. + public var id: Swift.String + /// The unique ID of the local shell tool call generated by the model. + /// + /// + /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/call_id`. + public var callId: Swift.String + /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/action`. + public var action: Components.Schemas.LocalShellExecAction + /// The status of the local shell call. + /// + /// + /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/status`. + @frozen public enum StatusPayload: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + case incomplete = "incomplete" + } + /// The status of the local shell call. + /// + /// + /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/status`. + public var status: Components.Schemas.LocalShellToolCall.StatusPayload + /// Creates a new `LocalShellToolCall`. /// /// - Parameters: - /// - _type: Specifies the event type. For a keypress action, this property is - /// - keys: The combination of keys the model is requesting to be pressed. This is an + /// - _type: The type of the local shell call. Always `local_shell_call`. + /// - id: The unique ID of the local shell call. + /// - callId: The unique ID of the local shell tool call generated by the model. + /// - action: + /// - status: The status of the local shell call. public init( - _type: Components.Schemas.KeyPress._TypePayload, - keys: [Swift.String] + _type: Components.Schemas.LocalShellToolCall._TypePayload, + id: Swift.String, + callId: Swift.String, + action: Components.Schemas.LocalShellExecAction, + status: Components.Schemas.LocalShellToolCall.StatusPayload ) { self._type = _type - self.keys = keys + self.id = id + self.callId = callId + self.action = action + self.status = status } public enum CodingKeys: String, CodingKey { case _type = "type" - case keys + case id + case callId = "call_id" + case action + case status } } - /// Execute a shell command on the server. + /// The output of a local shell tool call. /// /// - /// - Remark: Generated from `#/components/schemas/LocalShellExecAction`. - public struct LocalShellExecAction: Codable, Hashable, Sendable { - /// The type of the local shell action. Always `exec`. + /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput`. + public struct LocalShellToolCallOutput: Codable, Hashable, Sendable { + /// The type of the local shell tool call output. Always `local_shell_call_output`. /// /// - /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/type`. + /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case exec = "exec" + case localShellCallOutput = "local_shell_call_output" } - /// The type of the local shell action. Always `exec`. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/type`. - public var _type: Components.Schemas.LocalShellExecAction._TypePayload - /// The command to run. + /// The type of the local shell tool call output. Always `local_shell_call_output`. /// /// - /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/command`. - public var command: [Swift.String] - /// Optional timeout in milliseconds for the command. + /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput/type`. + public var _type: Components.Schemas.LocalShellToolCallOutput._TypePayload + /// The unique ID of the local shell tool call generated by the model. /// /// - /// - 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/LocalShellToolCallOutput/id`. + public var id: Swift.String + /// A JSON string of the output of the local shell tool call. /// /// - /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/working_directory`. - public var workingDirectory: Swift.String? - /// Environment variables to set for the command. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/env`. - public struct EnvPayload: Codable, Hashable, Sendable { - /// A container of undocumented properties. - public var additionalProperties: [String: Swift.String] - /// Creates a new `EnvPayload`. - /// - /// - Parameters: - /// - additionalProperties: A container of undocumented properties. - public init(additionalProperties: [String: Swift.String] = .init()) { - self.additionalProperties = additionalProperties - } - public init(from decoder: any Decoder) throws { - additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeAdditionalProperties(additionalProperties) - } - } - /// Environment variables to set for the command. - /// - /// - /// - 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`. - /// - /// - Parameters: - /// - _type: The type of the local shell action. Always `exec`. - /// - command: The command to run. - /// - 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: Optional user to run the command as. - public init( - _type: Components.Schemas.LocalShellExecAction._TypePayload, - command: [Swift.String], - timeoutMs: Swift.Int? = nil, - workingDirectory: Swift.String? = nil, - env: Components.Schemas.LocalShellExecAction.EnvPayload, - user: Swift.String? = nil - ) { - self._type = _type - self.command = command - self.timeoutMs = timeoutMs - self.workingDirectory = workingDirectory - self.env = env - self.user = user - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case command - case timeoutMs = "timeout_ms" - case workingDirectory = "working_directory" - case env - case user - } - } - /// A tool that allows the model to execute shell commands in a local environment. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellTool`. - public struct LocalShellTool: Codable, Hashable, Sendable { - /// The type of the local shell tool. Always `local_shell`. - /// - /// - Remark: Generated from `#/components/schemas/LocalShellTool/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case localShell = "local_shell" - } - /// The type of the local shell tool. Always `local_shell`. - /// - /// - Remark: Generated from `#/components/schemas/LocalShellTool/type`. - public var _type: Components.Schemas.LocalShellTool._TypePayload - /// Creates a new `LocalShellTool`. - /// - /// - Parameters: - /// - _type: The type of the local shell tool. Always `local_shell`. - public init(_type: Components.Schemas.LocalShellTool._TypePayload) { - self._type = _type - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - } - } - /// A tool call to run a command on the local shell. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCall`. - public struct LocalShellToolCall: Codable, Hashable, Sendable { - /// The type of the local shell call. Always `local_shell_call`. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case localShellCall = "local_shell_call" - } - /// The type of the local shell call. Always `local_shell_call`. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/type`. - public var _type: Components.Schemas.LocalShellToolCall._TypePayload - /// The unique ID of the local shell call. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/id`. - public var id: Swift.String - /// The unique ID of the local shell tool call generated by the model. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/call_id`. - public var callId: Swift.String - /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/action`. - public var action: Components.Schemas.LocalShellExecAction - /// The status of the local shell call. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/status`. - @frozen public enum StatusPayload: String, Codable, Hashable, Sendable, CaseIterable { - case inProgress = "in_progress" - case completed = "completed" - case incomplete = "incomplete" - } - /// The status of the local shell call. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCall/status`. - public var status: Components.Schemas.LocalShellToolCall.StatusPayload - /// Creates a new `LocalShellToolCall`. - /// - /// - Parameters: - /// - _type: The type of the local shell call. Always `local_shell_call`. - /// - id: The unique ID of the local shell call. - /// - callId: The unique ID of the local shell tool call generated by the model. - /// - action: - /// - status: The status of the local shell call. - public init( - _type: Components.Schemas.LocalShellToolCall._TypePayload, - id: Swift.String, - callId: Swift.String, - action: Components.Schemas.LocalShellExecAction, - status: Components.Schemas.LocalShellToolCall.StatusPayload - ) { - self._type = _type - self.id = id - self.callId = callId - self.action = action - self.status = status - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case id - case callId = "call_id" - case action - case status - } - } - /// The output of a local shell tool call. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput`. - public struct LocalShellToolCallOutput: Codable, Hashable, Sendable { - /// The type of the local shell tool call output. Always `local_shell_call_output`. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case localShellCallOutput = "local_shell_call_output" - } - /// The type of the local shell tool call output. Always `local_shell_call_output`. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput/type`. - public var _type: Components.Schemas.LocalShellToolCallOutput._TypePayload - /// The unique ID of the local shell tool call generated by the model. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput/id`. - public var id: Swift.String - /// A JSON string of the output of the local shell tool call. - /// - /// - /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput/output`. - public var output: Swift.String - /// The status of the item. One of `in_progress`, `completed`, or `incomplete`. + /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput/output`. + public var output: Swift.String + /// The status of the item. One of `in_progress`, `completed`, or `incomplete`. /// /// /// - Remark: Generated from `#/components/schemas/LocalShellToolCallOutput/status`. @@ -3439,9 +3802,6 @@ 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`. @@ -3450,7 +3810,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: The status of the item. One of `in_progress`, `completed`, or `incomplete`. + /// - status: public init( _type: Components.Schemas.LocalShellToolCallOutput._TypePayload, id: Swift.String, @@ -3552,9 +3912,7 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/type`. public var _type: Components.Schemas.MCPApprovalResponse._TypePayload - /// The unique ID of the approval response - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/id`. public var id: Swift.String? /// The ID of the approval request being answered. @@ -3567,19 +3925,17 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/approve`. public var approve: Swift.Bool - /// Optional reason for the decision. - /// - /// + public typealias String = Swift.String /// - 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: The unique ID of the approval response + /// - id: /// - approvalRequestId: The ID of the approval request being answered. /// - approve: Whether the request was approved. - /// - reason: Optional reason for the decision. + /// - reason: public init( _type: Components.Schemas.MCPApprovalResponse._TypePayload, id: Swift.String? = nil, @@ -3633,9 +3989,7 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponseResource/approve`. public var approve: Swift.Bool - /// Optional reason for the decision. - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPApprovalResponseResource/reason`. public var reason: Swift.String? /// Creates a new `MCPApprovalResponseResource`. @@ -3645,7 +3999,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: Optional reason for the decision. + /// - reason: public init( _type: Components.Schemas.MCPApprovalResponseResource._TypePayload, id: Swift.String, @@ -3699,9 +4053,7 @@ 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. - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPListTools/error`. public var error: Swift.String? /// Creates a new `MCPListTools`. @@ -3711,7 +4063,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 message if the server could not list tools. + /// - error: public init( _type: Components.Schemas.MCPListTools._TypePayload, id: Swift.String, @@ -3743,9 +4095,7 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/name`. public var name: Swift.String - /// The description of the tool. - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/description`. public var description: Swift.String? /// The JSON schema describing the tool's input. @@ -3753,18 +4103,16 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/input_schema`. public var inputSchema: OpenAPIRuntime.OpenAPIObjectContainer - /// Additional annotations about the tool. - /// - /// + public typealias OpenAPIObjectContainer = OpenAPIRuntime.OpenAPIObjectContainer /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/annotations`. public var annotations: OpenAPIRuntime.OpenAPIObjectContainer? /// Creates a new `MCPListToolsTool`. /// /// - Parameters: /// - name: The name of the tool. - /// - description: The description of the tool. + /// - description: /// - inputSchema: The JSON schema describing the tool's input. - /// - annotations: Additional annotations about the tool. + /// - annotations: public init( name: Swift.String, description: Swift.String? = nil, @@ -3804,11 +4152,69 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPTool/server_label`. public var serverLabel: Swift.String - /// The URL for the MCP server. + /// The URL for the MCP server. One of `server_url` or `connector_id` must be + /// provided. /// /// /// - Remark: Generated from `#/components/schemas/MCPTool/server_url`. - public var serverUrl: Swift.String + public var serverUrl: Swift.String? + /// Identifier for service connectors, like those available in ChatGPT. One of + /// `server_url` or `connector_id` must be provided. Learn more about service + /// connectors [here](/docs/guides/tools-remote-mcp#connectors). + /// + /// Currently supported `connector_id` values are: + /// + /// - Dropbox: `connector_dropbox` + /// - Gmail: `connector_gmail` + /// - Google Calendar: `connector_googlecalendar` + /// - Google Drive: `connector_googledrive` + /// - Microsoft Teams: `connector_microsoftteams` + /// - Outlook Calendar: `connector_outlookcalendar` + /// - Outlook Email: `connector_outlookemail` + /// - SharePoint: `connector_sharepoint` + /// + /// + /// - Remark: Generated from `#/components/schemas/MCPTool/connector_id`. + @frozen public enum ConnectorIdPayload: String, Codable, Hashable, Sendable, CaseIterable { + case connectorDropbox = "connector_dropbox" + case connectorGmail = "connector_gmail" + case connectorGooglecalendar = "connector_googlecalendar" + case connectorGoogledrive = "connector_googledrive" + case connectorMicrosoftteams = "connector_microsoftteams" + case connectorOutlookcalendar = "connector_outlookcalendar" + case connectorOutlookemail = "connector_outlookemail" + case connectorSharepoint = "connector_sharepoint" + } + /// Identifier for service connectors, like those available in ChatGPT. One of + /// `server_url` or `connector_id` must be provided. Learn more about service + /// connectors [here](/docs/guides/tools-remote-mcp#connectors). + /// + /// Currently supported `connector_id` values are: + /// + /// - Dropbox: `connector_dropbox` + /// - Gmail: `connector_gmail` + /// - Google Calendar: `connector_googlecalendar` + /// - Google Drive: `connector_googledrive` + /// - Microsoft Teams: `connector_microsoftteams` + /// - Outlook Calendar: `connector_outlookcalendar` + /// - Outlook Email: `connector_outlookemail` + /// - SharePoint: `connector_sharepoint` + /// + /// + /// - Remark: Generated from `#/components/schemas/MCPTool/connector_id`. + public var connectorId: Components.Schemas.MCPTool.ConnectorIdPayload? + /// An OAuth access token that can be used with a remote MCP server, either + /// with a custom MCP server URL or a service connector. Your application + /// must handle the OAuth authorization flow and provide the token here. + /// + /// + /// - Remark: Generated from `#/components/schemas/MCPTool/authorization`. + public var authorization: Swift.String? + /// Optional description of the MCP server, used to provide more context. + /// + /// + /// - Remark: Generated from `#/components/schemas/MCPTool/server_description`. + public var serverDescription: Swift.String? /// Optional HTTP headers to send to the MCP server. Use for authentication /// or other purposes. /// @@ -3824,17 +4230,13 @@ public enum Components { public init(additionalProperties: [String: Swift.String] = .init()) { self.additionalProperties = additionalProperties } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { 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. @@ -3846,43 +4248,10 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPTool/allowed_tools/case1`. case case1([Swift.String]) - /// A filter object to specify which tools are allowed. - /// - /// - /// - Remark: Generated from `#/components/schemas/MCPTool/allowed_tools/case2`. - public struct Case2Payload: Codable, Hashable, Sendable { - /// List of allowed tool names. - /// - /// - Remark: Generated from `#/components/schemas/MCPTool/allowed_tools/case2/tool_names`. - public var toolNames: [Swift.String]? - /// Creates a new `Case2Payload`. - /// - /// - Parameters: - /// - toolNames: List of allowed tool names. - public init(toolNames: [Swift.String]? = nil) { - self.toolNames = toolNames - } - public enum CodingKeys: String, CodingKey { - case toolNames = "tool_names" - } - public init(from decoder: any Decoder) throws { - let container = try decoder.container(keyedBy: CodingKeys.self) - self.toolNames = try container.decodeIfPresent( - [Swift.String].self, - forKey: .toolNames - ) - try decoder.ensureNoAdditionalProperties(knownKeys: [ - "tool_names" - ]) - } - } - /// A filter object to specify which tools are allowed. - /// - /// /// - Remark: Generated from `#/components/schemas/MCPTool/allowed_tools/case2`. - case case2(Components.Schemas.MCPTool.AllowedToolsPayload.Case2Payload) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + case MCPToolFilter(Components.Schemas.MCPToolFilter) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self = .case1(try decoder.decodeFromSingleValueContainer()) return @@ -3890,7 +4259,7 @@ public enum Components { errors.append(error) } do { - self = .case2(try .init(from: decoder)) + self = .MCPToolFilter(try .init(from: decoder)) return } catch { errors.append(error) @@ -3901,84 +4270,40 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .case1(value): try encoder.encodeToSingleValueContainer(value) - case let .case2(value): + case let .MCPToolFilter(value): try value.encode(to: encoder) } } } - /// 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. /// /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval`. @frozen public enum RequireApprovalPayload: Codable, Hashable, Sendable { + /// Specify which of the MCP server's tools require approval. Can be + /// `always`, `never`, or a filter object associated with tools + /// that require approval. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval/case1`. public struct Case1Payload: Codable, Hashable, Sendable { - /// A list of tools that always require approval. - /// - /// /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval/case1/always`. - public struct AlwaysPayload: Codable, Hashable, Sendable { - /// List of tools that require approval. - /// - /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval/case1/always/tool_names`. - public var toolNames: [Swift.String]? - /// Creates a new `AlwaysPayload`. - /// - /// - Parameters: - /// - toolNames: List of tools that require approval. - public init(toolNames: [Swift.String]? = nil) { - self.toolNames = toolNames - } - public enum CodingKeys: String, CodingKey { - case toolNames = "tool_names" - } - } - /// A list of tools that always require approval. - /// - /// - /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval/case1/always`. - public var always: Components.Schemas.MCPTool.RequireApprovalPayload.Case1Payload.AlwaysPayload? - /// A list of tools that never require approval. - /// - /// + public var always: Components.Schemas.MCPToolFilter? /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval/case1/never`. - public struct NeverPayload: Codable, Hashable, Sendable { - /// List of tools that do not require approval. - /// - /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval/case1/never/tool_names`. - public var toolNames: [Swift.String]? - /// Creates a new `NeverPayload`. - /// - /// - Parameters: - /// - toolNames: List of tools that do not require approval. - public init(toolNames: [Swift.String]? = nil) { - self.toolNames = toolNames - } - public enum CodingKeys: String, CodingKey { - case toolNames = "tool_names" - } - } - /// A list of tools that never require approval. - /// - /// - /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval/case1/never`. - public var never: Components.Schemas.MCPTool.RequireApprovalPayload.Case1Payload.NeverPayload? + public var never: Components.Schemas.MCPToolFilter? /// Creates a new `Case1Payload`. /// /// - Parameters: - /// - always: A list of tools that always require approval. - /// - never: A list of tools that never require approval. + /// - always: + /// - never: public init( - always: Components.Schemas.MCPTool.RequireApprovalPayload.Case1Payload.AlwaysPayload? = nil, - never: Components.Schemas.MCPTool.RequireApprovalPayload.Case1Payload.NeverPayload? = nil + always: Components.Schemas.MCPToolFilter? = nil, + never: Components.Schemas.MCPToolFilter? = nil ) { self.always = always self.never = never @@ -3987,14 +4312,14 @@ public enum Components { case always case never } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self.always = try container.decodeIfPresent( - Components.Schemas.MCPTool.RequireApprovalPayload.Case1Payload.AlwaysPayload.self, + Components.Schemas.MCPToolFilter.self, forKey: .always ) self.never = try container.decodeIfPresent( - Components.Schemas.MCPTool.RequireApprovalPayload.Case1Payload.NeverPayload.self, + Components.Schemas.MCPToolFilter.self, forKey: .never ) try decoder.ensureNoAdditionalProperties(knownKeys: [ @@ -4003,6 +4328,11 @@ public enum Components { ]) } } + /// Specify which of the MCP server's tools require approval. Can be + /// `always`, `never`, or a filter object associated with tools + /// that require approval. + /// + /// /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval/case1`. case case1(Components.Schemas.MCPTool.RequireApprovalPayload.Case1Payload) /// Specify a single approval policy for all tools. One of `always` or @@ -4022,8 +4352,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPTool/require_approval/case2`. case case2(Components.Schemas.MCPTool.RequireApprovalPayload.Case2Payload) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self = .case1(try .init(from: decoder)) return @@ -4042,7 +4372,7 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .case1(value): try value.encode(to: encoder) @@ -4051,41 +4381,60 @@ 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. + /// + /// + /// - Remark: Generated from `#/components/schemas/MCPTool/defer_loading`. + public var deferLoading: Swift.Bool? /// Creates a new `MCPTool`. /// /// - Parameters: /// - _type: The type of the MCP tool. Always `mcp`. /// - serverLabel: A label for this MCP server, used to identify it in tool calls. - /// - serverUrl: The URL for the MCP server. - /// - 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. + /// - serverUrl: The URL for the MCP server. One of `server_url` or `connector_id` must be + /// - 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: + /// - deferLoading: Whether this MCP tool is deferred and discovered via tool search. public init( _type: Components.Schemas.MCPTool._TypePayload, serverLabel: Swift.String, - serverUrl: Swift.String, + serverUrl: Swift.String? = nil, + connectorId: Components.Schemas.MCPTool.ConnectorIdPayload? = nil, + authorization: Swift.String? = nil, + serverDescription: Swift.String? = nil, headers: Components.Schemas.MCPTool.HeadersPayload? = nil, allowedTools: Components.Schemas.MCPTool.AllowedToolsPayload? = nil, - requireApproval: Components.Schemas.MCPTool.RequireApprovalPayload? = nil + requireApproval: Components.Schemas.MCPTool.RequireApprovalPayload? = nil, + deferLoading: Swift.Bool? = nil ) { self._type = _type self.serverLabel = serverLabel self.serverUrl = serverUrl + self.connectorId = connectorId + self.authorization = authorization + self.serverDescription = serverDescription self.headers = headers self.allowedTools = allowedTools self.requireApproval = requireApproval + self.deferLoading = deferLoading } public enum CodingKeys: String, CodingKey { case _type = "type" case serverLabel = "server_label" case serverUrl = "server_url" + case connectorId = "connector_id" + case authorization + case serverDescription = "server_description" case headers case allowedTools = "allowed_tools" case requireApproval = "require_approval" + case deferLoading = "defer_loading" } } /// An invocation of a tool on an MCP server. @@ -4125,16 +4474,20 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPToolCall/arguments`. public var arguments: Swift.String - /// The output from the tool call. - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPToolCall/output`. public var output: Swift.String? - /// The error from the tool call, if any. - /// - /// + public typealias String = Swift.String /// - 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`. + /// + /// + /// - Remark: Generated from `#/components/schemas/MCPToolCall/status`. + public var status: Components.Schemas.MCPToolCallStatus? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/MCPToolCall/approval_request_id`. + public var approvalRequestId: Swift.String? /// Creates a new `MCPToolCall`. /// /// - Parameters: @@ -4143,8 +4496,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: The output from the tool call. - /// - error: The error from the tool call, if any. + /// - output: + /// - error: + /// - status: The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`, or `failed`. + /// - approvalRequestId: public init( _type: Components.Schemas.MCPToolCall._TypePayload, id: Swift.String, @@ -4152,7 +4507,9 @@ public enum Components { name: Swift.String, arguments: Swift.String, output: Swift.String? = nil, - error: Swift.String? = nil + error: Swift.String? = nil, + status: Components.Schemas.MCPToolCallStatus? = nil, + approvalRequestId: Swift.String? = nil ) { self._type = _type self.id = id @@ -4161,6 +4518,8 @@ public enum Components { self.arguments = arguments self.output = output self.error = error + self.status = status + self.approvalRequestId = approvalRequestId } public enum CodingKeys: String, CodingKey { case _type = "type" @@ -4170,8 +4529,68 @@ public enum Components { case arguments case output case error + case status + case approvalRequestId = "approval_request_id" } } + /// A filter object to specify which tools are allowed. + /// + /// + /// - Remark: Generated from `#/components/schemas/MCPToolFilter`. + public struct MCPToolFilter: Codable, Hashable, Sendable { + /// List of allowed tool names. + /// + /// - Remark: Generated from `#/components/schemas/MCPToolFilter/tool_names`. + public var toolNames: [Swift.String]? + /// Indicates whether or not a tool modifies data or is read-only. If an + /// MCP server is [annotated with `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + /// it will match this filter. + /// + /// + /// - Remark: Generated from `#/components/schemas/MCPToolFilter/read_only`. + public var readOnly: Swift.Bool? + /// Creates a new `MCPToolFilter`. + /// + /// - Parameters: + /// - toolNames: List of allowed tool names. + /// - readOnly: Indicates whether or not a tool modifies data or is read-only. If an + public init( + toolNames: [Swift.String]? = nil, + readOnly: Swift.Bool? = nil + ) { + self.toolNames = toolNames + self.readOnly = readOnly + } + public enum CodingKeys: String, CodingKey { + case toolNames = "tool_names" + case readOnly = "read_only" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + self.toolNames = try container.decodeIfPresent( + [Swift.String].self, + forKey: .toolNames + ) + self.readOnly = try container.decodeIfPresent( + Swift.Bool.self, + forKey: .readOnly + ) + try decoder.ensureNoAdditionalProperties(knownKeys: [ + "tool_names", + "read_only" + ]) + } + } + /// Labels an `assistant` message as intermediate commentary (`commentary`) or the final answer (`final_answer`). + /// For models like `gpt-5.3-codex` and beyond, when sending follow-up requests, preserve and resend + /// phase on all assistant messages — dropping it can degrade performance. Not used for user messages. + /// + /// + /// - Remark: Generated from `#/components/schemas/MessagePhase`. + @frozen public enum MessagePhase: String, Codable, Hashable, Sendable, CaseIterable { + case commentary = "commentary" + case finalAnswer = "final_answer" + } /// Set of 16 key-value pairs that can be attached to an object. This can be /// useful for storing additional information about the object in a structured /// format, and querying for objects via API or the dashboard. @@ -4191,10 +4610,10 @@ public enum Components { public init(additionalProperties: [String: Swift.String] = .init()) { self.additionalProperties = additionalProperties } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try encoder.encodeAdditionalProperties(additionalProperties) } } @@ -4208,8 +4627,16 @@ public enum Components { case o1Pro20250319 = "o1-pro-2025-03-19" case o3Pro = "o3-pro" case o3Pro20250610 = "o3-pro-2025-06-10" + case o3DeepResearch = "o3-deep-research" + case o3DeepResearch20250626 = "o3-deep-research-2025-06-26" + case o4MiniDeepResearch = "o4-mini-deep-research" + case o4MiniDeepResearch20250626 = "o4-mini-deep-research-2025-06-26" case computerUsePreview = "computer-use-preview" case computerUsePreview20250311 = "computer-use-preview-2025-03-11" + case gpt5Codex = "gpt-5-codex" + case gpt5Pro = "gpt-5-pro" + case gpt5Pro20251006 = "gpt-5-pro-2025-10-06" + case gpt5_1CodexMax = "gpt-5.1-codex-max" } /// - Remark: Generated from `#/components/schemas/ModelIdsResponses/value2`. public var value2: Components.Schemas.ModelIdsResponses.Value2Payload? @@ -4225,8 +4652,8 @@ public enum Components { self.value1 = value1 self.value2 = value2 } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self.value1 = try decoder.decodeFromSingleValueContainer() } catch { @@ -4247,7 +4674,7 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try encoder.encodeFirstNonNilValueToSingleValueContainer([ self.value1, self.value2 @@ -4260,6 +4687,29 @@ public enum Components { public var value1: Swift.String? /// - Remark: Generated from `#/components/schemas/ModelIdsShared/value2`. @frozen public enum Value2Payload: String, Codable, Hashable, Sendable, CaseIterable { + case gpt5_4 = "gpt-5.4" + case gpt5_4Mini = "gpt-5.4-mini" + case gpt5_4Nano = "gpt-5.4-nano" + case gpt5_4Mini20260317 = "gpt-5.4-mini-2026-03-17" + case gpt5_4Nano20260317 = "gpt-5.4-nano-2026-03-17" + case gpt5_3ChatLatest = "gpt-5.3-chat-latest" + case gpt5_2 = "gpt-5.2" + case gpt5_220251211 = "gpt-5.2-2025-12-11" + case gpt5_2ChatLatest = "gpt-5.2-chat-latest" + case gpt5_2Pro = "gpt-5.2-pro" + case gpt5_2Pro20251211 = "gpt-5.2-pro-2025-12-11" + case gpt5_1 = "gpt-5.1" + case gpt5_120251113 = "gpt-5.1-2025-11-13" + case gpt5_1Codex = "gpt-5.1-codex" + case gpt5_1Mini = "gpt-5.1-mini" + case gpt5_1ChatLatest = "gpt-5.1-chat-latest" + case gpt5 = "gpt-5" + case gpt5Mini = "gpt-5-mini" + case gpt5Nano = "gpt-5-nano" + case gpt520250807 = "gpt-5-2025-08-07" + case gpt5Mini20250807 = "gpt-5-mini-2025-08-07" + case gpt5Nano20250807 = "gpt-5-nano-2025-08-07" + case gpt5ChatLatest = "gpt-5-chat-latest" case gpt4_1 = "gpt-4.1" case gpt4_1Mini = "gpt-4.1-mini" case gpt4_1Nano = "gpt-4.1-nano" @@ -4330,8 +4780,8 @@ public enum Components { self.value1 = value1 self.value2 = value2 } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self.value1 = try decoder.decodeFromSingleValueContainer() } catch { @@ -4352,7 +4802,7 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try encoder.encodeFirstNonNilValueToSingleValueContainer([ self.value1, self.value2 @@ -4363,393 +4813,438 @@ public enum Components { public struct ModelResponseProperties: Codable, Hashable, Sendable { /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/metadata`. public var metadata: Components.Schemas.Metadata? - /// 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. - /// - /// + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/top_logprobs`. + public var topLogprobs: Swift.Int? + public typealias Double = Swift.Double /// - 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. - /// - /// + public typealias Double = Swift.Double /// - 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. /// A stable identifier for your end-users. - /// Used to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#end-user-ids). + /// Used to boost cache hit rates by better bucketing similar requests and to help OpenAI detect and prevent abuse. [Learn more](/docs/guides/safety-best-practices#safety-identifiers). /// /// /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/user`. + @available(*, deprecated) public var user: Swift.String? + /// A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies. + /// The IDs should be a string that uniquely identifies each user, with a maximum length of 64 characters. We recommend hashing their username or email address, in order to avoid sending us any identifying information. [Learn more](/docs/guides/safety-best-practices#safety-identifiers). + /// + /// + /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/safety_identifier`. + public var safetyIdentifier: Swift.String? + /// 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). + /// + /// + /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/prompt_cache_key`. + public var promptCacheKey: Swift.String? /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/service_tier`. public var serviceTier: Components.Schemas.ServiceTier? + /// 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`. + @frozen public enum PromptCacheRetentionPayload: String, Codable, Hashable, Sendable, CaseIterable { + case inMemory = "in-memory" + case _24h = "24h" + } + /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/prompt_cache_retention`. + public var promptCacheRetention: Components.Schemas.ModelResponseProperties.PromptCacheRetentionPayload? /// Creates a new `ModelResponseProperties`. /// /// - Parameters: /// - metadata: - /// - 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: A stable identifier for your end-users. + /// - topLogprobs: + /// - temperature: + /// - topP: + /// - 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: public init( metadata: Components.Schemas.Metadata? = nil, + topLogprobs: Swift.Int? = nil, temperature: Swift.Double? = nil, topP: Swift.Double? = nil, user: Swift.String? = nil, - serviceTier: Components.Schemas.ServiceTier? = nil + safetyIdentifier: Swift.String? = nil, + promptCacheKey: Swift.String? = nil, + serviceTier: Components.Schemas.ServiceTier? = nil, + promptCacheRetention: Components.Schemas.ModelResponseProperties.PromptCacheRetentionPayload? = nil ) { self.metadata = metadata + self.topLogprobs = topLogprobs self.temperature = temperature self.topP = topP self.user = user + self.safetyIdentifier = safetyIdentifier + self.promptCacheKey = promptCacheKey self.serviceTier = serviceTier + self.promptCacheRetention = promptCacheRetention } public enum CodingKeys: String, CodingKey { case metadata + case topLogprobs = "top_logprobs" case temperature case topP = "top_p" case user + case safetyIdentifier = "safety_identifier" + case promptCacheKey = "prompt_cache_key" case serviceTier = "service_tier" + case promptCacheRetention = "prompt_cache_retention" } } - /// A mouse move action. + /// - Remark: Generated from `#/components/schemas/OutputContent`. + @frozen public enum OutputContent: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/OutputContent/OutputTextContent`. + case outputTextContent(Components.Schemas.OutputTextContent) + /// - Remark: Generated from `#/components/schemas/OutputContent/RefusalContent`. + case refusalContent(Components.Schemas.RefusalContent) + /// - Remark: Generated from `#/components/schemas/OutputContent/ReasoningTextContent`. + case reasoningTextContent(Components.Schemas.ReasoningTextContent) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "OutputTextContent", "#/components/schemas/OutputTextContent": + self = .outputTextContent(try .init(from: decoder)) + case "RefusalContent", "#/components/schemas/RefusalContent": + self = .refusalContent(try .init(from: decoder)) + case "ReasoningTextContent", "#/components/schemas/ReasoningTextContent": + self = .reasoningTextContent(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .outputTextContent(value): + try value.encode(to: encoder) + case let .refusalContent(value): + try value.encode(to: encoder) + case let .reasoningTextContent(value): + try value.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/OutputItem`. + @frozen public enum OutputItem: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/OutputItem/OutputMessage`. + case outputMessage(Components.Schemas.OutputMessage) + /// - Remark: Generated from `#/components/schemas/OutputItem/FileSearchToolCall`. + case fileSearchToolCall(Components.Schemas.FileSearchToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/FunctionToolCall`. + case functionToolCall(Components.Schemas.FunctionToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/FunctionToolCallOutputResource`. + case functionToolCallOutputResource(Components.Schemas.FunctionToolCallOutputResource) + /// - Remark: Generated from `#/components/schemas/OutputItem/WebSearchToolCall`. + case webSearchToolCall(Components.Schemas.WebSearchToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/ComputerToolCall`. + case computerToolCall(Components.Schemas.ComputerToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/ComputerToolCallOutputResource`. + case computerToolCallOutputResource(Components.Schemas.ComputerToolCallOutputResource) + /// - Remark: Generated from `#/components/schemas/OutputItem/ReasoningItem`. + case reasoningItem(Components.Schemas.ReasoningItem) + /// - Remark: Generated from `#/components/schemas/OutputItem/ToolSearchCall`. + case toolSearchCall(Components.Schemas.ToolSearchCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/ToolSearchOutput`. + case toolSearchOutput(Components.Schemas.ToolSearchOutput) + /// - Remark: Generated from `#/components/schemas/OutputItem/CompactionBody`. + case compactionBody(Components.Schemas.CompactionBody) + /// - Remark: Generated from `#/components/schemas/OutputItem/ImageGenToolCall`. + case imageGenToolCall(Components.Schemas.ImageGenToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/CodeInterpreterToolCall`. + case codeInterpreterToolCall(Components.Schemas.CodeInterpreterToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/LocalShellToolCall`. + case localShellToolCall(Components.Schemas.LocalShellToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/LocalShellToolCallOutput`. + case localShellToolCallOutput(Components.Schemas.LocalShellToolCallOutput) + /// - Remark: Generated from `#/components/schemas/OutputItem/FunctionShellCall`. + case functionShellCall(Components.Schemas.FunctionShellCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/FunctionShellCallOutput`. + case functionShellCallOutput(Components.Schemas.FunctionShellCallOutput) + /// - Remark: Generated from `#/components/schemas/OutputItem/ApplyPatchToolCall`. + case applyPatchToolCall(Components.Schemas.ApplyPatchToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/ApplyPatchToolCallOutput`. + case applyPatchToolCallOutput(Components.Schemas.ApplyPatchToolCallOutput) + /// - Remark: Generated from `#/components/schemas/OutputItem/MCPToolCall`. + case mcpToolCall(Components.Schemas.MCPToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/MCPListTools`. + case mcpListTools(Components.Schemas.MCPListTools) + /// - Remark: Generated from `#/components/schemas/OutputItem/MCPApprovalRequest`. + case mcpApprovalRequest(Components.Schemas.MCPApprovalRequest) + /// - Remark: Generated from `#/components/schemas/OutputItem/MCPApprovalResponseResource`. + case mcpApprovalResponseResource(Components.Schemas.MCPApprovalResponseResource) + /// - Remark: Generated from `#/components/schemas/OutputItem/CustomToolCall`. + case customToolCall(Components.Schemas.CustomToolCall) + /// - Remark: Generated from `#/components/schemas/OutputItem/CustomToolCallOutputResource`. + case customToolCallOutputResource(Components.Schemas.CustomToolCallOutputResource) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "OutputMessage", "#/components/schemas/OutputMessage": + self = .outputMessage(try .init(from: decoder)) + case "FileSearchToolCall", "#/components/schemas/FileSearchToolCall": + self = .fileSearchToolCall(try .init(from: decoder)) + case "FunctionToolCall", "#/components/schemas/FunctionToolCall": + self = .functionToolCall(try .init(from: decoder)) + case "FunctionToolCallOutputResource", "#/components/schemas/FunctionToolCallOutputResource": + self = .functionToolCallOutputResource(try .init(from: decoder)) + case "WebSearchToolCall", "#/components/schemas/WebSearchToolCall": + self = .webSearchToolCall(try .init(from: decoder)) + case "ComputerToolCall", "#/components/schemas/ComputerToolCall": + self = .computerToolCall(try .init(from: decoder)) + case "ComputerToolCallOutputResource", "#/components/schemas/ComputerToolCallOutputResource": + self = .computerToolCallOutputResource(try .init(from: decoder)) + case "ReasoningItem", "#/components/schemas/ReasoningItem": + self = .reasoningItem(try .init(from: decoder)) + case "ToolSearchCall", "#/components/schemas/ToolSearchCall": + self = .toolSearchCall(try .init(from: decoder)) + case "ToolSearchOutput", "#/components/schemas/ToolSearchOutput": + self = .toolSearchOutput(try .init(from: decoder)) + case "CompactionBody", "#/components/schemas/CompactionBody": + self = .compactionBody(try .init(from: decoder)) + case "ImageGenToolCall", "#/components/schemas/ImageGenToolCall": + self = .imageGenToolCall(try .init(from: decoder)) + case "CodeInterpreterToolCall", "#/components/schemas/CodeInterpreterToolCall": + self = .codeInterpreterToolCall(try .init(from: decoder)) + case "LocalShellToolCall", "#/components/schemas/LocalShellToolCall": + self = .localShellToolCall(try .init(from: decoder)) + case "LocalShellToolCallOutput", "#/components/schemas/LocalShellToolCallOutput": + self = .localShellToolCallOutput(try .init(from: decoder)) + case "FunctionShellCall", "#/components/schemas/FunctionShellCall": + self = .functionShellCall(try .init(from: decoder)) + case "FunctionShellCallOutput", "#/components/schemas/FunctionShellCallOutput": + self = .functionShellCallOutput(try .init(from: decoder)) + case "ApplyPatchToolCall", "#/components/schemas/ApplyPatchToolCall": + self = .applyPatchToolCall(try .init(from: decoder)) + case "ApplyPatchToolCallOutput", "#/components/schemas/ApplyPatchToolCallOutput": + self = .applyPatchToolCallOutput(try .init(from: decoder)) + case "MCPToolCall", "#/components/schemas/MCPToolCall": + self = .mcpToolCall(try .init(from: decoder)) + case "MCPListTools", "#/components/schemas/MCPListTools": + self = .mcpListTools(try .init(from: decoder)) + case "MCPApprovalRequest", "#/components/schemas/MCPApprovalRequest": + self = .mcpApprovalRequest(try .init(from: decoder)) + case "MCPApprovalResponseResource", "#/components/schemas/MCPApprovalResponseResource": + self = .mcpApprovalResponseResource(try .init(from: decoder)) + case "CustomToolCall", "#/components/schemas/CustomToolCall": + self = .customToolCall(try .init(from: decoder)) + case "CustomToolCallOutputResource", "#/components/schemas/CustomToolCallOutputResource": + self = .customToolCallOutputResource(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .outputMessage(value): + try value.encode(to: encoder) + case let .fileSearchToolCall(value): + try value.encode(to: encoder) + case let .functionToolCall(value): + try value.encode(to: encoder) + case let .functionToolCallOutputResource(value): + try value.encode(to: encoder) + case let .webSearchToolCall(value): + try value.encode(to: encoder) + case let .computerToolCall(value): + try value.encode(to: encoder) + case let .computerToolCallOutputResource(value): + try value.encode(to: encoder) + case let .reasoningItem(value): + try value.encode(to: encoder) + case let .toolSearchCall(value): + try value.encode(to: encoder) + case let .toolSearchOutput(value): + try value.encode(to: encoder) + case let .compactionBody(value): + try value.encode(to: encoder) + case let .imageGenToolCall(value): + try value.encode(to: encoder) + case let .codeInterpreterToolCall(value): + try value.encode(to: encoder) + case let .localShellToolCall(value): + try value.encode(to: encoder) + case let .localShellToolCallOutput(value): + try value.encode(to: encoder) + case let .functionShellCall(value): + try value.encode(to: encoder) + case let .functionShellCallOutput(value): + try value.encode(to: encoder) + case let .applyPatchToolCall(value): + try value.encode(to: encoder) + case let .applyPatchToolCallOutput(value): + try value.encode(to: encoder) + case let .mcpToolCall(value): + try value.encode(to: encoder) + case let .mcpListTools(value): + try value.encode(to: encoder) + case let .mcpApprovalRequest(value): + try value.encode(to: encoder) + case let .mcpApprovalResponseResource(value): + try value.encode(to: encoder) + case let .customToolCall(value): + try value.encode(to: encoder) + case let .customToolCallOutputResource(value): + try value.encode(to: encoder) + } + } + } + /// An output message from the model. /// /// - /// - Remark: Generated from `#/components/schemas/Move`. - public struct Move: Codable, Hashable, Sendable { - /// Specifies the event type. For a move action, this property is - /// always set to `move`. + /// - Remark: Generated from `#/components/schemas/OutputMessage`. + public struct OutputMessage: Codable, Hashable, Sendable { + /// The unique ID of the output message. + /// + /// + /// - Remark: Generated from `#/components/schemas/OutputMessage/id`. + public var id: Swift.String + /// The type of the output message. Always `message`. /// /// - /// - Remark: Generated from `#/components/schemas/Move/type`. + /// - Remark: Generated from `#/components/schemas/OutputMessage/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case move = "move" + case message = "message" } - /// Specifies the event type. For a move action, this property is - /// always set to `move`. + /// The type of the output message. Always `message`. /// /// - /// - Remark: Generated from `#/components/schemas/Move/type`. - public var _type: Components.Schemas.Move._TypePayload - /// The x-coordinate to move to. + /// - Remark: Generated from `#/components/schemas/OutputMessage/type`. + public var _type: Components.Schemas.OutputMessage._TypePayload + /// The role of the output message. Always `assistant`. /// /// - /// - Remark: Generated from `#/components/schemas/Move/x`. - public var x: Swift.Int - /// The y-coordinate to move to. + /// - Remark: Generated from `#/components/schemas/OutputMessage/role`. + @frozen public enum RolePayload: String, Codable, Hashable, Sendable, CaseIterable { + case assistant = "assistant" + } + /// The role of the output message. Always `assistant`. /// /// - /// - Remark: Generated from `#/components/schemas/Move/y`. - public var y: Swift.Int - /// Creates a new `Move`. + /// - Remark: Generated from `#/components/schemas/OutputMessage/role`. + public var role: Components.Schemas.OutputMessage.RolePayload + /// The content of the output message. + /// + /// + /// - 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 + /// `incomplete`. Populated when input items are returned via API. + /// + /// + /// - Remark: Generated from `#/components/schemas/OutputMessage/status`. + @frozen public enum StatusPayload: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + case incomplete = "incomplete" + } + /// The status of the message input. One of `in_progress`, `completed`, or + /// `incomplete`. Populated when input items are returned via API. + /// + /// + /// - Remark: Generated from `#/components/schemas/OutputMessage/status`. + public var status: Components.Schemas.OutputMessage.StatusPayload + /// Creates a new `OutputMessage`. /// /// - Parameters: - /// - _type: Specifies the event type. For a move action, this property is - /// - x: The x-coordinate to move to. - /// - y: The y-coordinate to move to. + /// - id: The unique ID of the output message. + /// - _type: The type of the output message. Always `message`. + /// - role: The role of the output message. Always `assistant`. + /// - content: The content of the output message. + /// - phase: + /// - status: The status of the message input. One of `in_progress`, `completed`, or public init( - _type: Components.Schemas.Move._TypePayload, - x: Swift.Int, - y: Swift.Int + id: Swift.String, + _type: Components.Schemas.OutputMessage._TypePayload, + role: Components.Schemas.OutputMessage.RolePayload, + content: [Components.Schemas.OutputMessageContent], + phase: Components.Schemas.MessagePhase? = nil, + status: Components.Schemas.OutputMessage.StatusPayload ) { + self.id = id self._type = _type - self.x = x - self.y = y + self.role = role + self.content = content + self.phase = phase + self.status = status } public enum CodingKeys: String, CodingKey { + case id case _type = "type" - case x - case y + case role + case content + case phase + case status } } - /// - Remark: Generated from `#/components/schemas/OutputContent`. - @frozen public enum OutputContent: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/OutputContent/case1`. - case OutputTextContent(Components.Schemas.OutputTextContent) - /// - Remark: Generated from `#/components/schemas/OutputContent/case2`. - case RefusalContent(Components.Schemas.RefusalContent) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self = .OutputTextContent(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .RefusalContent(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - throw Swift.DecodingError.failedToDecodeOneOfSchema( - type: Self.self, - codingPath: decoder.codingPath, - errors: errors + /// - Remark: Generated from `#/components/schemas/OutputMessageContent`. + @frozen public enum OutputMessageContent: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/OutputMessageContent/OutputTextContent`. + case outputTextContent(Components.Schemas.OutputTextContent) + /// - Remark: Generated from `#/components/schemas/OutputMessageContent/RefusalContent`. + case refusalContent(Components.Schemas.RefusalContent) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type ) + switch discriminator { + case "OutputTextContent", "#/components/schemas/OutputTextContent": + self = .outputTextContent(try .init(from: decoder)) + case "RefusalContent", "#/components/schemas/RefusalContent": + self = .refusalContent(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { - case let .OutputTextContent(value): + case let .outputTextContent(value): try value.encode(to: encoder) - case let .RefusalContent(value): + case let .refusalContent(value): try value.encode(to: encoder) } } } - /// - Remark: Generated from `#/components/schemas/OutputItem`. - public struct OutputItem: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/OutputItem/value1`. - public var value1: Components.Schemas.OutputMessage? - /// - Remark: Generated from `#/components/schemas/OutputItem/value2`. - public var value2: Components.Schemas.FileSearchToolCall? - /// - Remark: Generated from `#/components/schemas/OutputItem/value3`. - public var value3: Components.Schemas.FunctionToolCall? - /// - Remark: Generated from `#/components/schemas/OutputItem/value4`. - public var value4: Components.Schemas.WebSearchToolCall? - /// - Remark: Generated from `#/components/schemas/OutputItem/value5`. - public var value5: Components.Schemas.ComputerToolCall? - /// - Remark: Generated from `#/components/schemas/OutputItem/value6`. - public var value6: Components.Schemas.ReasoningItem? - /// - Remark: Generated from `#/components/schemas/OutputItem/value7`. - public var value7: Components.Schemas.ImageGenToolCall? - /// - Remark: Generated from `#/components/schemas/OutputItem/value8`. - public var value8: Components.Schemas.CodeInterpreterToolCall? - /// - Remark: Generated from `#/components/schemas/OutputItem/value9`. - public var value9: Components.Schemas.LocalShellToolCall? - /// - Remark: Generated from `#/components/schemas/OutputItem/value10`. - public var value10: Components.Schemas.MCPToolCall? - /// - Remark: Generated from `#/components/schemas/OutputItem/value11`. - public var value11: Components.Schemas.MCPListTools? - /// - Remark: Generated from `#/components/schemas/OutputItem/value12`. - public var value12: Components.Schemas.MCPApprovalRequest? - /// Creates a new `OutputItem`. - /// - /// - Parameters: - /// - value1: - /// - value2: - /// - value3: - /// - value4: - /// - value5: - /// - value6: - /// - value7: - /// - value8: - /// - value9: - /// - value10: - /// - value11: - /// - value12: - public init( - value1: Components.Schemas.OutputMessage? = nil, - value2: Components.Schemas.FileSearchToolCall? = nil, - value3: Components.Schemas.FunctionToolCall? = nil, - value4: Components.Schemas.WebSearchToolCall? = nil, - value5: Components.Schemas.ComputerToolCall? = nil, - value6: Components.Schemas.ReasoningItem? = nil, - value7: Components.Schemas.ImageGenToolCall? = nil, - value8: Components.Schemas.CodeInterpreterToolCall? = nil, - value9: Components.Schemas.LocalShellToolCall? = nil, - value10: Components.Schemas.MCPToolCall? = nil, - value11: Components.Schemas.MCPListTools? = nil, - value12: Components.Schemas.MCPApprovalRequest? = nil - ) { - self.value1 = value1 - self.value2 = value2 - self.value3 = value3 - self.value4 = value4 - self.value5 = value5 - self.value6 = value6 - self.value7 = value7 - self.value8 = value8 - self.value9 = value9 - self.value10 = value10 - self.value11 = value11 - self.value12 = value12 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value3 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value4 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value5 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value6 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value7 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value8 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value9 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value10 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value11 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value12 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2, - self.value3, - self.value4, - self.value5, - self.value6, - self.value7, - self.value8, - self.value9, - self.value10, - self.value11, - self.value12 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try self.value1?.encode(to: encoder) - try self.value2?.encode(to: encoder) - try self.value3?.encode(to: encoder) - try self.value4?.encode(to: encoder) - try self.value5?.encode(to: encoder) - try self.value6?.encode(to: encoder) - try self.value7?.encode(to: encoder) - try self.value8?.encode(to: encoder) - try self.value9?.encode(to: encoder) - try self.value10?.encode(to: encoder) - try self.value11?.encode(to: encoder) - try self.value12?.encode(to: encoder) - } - } - /// An output message from the model. - /// - /// - /// - Remark: Generated from `#/components/schemas/OutputMessage`. - public struct OutputMessage: Codable, Hashable, Sendable { - /// The unique ID of the output message. - /// - /// - /// - Remark: Generated from `#/components/schemas/OutputMessage/id`. - public var id: Swift.String - /// The type of the output message. Always `message`. - /// - /// - /// - Remark: Generated from `#/components/schemas/OutputMessage/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case message = "message" - } - /// The type of the output message. Always `message`. - /// - /// - /// - Remark: Generated from `#/components/schemas/OutputMessage/type`. - public var _type: Components.Schemas.OutputMessage._TypePayload - /// The role of the output message. Always `assistant`. - /// - /// - /// - Remark: Generated from `#/components/schemas/OutputMessage/role`. - @frozen public enum RolePayload: String, Codable, Hashable, Sendable, CaseIterable { - case assistant = "assistant" - } - /// The role of the output message. Always `assistant`. - /// - /// - /// - Remark: Generated from `#/components/schemas/OutputMessage/role`. - public var role: Components.Schemas.OutputMessage.RolePayload - /// The content of the output message. - /// - /// - /// - Remark: Generated from `#/components/schemas/OutputMessage/content`. - public var content: [Components.Schemas.OutputContent] - /// The status of the message input. One of `in_progress`, `completed`, or - /// `incomplete`. Populated when input items are returned via API. - /// - /// - /// - Remark: Generated from `#/components/schemas/OutputMessage/status`. - @frozen public enum StatusPayload: String, Codable, Hashable, Sendable, CaseIterable { - case inProgress = "in_progress" - case completed = "completed" - case incomplete = "incomplete" - } - /// The status of the message input. One of `in_progress`, `completed`, or - /// `incomplete`. Populated when input items are returned via API. - /// - /// - /// - Remark: Generated from `#/components/schemas/OutputMessage/status`. - public var status: Components.Schemas.OutputMessage.StatusPayload - /// Creates a new `OutputMessage`. - /// - /// - Parameters: - /// - id: The unique ID of the output message. - /// - _type: The type of the output message. Always `message`. - /// - role: The role of the output message. Always `assistant`. - /// - content: The content of the output message. - /// - status: The status of the message input. One of `in_progress`, `completed`, or - public init( - id: Swift.String, - _type: Components.Schemas.OutputMessage._TypePayload, - role: Components.Schemas.OutputMessage.RolePayload, - content: [Components.Schemas.OutputContent], - status: Components.Schemas.OutputMessage.StatusPayload - ) { - self.id = id - self._type = _type - self.role = role - self.content = content - self.status = status - } - public enum CodingKeys: String, CodingKey { - case id - case _type = "type" - case role - case content - case status - } - } /// Reference to a prompt template and its variables. /// [Learn more](/docs/guides/text?api-mode=responses#reusable-prompts). /// @@ -4760,8 +5255,7 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/Prompt/id`. public var id: Swift.String - /// Optional version of the prompt template. - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/Prompt/version`. public var version: Swift.String? /// - Remark: Generated from `#/components/schemas/Prompt/variables`. @@ -4770,7 +5264,7 @@ public enum Components { /// /// - Parameters: /// - id: The unique identifier of the prompt template to use. - /// - version: Optional version of the prompt template. + /// - version: /// - variables: public init( id: Swift.String, @@ -4787,7 +5281,7 @@ public enum Components { case variables } } - /// **o-series models only** + /// **gpt-5 and o-series models only** /// /// Configuration options for /// [reasoning models](https://platform.openai.com/docs/guides/reasoning). @@ -4801,6 +5295,8 @@ public enum Components { /// 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`. @frozen public enum SummaryPayload: String, Codable, Hashable, Sendable, CaseIterable { @@ -4808,11 +5304,6 @@ 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`. - /// - /// /// - Remark: Generated from `#/components/schemas/Reasoning/summary`. public var summary: Components.Schemas.Reasoning.SummaryPayload? /// **Deprecated:** use `summary` instead. @@ -4828,28 +5319,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: A summary of the reasoning performed by the model. This can be - /// - generateSummary: **Deprecated:** use `summary` instead. + /// - summary: + /// - generateSummary: public init( effort: Components.Schemas.ReasoningEffort? = nil, - summary: Components.Schemas.Reasoning.SummaryPayload? = nil + summary: Components.Schemas.Reasoning.SummaryPayload? = nil, + generateSummary: Components.Schemas.Reasoning.GenerateSummaryPayload? = nil ) { self.effort = effort self.summary = summary + self.generateSummary = generateSummary } public enum CodingKeys: String, CodingKey { case effort @@ -4857,14 +5342,17 @@ public enum Components { case generateSummary = "generate_summary" } } - /// **o-series models only** - /// /// Constrains effort on reasoning for /// [reasoning models](https://platform.openai.com/docs/guides/reasoning). - /// Currently supported values are `none`, `minimal`, `low`, `medium`, and `high`. Reducing + /// Currently supported values are `none`, `minimal`, `low`, `medium`, `high`, and `xhigh`. Reducing /// reasoning effort can result in faster responses and fewer tokens used /// on reasoning in a response. /// + /// - `gpt-5.1` defaults to `none`, which does not perform reasoning. The supported reasoning values for `gpt-5.1` are `none`, `low`, `medium`, and `high`. Tool calls are supported for all reasoning values in gpt-5.1. + /// - All models before `gpt-5.1` default to `medium` reasoning effort, and do not support `none`. + /// - The `gpt-5-pro` model defaults to (and only supports) `high` reasoning effort. + /// - `xhigh` is supported for all models after `gpt-5.1-codex-max`. + /// /// /// - Remark: Generated from `#/components/schemas/ReasoningEffort`. @frozen public enum ReasoningEffort: String, Codable, Hashable, Sendable, CaseIterable { @@ -4873,6 +5361,7 @@ public enum Components { case low = "low" case medium = "medium" case high = "high" + case xhigh = "xhigh" } /// A description of the chain of thought used by a reasoning model while generating /// a response. Be sure to include these items in your `input` to the Responses API @@ -4899,59 +5388,19 @@ 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. - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ReasoningItem/encrypted_content`. public var encryptedContent: Swift.String? - /// - Remark: Generated from `#/components/schemas/ReasoningItem/SummaryPayload`. - public struct SummaryPayloadPayload: Codable, Hashable, Sendable { - /// The type of the object. Always `summary_text`. - /// - /// - /// - Remark: Generated from `#/components/schemas/ReasoningItem/SummaryPayload/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case summaryText = "summary_text" - } - /// The type of the object. Always `summary_text`. - /// - /// - /// - Remark: Generated from `#/components/schemas/ReasoningItem/SummaryPayload/type`. - public var _type: Components.Schemas.ReasoningItem.SummaryPayloadPayload._TypePayload - /// A short summary of the reasoning used by the model when generating - /// the response. - /// - /// - /// - Remark: Generated from `#/components/schemas/ReasoningItem/SummaryPayload/text`. - public var text: Swift.String - /// Creates a new `SummaryPayloadPayload`. - /// - /// - Parameters: - /// - _type: The type of the object. Always `summary_text`. - /// - text: A short summary of the reasoning used by the model when generating - public init( - _type: Components.Schemas.ReasoningItem.SummaryPayloadPayload._TypePayload, - text: Swift.String - ) { - self._type = _type - self.text = text - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case text - } - } - /// Reasoning text contents. + /// Reasoning summary content. /// /// /// - Remark: Generated from `#/components/schemas/ReasoningItem/summary`. - public typealias SummaryPayload = [Components.Schemas.ReasoningItem.SummaryPayloadPayload] - /// Reasoning text contents. + public var summary: [Components.Schemas.SummaryTextContent] + /// Reasoning text content. /// /// - /// - Remark: Generated from `#/components/schemas/ReasoningItem/summary`. - public var summary: Components.Schemas.ReasoningItem.SummaryPayload + /// - Remark: Generated from `#/components/schemas/ReasoningItem/content`. + public var content: [Components.Schemas.ReasoningTextContent]? /// The status of the item. One of `in_progress`, `completed`, or /// `incomplete`. Populated when items are returned via API. /// @@ -4973,20 +5422,23 @@ public enum Components { /// - Parameters: /// - _type: The type of the object. Always `reasoning`. /// - id: The unique identifier of the reasoning content. - /// - encryptedContent: The encrypted content of the reasoning item - populated when a response is - /// - summary: Reasoning text contents. + /// - encryptedContent: + /// - summary: Reasoning summary content. + /// - content: Reasoning text content. /// - status: The status of the item. One of `in_progress`, `completed`, or public init( _type: Components.Schemas.ReasoningItem._TypePayload, id: Swift.String, encryptedContent: Swift.String? = nil, - summary: Components.Schemas.ReasoningItem.SummaryPayload, + summary: [Components.Schemas.SummaryTextContent], + content: [Components.Schemas.ReasoningTextContent]? = nil, status: Components.Schemas.ReasoningItem.StatusPayload? = nil ) { self._type = _type self.id = id self.encryptedContent = encryptedContent self.summary = summary + self.content = content self.status = status } public enum CodingKeys: String, CodingKey { @@ -4994,6 +5446,7 @@ public enum Components { case id case encryptedContent = "encrypted_content" case summary + case content case status } } @@ -5046,6 +5499,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/Response/value3/created_at`. public var createdAt: Swift.Double + public typealias Double = Swift.Double + /// - Remark: Generated from `#/components/schemas/Response/value3/completed_at`. + public var completedAt: Swift.Double? /// - Remark: Generated from `#/components/schemas/Response/value3/error`. public var error: Components.Schemas.ResponseError? /// Details about why the response is incomplete. @@ -5075,9 +5531,6 @@ 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. @@ -5113,8 +5566,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/Response/value3/instructions/case2`. case case2([Components.Schemas.InputItem]) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self = .case1(try decoder.decodeFromSingleValueContainer()) return @@ -5133,7 +5586,7 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .case1(value): try encoder.encodeToSingleValueContainer(value) @@ -5142,20 +5595,9 @@ 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. - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/Response/value3/output_text`. public var outputText: Swift.String? /// - Remark: Generated from `#/components/schemas/Response/value3/usage`. @@ -5165,6 +5607,13 @@ 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? + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/Response/value3/max_output_tokens`. + public var maxOutputTokens: Swift.Int? /// Creates a new `Value3Payload`. /// /// - Parameters: @@ -5172,30 +5621,37 @@ 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: /// - error: - /// - incompleteDetails: Details about why the response is incomplete. + /// - incompleteDetails: /// - output: An array of content items generated by the model. - /// - instructions: A system (or developer) message inserted into the model's context. - /// - outputText: SDK-only convenience property that contains the aggregated text output + /// - instructions: + /// - outputText: /// - usage: /// - parallelToolCalls: Whether to allow the model to run tool calls in parallel. + /// - conversation: + /// - maxOutputTokens: public init( id: Swift.String, object: Components.Schemas.Response.Value3Payload.ObjectPayload, status: Components.Schemas.Response.Value3Payload.StatusPayload? = nil, createdAt: Swift.Double, + completedAt: Swift.Double? = nil, error: Components.Schemas.ResponseError? = nil, incompleteDetails: Components.Schemas.Response.Value3Payload.IncompleteDetailsPayload? = nil, output: [Components.Schemas.OutputItem], instructions: Components.Schemas.Response.Value3Payload.InstructionsPayload? = nil, outputText: Swift.String? = nil, usage: Components.Schemas.ResponseUsage? = nil, - parallelToolCalls: Swift.Bool + parallelToolCalls: Swift.Bool, + conversation: Components.Schemas.Conversation2? = nil, + maxOutputTokens: Swift.Int? = nil ) { self.id = id self.object = object self.status = status self.createdAt = createdAt + self.completedAt = completedAt self.error = error self.incompleteDetails = incompleteDetails self.output = output @@ -5203,12 +5659,15 @@ public enum Components { self.outputText = outputText self.usage = usage self.parallelToolCalls = parallelToolCalls + self.conversation = conversation + self.maxOutputTokens = maxOutputTokens } public enum CodingKeys: String, CodingKey { case id case object case status case createdAt = "created_at" + case completedAt = "completed_at" case error case incompleteDetails = "incomplete_details" case output @@ -5216,6 +5675,8 @@ public enum Components { case outputText = "output_text" case usage case parallelToolCalls = "parallel_tool_calls" + case conversation + case maxOutputTokens = "max_output_tokens" } } /// - Remark: Generated from `#/components/schemas/Response/value3`. @@ -5235,12 +5696,12 @@ public enum Components { self.value2 = value2 self.value3 = value3 } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { self.value1 = try .init(from: decoder) self.value2 = try .init(from: decoder) self.value3 = try .init(from: decoder) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try self.value1.encode(to: encoder) try self.value2.encode(to: encoder) try self.value3.encode(to: encoder) @@ -5309,6 +5770,11 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseAudioDoneEvent/type`. public var _type: Components.Schemas.ResponseAudioDoneEvent._TypePayload + /// The ID of the response. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseAudioDoneEvent/response_id`. + public var responseId: Swift.String /// The sequence number of the delta. /// /// @@ -5318,16 +5784,20 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.audio.done`. + /// - responseId: The ID of the response. /// - sequenceNumber: The sequence number of the delta. public init( _type: Components.Schemas.ResponseAudioDoneEvent._TypePayload, + responseId: Swift.String, sequenceNumber: Swift.Int ) { self._type = _type + self.responseId = responseId self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" + case responseId = "response_id" case sequenceNumber = "sequence_number" } } @@ -5347,6 +5817,11 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseAudioTranscriptDeltaEvent/type`. public var _type: Components.Schemas.ResponseAudioTranscriptDeltaEvent._TypePayload + /// The ID of the response. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseAudioTranscriptDeltaEvent/response_id`. + public var responseId: Swift.String /// The partial transcript of the audio response. /// /// @@ -5360,19 +5835,23 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.audio.transcript.delta`. + /// - responseId: The ID of the response. /// - delta: The partial transcript of the audio response. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseAudioTranscriptDeltaEvent._TypePayload, + responseId: Swift.String, delta: Swift.String, sequenceNumber: Swift.Int ) { self._type = _type + self.responseId = responseId self.delta = delta self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" + case responseId = "response_id" case delta case sequenceNumber = "sequence_number" } @@ -5393,6 +5872,11 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseAudioTranscriptDoneEvent/type`. public var _type: Components.Schemas.ResponseAudioTranscriptDoneEvent._TypePayload + /// The ID of the response. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseAudioTranscriptDoneEvent/response_id`. + public var responseId: Swift.String /// The sequence number of this event. /// /// - Remark: Generated from `#/components/schemas/ResponseAudioTranscriptDoneEvent/sequence_number`. @@ -5401,46 +5885,50 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.audio.transcript.done`. + /// - responseId: The ID of the response. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseAudioTranscriptDoneEvent._TypePayload, + responseId: Swift.String, sequenceNumber: Swift.Int ) { self._type = _type + self.responseId = responseId self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" + case responseId = "response_id" case sequenceNumber = "sequence_number" } } - /// Emitted when a partial code snippet is added by the code interpreter. + /// Emitted when a partial code snippet is streamed by the code interpreter. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent`. public struct ResponseCodeInterpreterCallCodeDeltaEvent: Codable, Hashable, Sendable { /// The type of the event. Always `response.code_interpreter_call_code.delta`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { case response_codeInterpreterCallCode_delta = "response.code_interpreter_call_code.delta" } /// The type of the event. Always `response.code_interpreter_call_code.delta`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent/type`. public var _type: Components.Schemas.ResponseCodeInterpreterCallCodeDeltaEvent._TypePayload - /// The index of the output item that the code interpreter call is in progress. - /// + /// The index of the output item in the response for which the code is being streamed. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent/output_index`. public var outputIndex: Swift.Int - /// The partial code snippet added by the code interpreter. + /// The unique identifier of the code interpreter tool call item. /// + /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent/item_id`. + public var itemId: Swift.String + /// The partial code snippet being streamed by the code interpreter. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent/delta`. public var delta: Swift.String - /// The sequence number of this event. + /// The sequence number of this event, used to order streaming events. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent/sequence_number`. public var sequenceNumber: Swift.Int @@ -5448,54 +5936,58 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.code_interpreter_call_code.delta`. - /// - outputIndex: The index of the output item that the code interpreter call is in progress. - /// - delta: The partial code snippet added by the code interpreter. - /// - sequenceNumber: The sequence number of this event. + /// - outputIndex: The index of the output item in the response for which the code is being streamed. + /// - itemId: The unique identifier of the code interpreter tool call item. + /// - delta: The partial code snippet being streamed by the code interpreter. + /// - sequenceNumber: The sequence number of this event, used to order streaming events. public init( _type: Components.Schemas.ResponseCodeInterpreterCallCodeDeltaEvent._TypePayload, outputIndex: Swift.Int, + itemId: Swift.String, delta: Swift.String, sequenceNumber: Swift.Int ) { self._type = _type self.outputIndex = outputIndex + self.itemId = itemId self.delta = delta self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" case outputIndex = "output_index" + case itemId = "item_id" case delta case sequenceNumber = "sequence_number" } } - /// Emitted when code snippet output is finalized by the code interpreter. + /// Emitted when the code snippet is finalized by the code interpreter. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent`. public struct ResponseCodeInterpreterCallCodeDoneEvent: Codable, Hashable, Sendable { /// The type of the event. Always `response.code_interpreter_call_code.done`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { case response_codeInterpreterCallCode_done = "response.code_interpreter_call_code.done" } /// The type of the event. Always `response.code_interpreter_call_code.done`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent/type`. public var _type: Components.Schemas.ResponseCodeInterpreterCallCodeDoneEvent._TypePayload - /// The index of the output item that the code interpreter call is in progress. - /// + /// The index of the output item in the response for which the code is finalized. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent/output_index`. public var outputIndex: Swift.Int - /// The final code snippet output by the code interpreter. + /// The unique identifier of the code interpreter tool call item. /// + /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent/item_id`. + public var itemId: Swift.String + /// The final code snippet output by the code interpreter. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent/code`. public var code: Swift.String - /// The sequence number of this event. + /// The sequence number of this event, used to order streaming events. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent/sequence_number`. public var sequenceNumber: Swift.Int @@ -5503,23 +5995,27 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.code_interpreter_call_code.done`. - /// - outputIndex: The index of the output item that the code interpreter call is in progress. + /// - outputIndex: The index of the output item in the response for which the code is finalized. + /// - itemId: The unique identifier of the code interpreter tool call item. /// - code: The final code snippet output by the code interpreter. - /// - sequenceNumber: The sequence number of this event. + /// - sequenceNumber: The sequence number of this event, used to order streaming events. public init( _type: Components.Schemas.ResponseCodeInterpreterCallCodeDoneEvent._TypePayload, outputIndex: Swift.Int, + itemId: Swift.String, code: Swift.String, sequenceNumber: Swift.Int ) { self._type = _type self.outputIndex = outputIndex + self.itemId = itemId self.code = code self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" case outputIndex = "output_index" + case itemId = "item_id" case code case sequenceNumber = "sequence_number" } @@ -5530,24 +6026,23 @@ public enum Components { public struct ResponseCodeInterpreterCallCompletedEvent: Codable, Hashable, Sendable { /// The type of the event. Always `response.code_interpreter_call.completed`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCompletedEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { case response_codeInterpreterCall_completed = "response.code_interpreter_call.completed" } /// The type of the event. Always `response.code_interpreter_call.completed`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCompletedEvent/type`. public var _type: Components.Schemas.ResponseCodeInterpreterCallCompletedEvent._TypePayload - /// The index of the output item that the code interpreter call is in progress. - /// + /// The index of the output item in the response for which the code interpreter call is completed. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCompletedEvent/output_index`. public var outputIndex: Swift.Int - /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCompletedEvent/code_interpreter_call`. - public var codeInterpreterCall: Components.Schemas.CodeInterpreterToolCall - /// The sequence number of this event. + /// The unique identifier of the code interpreter tool call item. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCompletedEvent/item_id`. + public var itemId: Swift.String + /// The sequence number of this event, used to order streaming events. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallCompletedEvent/sequence_number`. public var sequenceNumber: Swift.Int @@ -5555,24 +6050,24 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.code_interpreter_call.completed`. - /// - outputIndex: The index of the output item that the code interpreter call is in progress. - /// - codeInterpreterCall: - /// - sequenceNumber: The sequence number of this event. + /// - outputIndex: The index of the output item in the response for which the code interpreter call is completed. + /// - itemId: The unique identifier of the code interpreter tool call item. + /// - sequenceNumber: The sequence number of this event, used to order streaming events. public init( _type: Components.Schemas.ResponseCodeInterpreterCallCompletedEvent._TypePayload, outputIndex: Swift.Int, - codeInterpreterCall: Components.Schemas.CodeInterpreterToolCall, + itemId: Swift.String, sequenceNumber: Swift.Int ) { self._type = _type self.outputIndex = outputIndex - self.codeInterpreterCall = codeInterpreterCall + self.itemId = itemId self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" case outputIndex = "output_index" - case codeInterpreterCall = "code_interpreter_call" + case itemId = "item_id" case sequenceNumber = "sequence_number" } } @@ -5582,24 +6077,23 @@ public enum Components { public struct ResponseCodeInterpreterCallInProgressEvent: Codable, Hashable, Sendable { /// The type of the event. Always `response.code_interpreter_call.in_progress`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInProgressEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { case response_codeInterpreterCall_inProgress = "response.code_interpreter_call.in_progress" } /// The type of the event. Always `response.code_interpreter_call.in_progress`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInProgressEvent/type`. public var _type: Components.Schemas.ResponseCodeInterpreterCallInProgressEvent._TypePayload - /// The index of the output item that the code interpreter call is in progress. - /// + /// The index of the output item in the response for which the code interpreter call is in progress. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInProgressEvent/output_index`. public var outputIndex: Swift.Int - /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInProgressEvent/code_interpreter_call`. - public var codeInterpreterCall: Components.Schemas.CodeInterpreterToolCall - /// The sequence number of this event. + /// The unique identifier of the code interpreter tool call item. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInProgressEvent/item_id`. + public var itemId: Swift.String + /// The sequence number of this event, used to order streaming events. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInProgressEvent/sequence_number`. public var sequenceNumber: Swift.Int @@ -5607,24 +6101,24 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.code_interpreter_call.in_progress`. - /// - outputIndex: The index of the output item that the code interpreter call is in progress. - /// - codeInterpreterCall: - /// - sequenceNumber: The sequence number of this event. + /// - outputIndex: The index of the output item in the response for which the code interpreter call is in progress. + /// - itemId: The unique identifier of the code interpreter tool call item. + /// - sequenceNumber: The sequence number of this event, used to order streaming events. public init( _type: Components.Schemas.ResponseCodeInterpreterCallInProgressEvent._TypePayload, outputIndex: Swift.Int, - codeInterpreterCall: Components.Schemas.CodeInterpreterToolCall, + itemId: Swift.String, sequenceNumber: Swift.Int ) { self._type = _type self.outputIndex = outputIndex - self.codeInterpreterCall = codeInterpreterCall + self.itemId = itemId self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" case outputIndex = "output_index" - case codeInterpreterCall = "code_interpreter_call" + case itemId = "item_id" case sequenceNumber = "sequence_number" } } @@ -5634,50 +6128,49 @@ public enum Components { public struct ResponseCodeInterpreterCallInterpretingEvent: Codable, Hashable, Sendable { /// The type of the event. Always `response.code_interpreter_call.interpreting`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { case response_codeInterpreterCall_interpreting = "response.code_interpreter_call.interpreting" } /// The type of the event. Always `response.code_interpreter_call.interpreting`. /// - /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent/type`. public var _type: Components.Schemas.ResponseCodeInterpreterCallInterpretingEvent._TypePayload - /// The sequence number of this event. - /// - /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent/sequence_number`. - public var sequenceNumber: Swift.Int - /// The index of the output item that the code interpreter call is in progress. - /// + /// The index of the output item in the response for which the code interpreter is interpreting code. /// /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent/output_index`. public var outputIndex: Swift.Int - /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent/code_interpreter_call`. - public var codeInterpreterCall: Components.Schemas.CodeInterpreterToolCall + /// The unique identifier of the code interpreter tool call item. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent/item_id`. + public var itemId: Swift.String + /// The sequence number of this event, used to order streaming events. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent/sequence_number`. + public var sequenceNumber: Swift.Int /// Creates a new `ResponseCodeInterpreterCallInterpretingEvent`. /// /// - Parameters: /// - _type: The type of the event. Always `response.code_interpreter_call.interpreting`. - /// - sequenceNumber: The sequence number of this event. - /// - outputIndex: The index of the output item that the code interpreter call is in progress. - /// - codeInterpreterCall: + /// - outputIndex: The index of the output item in the response for which the code interpreter is interpreting code. + /// - itemId: The unique identifier of the code interpreter tool call item. + /// - sequenceNumber: The sequence number of this event, used to order streaming events. public init( _type: Components.Schemas.ResponseCodeInterpreterCallInterpretingEvent._TypePayload, - sequenceNumber: Swift.Int, outputIndex: Swift.Int, - codeInterpreterCall: Components.Schemas.CodeInterpreterToolCall + itemId: Swift.String, + sequenceNumber: Swift.Int ) { self._type = _type - self.sequenceNumber = sequenceNumber self.outputIndex = outputIndex - self.codeInterpreterCall = codeInterpreterCall + self.itemId = itemId + self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" - case sequenceNumber = "sequence_number" case outputIndex = "output_index" - case codeInterpreterCall = "code_interpreter_call" + case itemId = "item_id" + case sequenceNumber = "sequence_number" } } /// Emitted when the model response is complete. @@ -5696,6 +6189,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseCompletedEvent/type`. public var _type: Components.Schemas.ResponseCompletedEvent._TypePayload + /// Properties of the completed response. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseCompletedEvent/response`. public var response: Components.Schemas.Response /// The sequence number for this event. @@ -5706,7 +6202,7 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.completed`. - /// - response: + /// - response: Properties of the completed response. /// - sequenceNumber: The sequence number for this event. public init( _type: Components.Schemas.ResponseCompletedEvent._TypePayload, @@ -5754,6 +6250,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseContentPartAddedEvent/content_index`. public var contentIndex: Swift.Int + /// The content part that was added. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseContentPartAddedEvent/part`. public var part: Components.Schemas.OutputContent /// The sequence number of this event. @@ -5767,7 +6266,7 @@ public enum Components { /// - itemId: The ID of the output item that the content part was added to. /// - outputIndex: The index of the output item that the content part was added to. /// - contentIndex: The index of the content part that was added. - /// - part: + /// - part: The content part that was added. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseContentPartAddedEvent._TypePayload, @@ -5828,6 +6327,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseContentPartDoneEvent/sequence_number`. public var sequenceNumber: Swift.Int + /// The content part that is done. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseContentPartDoneEvent/part`. public var part: Components.Schemas.OutputContent /// Creates a new `ResponseContentPartDoneEvent`. @@ -5838,7 +6340,7 @@ public enum Components { /// - outputIndex: The index of the output item that the content part was added to. /// - contentIndex: The index of the content part that is done. /// - sequenceNumber: The sequence number of this event. - /// - part: + /// - part: The content part that is done. public init( _type: Components.Schemas.ResponseContentPartDoneEvent._TypePayload, itemId: Swift.String, @@ -5880,6 +6382,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseCreatedEvent/type`. public var _type: Components.Schemas.ResponseCreatedEvent._TypePayload + /// The response that was created. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseCreatedEvent/response`. public var response: Components.Schemas.Response /// The sequence number for this event. @@ -5890,7 +6395,7 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.created`. - /// - response: + /// - response: The response that was created. /// - sequenceNumber: The sequence number for this event. public init( _type: Components.Schemas.ResponseCreatedEvent._TypePayload, @@ -5907,6 +6412,126 @@ public enum Components { case sequenceNumber = "sequence_number" } } + /// Event representing a delta (partial update) to the input of a custom tool call. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDeltaEvent`. + public struct ResponseCustomToolCallInputDeltaEvent: Codable, Hashable, Sendable { + /// The event type identifier. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDeltaEvent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case response_customToolCallInput_delta = "response.custom_tool_call_input.delta" + } + /// The event type identifier. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDeltaEvent/type`. + public var _type: Components.Schemas.ResponseCustomToolCallInputDeltaEvent._TypePayload + /// The sequence number of this event. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDeltaEvent/sequence_number`. + public var sequenceNumber: Swift.Int + /// The index of the output this delta applies to. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDeltaEvent/output_index`. + public var outputIndex: Swift.Int + /// Unique identifier for the API item associated with this event. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDeltaEvent/item_id`. + public var itemId: Swift.String + /// The incremental input data (delta) for the custom tool call. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDeltaEvent/delta`. + public var delta: Swift.String + /// Creates a new `ResponseCustomToolCallInputDeltaEvent`. + /// + /// - Parameters: + /// - _type: The event type identifier. + /// - sequenceNumber: The sequence number of this event. + /// - outputIndex: The index of the output this delta applies to. + /// - itemId: Unique identifier for the API item associated with this event. + /// - delta: The incremental input data (delta) for the custom tool call. + public init( + _type: Components.Schemas.ResponseCustomToolCallInputDeltaEvent._TypePayload, + sequenceNumber: Swift.Int, + outputIndex: Swift.Int, + itemId: Swift.String, + delta: Swift.String + ) { + self._type = _type + self.sequenceNumber = sequenceNumber + self.outputIndex = outputIndex + self.itemId = itemId + self.delta = delta + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case sequenceNumber = "sequence_number" + case outputIndex = "output_index" + case itemId = "item_id" + case delta + } + } + /// Event indicating that input for a custom tool call is complete. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDoneEvent`. + public struct ResponseCustomToolCallInputDoneEvent: Codable, Hashable, Sendable { + /// The event type identifier. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDoneEvent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case response_customToolCallInput_done = "response.custom_tool_call_input.done" + } + /// The event type identifier. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDoneEvent/type`. + public var _type: Components.Schemas.ResponseCustomToolCallInputDoneEvent._TypePayload + /// The sequence number of this event. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDoneEvent/sequence_number`. + public var sequenceNumber: Swift.Int + /// The index of the output this event applies to. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDoneEvent/output_index`. + public var outputIndex: Swift.Int + /// Unique identifier for the API item associated with this event. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDoneEvent/item_id`. + public var itemId: Swift.String + /// The complete input data for the custom tool call. + /// + /// - Remark: Generated from `#/components/schemas/ResponseCustomToolCallInputDoneEvent/input`. + public var input: Swift.String + /// Creates a new `ResponseCustomToolCallInputDoneEvent`. + /// + /// - Parameters: + /// - _type: The event type identifier. + /// - sequenceNumber: The sequence number of this event. + /// - outputIndex: The index of the output this event applies to. + /// - itemId: Unique identifier for the API item associated with this event. + /// - input: The complete input data for the custom tool call. + public init( + _type: Components.Schemas.ResponseCustomToolCallInputDoneEvent._TypePayload, + sequenceNumber: Swift.Int, + outputIndex: Swift.Int, + itemId: Swift.String, + input: Swift.String + ) { + self._type = _type + self.sequenceNumber = sequenceNumber + self.outputIndex = outputIndex + self.itemId = itemId + self.input = input + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case sequenceNumber = "sequence_number" + case outputIndex = "output_index" + case itemId = "item_id" + case input + } + } /// An error object returned when the model fails to generate a Response. /// /// @@ -5976,9 +6601,7 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/type`. public var _type: Components.Schemas.ResponseErrorEvent._TypePayload - /// The error code. - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/code`. public var code: Swift.String? /// The error message. @@ -5986,9 +6609,7 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/message`. public var message: Swift.String - /// The error parameter. - /// - /// + public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/param`. public var param: Swift.String? /// The sequence number of this event. @@ -5999,9 +6620,9 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `error`. - /// - code: The error code. + /// - code: /// - message: The error message. - /// - param: The error parameter. + /// - param: /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseErrorEvent._TypePayload, @@ -6045,6 +6666,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseFailedEvent/sequence_number`. public var sequenceNumber: Swift.Int + /// The response that failed. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseFailedEvent/response`. public var response: Components.Schemas.Response /// Creates a new `ResponseFailedEvent`. @@ -6052,7 +6676,7 @@ public enum Components { /// - Parameters: /// - _type: The type of the event. Always `response.failed`. /// - sequenceNumber: The sequence number of this event. - /// - response: + /// - response: The response that failed. public init( _type: Components.Schemas.ResponseFailedEvent._TypePayload, sequenceNumber: Swift.Int, @@ -6277,10 +6901,10 @@ public enum Components { public init(additionalProperties: OpenAPIRuntime.OpenAPIObjectContainer = .init()) { self.additionalProperties = additionalProperties } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try encoder.encodeAdditionalProperties(additionalProperties) } } @@ -6388,6 +7012,10 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseFunctionCallArgumentsDoneEvent/item_id`. public var itemId: Swift.String + /// The name of the function that was called. + /// + /// - Remark: Generated from `#/components/schemas/ResponseFunctionCallArgumentsDoneEvent/name`. + public var name: Swift.String /// The index of the output item. /// /// - Remark: Generated from `#/components/schemas/ResponseFunctionCallArgumentsDoneEvent/output_index`. @@ -6405,18 +7033,21 @@ public enum Components { /// - Parameters: /// - _type: /// - itemId: The ID of the item. + /// - name: The name of the function that was called. /// - outputIndex: The index of the output item. /// - sequenceNumber: The sequence number of this event. /// - arguments: The function-call arguments. public init( _type: Components.Schemas.ResponseFunctionCallArgumentsDoneEvent._TypePayload, itemId: Swift.String, + name: Swift.String, outputIndex: Swift.Int, sequenceNumber: Swift.Int, arguments: Swift.String ) { self._type = _type self.itemId = itemId + self.name = name self.outputIndex = outputIndex self.sequenceNumber = sequenceNumber self.arguments = arguments @@ -6424,6 +7055,7 @@ public enum Components { public enum CodingKeys: String, CodingKey { case _type = "type" case itemId = "item_id" + case name case outputIndex = "output_index" case sequenceNumber = "sequence_number" case arguments @@ -6669,6 +7301,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseInProgressEvent/type`. public var _type: Components.Schemas.ResponseInProgressEvent._TypePayload + /// The response that is in progress. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseInProgressEvent/response`. public var response: Components.Schemas.Response /// The sequence number of this event. @@ -6679,7 +7314,7 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.in_progress`. - /// - response: + /// - response: The response that is in progress. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseInProgressEvent._TypePayload, @@ -6713,6 +7348,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseIncompleteEvent/type`. public var _type: Components.Schemas.ResponseIncompleteEvent._TypePayload + /// The response that was incomplete. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseIncompleteEvent/response`. public var response: Components.Schemas.Response /// The sequence number of this event. @@ -6723,7 +7361,7 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always `response.incomplete`. - /// - response: + /// - response: The response that was incomplete. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseIncompleteEvent._TypePayload, @@ -6799,18 +7437,92 @@ public enum Components { case lastId = "last_id" } } + /// A logprob is the logarithmic probability that the model assigns to producing + /// a particular token at a given position in the sequence. Less-negative (higher) + /// logprob values indicate greater model confidence in that token choice. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseLogProb`. + public struct ResponseLogProb: Codable, Hashable, Sendable { + /// A possible text token. + /// + /// - Remark: Generated from `#/components/schemas/ResponseLogProb/token`. + public var token: Swift.String + /// The log probability of this token. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseLogProb/logprob`. + public var logprob: Swift.Double + /// - Remark: Generated from `#/components/schemas/ResponseLogProb/TopLogprobsPayload`. + public struct TopLogprobsPayloadPayload: Codable, Hashable, Sendable { + /// A possible text token. + /// + /// - Remark: Generated from `#/components/schemas/ResponseLogProb/TopLogprobsPayload/token`. + public var token: Swift.String? + /// The log probability of this token. + /// + /// - Remark: Generated from `#/components/schemas/ResponseLogProb/TopLogprobsPayload/logprob`. + public var logprob: Swift.Double? + /// Creates a new `TopLogprobsPayloadPayload`. + /// + /// - Parameters: + /// - token: A possible text token. + /// - logprob: The log probability of this token. + public init( + token: Swift.String? = nil, + logprob: Swift.Double? = nil + ) { + self.token = token + self.logprob = logprob + } + public enum CodingKeys: String, CodingKey { + case token + case logprob + } + } + /// The log probability of the top 20 most likely tokens. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseLogProb/top_logprobs`. + public typealias TopLogprobsPayload = [Components.Schemas.ResponseLogProb.TopLogprobsPayloadPayload] + /// The log probability of the top 20 most likely tokens. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseLogProb/top_logprobs`. + public var topLogprobs: Components.Schemas.ResponseLogProb.TopLogprobsPayload? + /// Creates a new `ResponseLogProb`. + /// + /// - Parameters: + /// - token: A possible text token. + /// - logprob: The log probability of this token. + /// - topLogprobs: The log probability of the top 20 most likely tokens. + public init( + token: Swift.String, + logprob: Swift.Double, + topLogprobs: Components.Schemas.ResponseLogProb.TopLogprobsPayload? = nil + ) { + self.token = token + self.logprob = logprob + self.topLogprobs = topLogprobs + } + public enum CodingKeys: String, CodingKey { + case token + case logprob + case topLogprobs = "top_logprobs" + } + } /// Emitted when there is a delta (partial update) to the arguments of an MCP tool call. /// /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDeltaEvent`. public struct ResponseMCPCallArgumentsDeltaEvent: Codable, Hashable, Sendable { - /// The type of the event. Always 'response.mcp_call.arguments_delta'. + /// The type of the event. Always 'response.mcp_call_arguments.delta'. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDeltaEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_mcpCall_argumentsDelta = "response.mcp_call.arguments_delta" + case response_mcpCallArguments_delta = "response.mcp_call_arguments.delta" } - /// The type of the event. Always 'response.mcp_call.arguments_delta'. + /// The type of the event. Always 'response.mcp_call_arguments.delta'. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDeltaEvent/type`. public var _type: Components.Schemas.ResponseMCPCallArgumentsDeltaEvent._TypePayload @@ -6822,10 +7534,11 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDeltaEvent/item_id`. public var itemId: Swift.String - /// The partial update to the arguments for the MCP tool call. + /// A JSON string containing the partial update to the arguments for the MCP tool call. + /// /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDeltaEvent/delta`. - public var delta: OpenAPIRuntime.OpenAPIObjectContainer + public var delta: Swift.String /// The sequence number of this event. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDeltaEvent/sequence_number`. @@ -6833,16 +7546,16 @@ public enum Components { /// Creates a new `ResponseMCPCallArgumentsDeltaEvent`. /// /// - Parameters: - /// - _type: The type of the event. Always 'response.mcp_call.arguments_delta'. + /// - _type: The type of the event. Always 'response.mcp_call_arguments.delta'. /// - outputIndex: The index of the output item in the response's output array. /// - itemId: The unique identifier of the MCP tool call item being processed. - /// - delta: The partial update to the arguments for the MCP tool call. + /// - delta: A JSON string containing the partial update to the arguments for the MCP tool call. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseMCPCallArgumentsDeltaEvent._TypePayload, outputIndex: Swift.Int, itemId: Swift.String, - delta: OpenAPIRuntime.OpenAPIObjectContainer, + delta: Swift.String, sequenceNumber: Swift.Int ) { self._type = _type @@ -6864,13 +7577,13 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDoneEvent`. public struct ResponseMCPCallArgumentsDoneEvent: Codable, Hashable, Sendable { - /// The type of the event. Always 'response.mcp_call.arguments_done'. + /// The type of the event. Always 'response.mcp_call_arguments.done'. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDoneEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_mcpCall_argumentsDone = "response.mcp_call.arguments_done" + case response_mcpCallArguments_done = "response.mcp_call_arguments.done" } - /// The type of the event. Always 'response.mcp_call.arguments_done'. + /// The type of the event. Always 'response.mcp_call_arguments.done'. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDoneEvent/type`. public var _type: Components.Schemas.ResponseMCPCallArgumentsDoneEvent._TypePayload @@ -6882,10 +7595,11 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDoneEvent/item_id`. public var itemId: Swift.String - /// The finalized arguments for the MCP tool call. + /// A JSON string containing the finalized arguments for the MCP tool call. + /// /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDoneEvent/arguments`. - public var arguments: OpenAPIRuntime.OpenAPIObjectContainer + public var arguments: Swift.String /// The sequence number of this event. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallArgumentsDoneEvent/sequence_number`. @@ -6893,16 +7607,16 @@ public enum Components { /// Creates a new `ResponseMCPCallArgumentsDoneEvent`. /// /// - Parameters: - /// - _type: The type of the event. Always 'response.mcp_call.arguments_done'. + /// - _type: The type of the event. Always 'response.mcp_call_arguments.done'. /// - outputIndex: The index of the output item in the response's output array. /// - itemId: The unique identifier of the MCP tool call item being processed. - /// - arguments: The finalized arguments for the MCP tool call. + /// - arguments: A JSON string containing the finalized arguments for the MCP tool call. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseMCPCallArgumentsDoneEvent._TypePayload, outputIndex: Swift.Int, itemId: Swift.String, - arguments: OpenAPIRuntime.OpenAPIObjectContainer, + arguments: Swift.String, sequenceNumber: Swift.Int ) { self._type = _type @@ -6934,6 +7648,14 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallCompletedEvent/type`. public var _type: Components.Schemas.ResponseMCPCallCompletedEvent._TypePayload + /// The ID of the MCP tool call item that completed. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPCallCompletedEvent/item_id`. + public var itemId: Swift.String + /// The index of the output item that completed. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPCallCompletedEvent/output_index`. + public var outputIndex: Swift.Int /// The sequence number of this event. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallCompletedEvent/sequence_number`. @@ -6942,16 +7664,24 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always 'response.mcp_call.completed'. + /// - itemId: The ID of the MCP tool call item that completed. + /// - outputIndex: The index of the output item that completed. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseMCPCallCompletedEvent._TypePayload, + itemId: Swift.String, + outputIndex: Swift.Int, sequenceNumber: Swift.Int ) { self._type = _type + self.itemId = itemId + self.outputIndex = outputIndex self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" + case itemId = "item_id" + case outputIndex = "output_index" case sequenceNumber = "sequence_number" } } @@ -6970,6 +7700,14 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallFailedEvent/type`. public var _type: Components.Schemas.ResponseMCPCallFailedEvent._TypePayload + /// The ID of the MCP tool call item that failed. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPCallFailedEvent/item_id`. + public var itemId: Swift.String + /// The index of the output item that failed. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPCallFailedEvent/output_index`. + public var outputIndex: Swift.Int /// The sequence number of this event. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPCallFailedEvent/sequence_number`. @@ -6978,16 +7716,24 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always 'response.mcp_call.failed'. + /// - itemId: The ID of the MCP tool call item that failed. + /// - outputIndex: The index of the output item that failed. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseMCPCallFailedEvent._TypePayload, + itemId: Swift.String, + outputIndex: Swift.Int, sequenceNumber: Swift.Int ) { self._type = _type + self.itemId = itemId + self.outputIndex = outputIndex self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" + case itemId = "item_id" + case outputIndex = "output_index" case sequenceNumber = "sequence_number" } } @@ -7058,6 +7804,14 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsCompletedEvent/type`. public var _type: Components.Schemas.ResponseMCPListToolsCompletedEvent._TypePayload + /// The ID of the MCP tool call item that produced this output. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsCompletedEvent/item_id`. + public var itemId: Swift.String + /// The index of the output item that was processed. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsCompletedEvent/output_index`. + public var outputIndex: Swift.Int /// The sequence number of this event. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsCompletedEvent/sequence_number`. @@ -7066,16 +7820,24 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always 'response.mcp_list_tools.completed'. + /// - itemId: The ID of the MCP tool call item that produced this output. + /// - outputIndex: The index of the output item that was processed. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseMCPListToolsCompletedEvent._TypePayload, + itemId: Swift.String, + outputIndex: Swift.Int, sequenceNumber: Swift.Int ) { self._type = _type + self.itemId = itemId + self.outputIndex = outputIndex self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" + case itemId = "item_id" + case outputIndex = "output_index" case sequenceNumber = "sequence_number" } } @@ -7094,6 +7856,14 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsFailedEvent/type`. public var _type: Components.Schemas.ResponseMCPListToolsFailedEvent._TypePayload + /// The ID of the MCP tool call item that failed. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsFailedEvent/item_id`. + public var itemId: Swift.String + /// The index of the output item that failed. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsFailedEvent/output_index`. + public var outputIndex: Swift.Int /// The sequence number of this event. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsFailedEvent/sequence_number`. @@ -7102,16 +7872,24 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always 'response.mcp_list_tools.failed'. + /// - itemId: The ID of the MCP tool call item that failed. + /// - outputIndex: The index of the output item that failed. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseMCPListToolsFailedEvent._TypePayload, + itemId: Swift.String, + outputIndex: Swift.Int, sequenceNumber: Swift.Int ) { self._type = _type + self.itemId = itemId + self.outputIndex = outputIndex self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" + case itemId = "item_id" + case outputIndex = "output_index" case sequenceNumber = "sequence_number" } } @@ -7130,6 +7908,14 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsInProgressEvent/type`. public var _type: Components.Schemas.ResponseMCPListToolsInProgressEvent._TypePayload + /// The ID of the MCP tool call item that is being processed. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsInProgressEvent/item_id`. + public var itemId: Swift.String + /// The index of the output item that is being processed. + /// + /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsInProgressEvent/output_index`. + public var outputIndex: Swift.Int /// The sequence number of this event. /// /// - Remark: Generated from `#/components/schemas/ResponseMCPListToolsInProgressEvent/sequence_number`. @@ -7138,16 +7924,24 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always 'response.mcp_list_tools.in_progress'. + /// - itemId: The ID of the MCP tool call item that is being processed. + /// - outputIndex: The index of the output item that is being processed. /// - sequenceNumber: The sequence number of this event. public init( _type: Components.Schemas.ResponseMCPListToolsInProgressEvent._TypePayload, + itemId: Swift.String, + outputIndex: Swift.Int, sequenceNumber: Swift.Int ) { self._type = _type + self.itemId = itemId + self.outputIndex = outputIndex self.sequenceNumber = sequenceNumber } public enum CodingKeys: String, CodingKey { case _type = "type" + case itemId = "item_id" + case outputIndex = "output_index" case sequenceNumber = "sequence_number" } } @@ -7177,6 +7971,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseOutputItemAddedEvent/sequence_number`. public var sequenceNumber: Swift.Int + /// The output item that was added. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseOutputItemAddedEvent/item`. public var item: Components.Schemas.OutputItem /// Creates a new `ResponseOutputItemAddedEvent`. @@ -7185,7 +7982,7 @@ public enum Components { /// - _type: The type of the event. Always `response.output_item.added`. /// - outputIndex: The index of the output item that was added. /// - sequenceNumber: The sequence number of this event. - /// - item: + /// - item: The output item that was added. public init( _type: Components.Schemas.ResponseOutputItemAddedEvent._TypePayload, outputIndex: Swift.Int, @@ -7230,6 +8027,9 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseOutputItemDoneEvent/sequence_number`. public var sequenceNumber: Swift.Int + /// The output item that was marked done. + /// + /// /// - Remark: Generated from `#/components/schemas/ResponseOutputItemDoneEvent/item`. public var item: Components.Schemas.OutputItem /// Creates a new `ResponseOutputItemDoneEvent`. @@ -7238,7 +8038,7 @@ public enum Components { /// - _type: The type of the event. Always `response.output_item.done`. /// - outputIndex: The index of the output item that was marked done. /// - sequenceNumber: The sequence number of this event. - /// - item: + /// - item: The output item that was marked done. public init( _type: Components.Schemas.ResponseOutputItemDoneEvent._TypePayload, outputIndex: Swift.Int, @@ -7262,13 +8062,13 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseOutputTextAnnotationAddedEvent`. public struct ResponseOutputTextAnnotationAddedEvent: Codable, Hashable, Sendable { - /// The type of the event. Always 'response.output_text_annotation.added'. + /// The type of the event. Always 'response.output_text.annotation.added'. /// /// - Remark: Generated from `#/components/schemas/ResponseOutputTextAnnotationAddedEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_outputTextAnnotation_added = "response.output_text_annotation.added" + case response_outputText_annotation_added = "response.output_text.annotation.added" } - /// The type of the event. Always 'response.output_text_annotation.added'. + /// The type of the event. Always 'response.output_text.annotation.added'. /// /// - Remark: Generated from `#/components/schemas/ResponseOutputTextAnnotationAddedEvent/type`. public var _type: Components.Schemas.ResponseOutputTextAnnotationAddedEvent._TypePayload @@ -7299,7 +8099,7 @@ public enum Components { /// Creates a new `ResponseOutputTextAnnotationAddedEvent`. /// /// - Parameters: - /// - _type: The type of the event. Always 'response.output_text_annotation.added'. + /// - _type: The type of the event. Always 'response.output_text.annotation.added'. /// - itemId: The unique identifier of the item to which the annotation is being added. /// - outputIndex: The index of the output item in the response's output array. /// - contentIndex: The index of the content part within the output item. @@ -7350,8 +8150,8 @@ public enum Components { case InputImageContent(Components.Schemas.InputImageContent) /// - Remark: Generated from `#/components/schemas/ResponsePromptVariables/additionalProperties/case4`. case InputFileContent(Components.Schemas.InputFileContent) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self = .case1(try decoder.decodeFromSingleValueContainer()) return @@ -7382,7 +8182,7 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .case1(value): try encoder.encodeToSingleValueContainer(value) @@ -7404,147 +8204,49 @@ public enum Components { public init(additionalProperties: [String: Components.Schemas.ResponsePromptVariables.AdditionalPropertiesPayload] = .init()) { self.additionalProperties = additionalProperties } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try encoder.encodeAdditionalProperties(additionalProperties) } } /// - 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). - /// - /// + public typealias String = Swift.String /// - 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 + /// offers a wide range of models with different capabilities, performance + /// characteristics, and price points. Refer to the [model guide](/docs/models) + /// to browse and compare available models. + /// + /// /// - 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). - /// - /// + public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/ResponseProperties/background`. public var background: Swift.Bool? - /// 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/ResponseProperties/max_output_tokens`. - public var maxOutputTokens: Swift.Int? - /// Configuration options for a text response from the model. Can be plain - /// text or structured JSON data. Learn more: - /// - [Text inputs and outputs](/docs/guides/text) - /// - [Structured Outputs](/docs/guides/structured-outputs) - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseProperties/text`. - public struct TextPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/ResponseProperties/text/format`. - public var format: Components.Schemas.TextResponseFormatConfiguration? - /// Creates a new `TextPayload`. - /// - /// - Parameters: - /// - format: - public init(format: Components.Schemas.TextResponseFormatConfiguration? = nil) { - self.format = format - } - public enum CodingKeys: String, CodingKey { - case format - } - } - /// Configuration options for a text response from the model. Can be plain - /// text or structured JSON data. Learn more: - /// - [Text inputs and outputs](/docs/guides/text) - /// - [Structured Outputs](/docs/guides/structured-outputs) - /// - /// + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/ResponseProperties/max_tool_calls`. + public var maxToolCalls: Swift.Int? /// - Remark: Generated from `#/components/schemas/ResponseProperties/text`. - public var text: Components.Schemas.ResponseProperties.TextPayload? - /// An array of tools the model may call while generating a response. You - /// can specify which tool to use by setting the `tool_choice` parameter. - /// - /// The two categories of tools you can provide the model are: - /// - /// - **Built-in tools**: Tools that are provided by OpenAI that extend the - /// model's capabilities, like [web search](/docs/guides/tools-web-search) - /// or [file search](/docs/guides/tools-file-search). Learn more about - /// [built-in tools](/docs/guides/tools). - /// - **Function calls (custom tools)**: Functions that are defined by you, - /// enabling the model to call your own code. Learn more about - /// [function calling](/docs/guides/function-calling). - /// - /// + public var text: Components.Schemas.ResponseTextParam? /// - Remark: Generated from `#/components/schemas/ResponseProperties/tools`. - public var tools: [Components.Schemas.Tool]? - /// How the model should select which tool (or tools) to use when generating - /// a response. See the `tools` parameter to see how to specify which tools - /// the model can call. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseProperties/tool_choice`. - @frozen public enum ToolChoicePayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/ResponseProperties/tool_choice/case1`. - case ToolChoiceOptions(Components.Schemas.ToolChoiceOptions) - /// - Remark: Generated from `#/components/schemas/ResponseProperties/tool_choice/case2`. - case ToolChoiceTypes(Components.Schemas.ToolChoiceTypes) - /// - Remark: Generated from `#/components/schemas/ResponseProperties/tool_choice/case3`. - case ToolChoiceFunction(Components.Schemas.ToolChoiceFunction) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self = .ToolChoiceOptions(try decoder.decodeFromSingleValueContainer()) - return - } catch { - errors.append(error) - } - do { - self = .ToolChoiceTypes(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { - self = .ToolChoiceFunction(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - throw Swift.DecodingError.failedToDecodeOneOfSchema( - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - switch self { - case let .ToolChoiceOptions(value): - try encoder.encodeToSingleValueContainer(value) - case let .ToolChoiceTypes(value): - try value.encode(to: encoder) - case let .ToolChoiceFunction(value): - try value.encode(to: encoder) - } - } - } - /// How the model should select which tool (or tools) to use when generating - /// a response. See the `tools` parameter to see how to specify which tools - /// the model can call. - /// - /// + public var tools: Components.Schemas.ToolsArray? /// - Remark: Generated from `#/components/schemas/ResponseProperties/tool_choice`. - public var toolChoice: Components.Schemas.ResponseProperties.ToolChoicePayload? + public var toolChoice: Components.Schemas.ToolChoiceParam? /// - Remark: Generated from `#/components/schemas/ResponseProperties/prompt`. public var prompt: Components.Schemas.Prompt? /// The truncation strategy to use for the model response. - /// - `auto`: If the context of this response and previous ones exceeds + /// - `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 input items in the - /// middle of the conversation. - /// - `disabled` (default): If a model response will exceed the context window + /// 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. /// /// @@ -7553,39 +8255,30 @@ public enum Components { case auto = "auto" case disabled = "disabled" } - /// The truncation strategy to use for the model response. - /// - `auto`: If the context of this response and previous ones exceeds - /// the model's context window size, the model will truncate the - /// response to fit the context window by dropping input items in the - /// middle of the conversation. - /// - `disabled` (default): If a model response 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: The unique ID of the previous response to the model. Use this to - /// - model: + /// - previousResponseId: + /// - model: Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI /// - reasoning: - /// - background: Whether to run the model response in the background. - /// - 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). - /// - text: Configuration options for a text response from the model. Can be plain - /// - tools: An array of tools the model may call while generating a response. You - /// - toolChoice: How the model should select which tool (or tools) to use when generating + /// - background: + /// - maxToolCalls: + /// - text: + /// - tools: + /// - toolChoice: /// - prompt: - /// - truncation: The truncation strategy to use for the model response. + /// - truncation: public init( previousResponseId: Swift.String? = nil, model: Components.Schemas.ModelIdsResponses? = nil, reasoning: Components.Schemas.Reasoning? = nil, background: Swift.Bool? = nil, - maxOutputTokens: Swift.Int? = nil, - text: Components.Schemas.ResponseProperties.TextPayload? = nil, - tools: [Components.Schemas.Tool]? = nil, - toolChoice: Components.Schemas.ResponseProperties.ToolChoicePayload? = nil, + maxToolCalls: Swift.Int? = nil, + text: Components.Schemas.ResponseTextParam? = nil, + tools: Components.Schemas.ToolsArray? = nil, + toolChoice: Components.Schemas.ToolChoiceParam? = nil, prompt: Components.Schemas.Prompt? = nil, truncation: Components.Schemas.ResponseProperties.TruncationPayload? = nil ) { @@ -7593,7 +8286,7 @@ public enum Components { self.model = model self.reasoning = reasoning self.background = background - self.maxOutputTokens = maxOutputTokens + self.maxToolCalls = maxToolCalls self.text = text self.tools = tools self.toolChoice = toolChoice @@ -7605,7 +8298,7 @@ public enum Components { case model case reasoning case background - case maxOutputTokens = "max_output_tokens" + case maxToolCalls = "max_tool_calls" case text case tools case toolChoice = "tool_choice" @@ -7628,6 +8321,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseQueuedEvent/type`. public var _type: Components.Schemas.ResponseQueuedEvent._TypePayload + /// The full response object that is queued. + /// /// - Remark: Generated from `#/components/schemas/ResponseQueuedEvent/response`. public var response: Components.Schemas.Response /// The sequence number for this event. @@ -7638,7 +8333,7 @@ public enum Components { /// /// - Parameters: /// - _type: The type of the event. Always 'response.queued'. - /// - response: + /// - response: The full response object that is queued. /// - sequenceNumber: The sequence number for this event. public init( _type: Components.Schemas.ResponseQueuedEvent._TypePayload, @@ -7655,425 +8350,153 @@ public enum Components { case sequenceNumber = "sequence_number" } } - /// Emitted when there is a delta (partial update) to the reasoning content. - /// + /// Emitted when a new reasoning summary part is added. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDeltaEvent`. - public struct ResponseReasoningDeltaEvent: Codable, Hashable, Sendable { - /// The type of the event. Always 'response.reasoning.delta'. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent`. + public struct ResponseReasoningSummaryPartAddedEvent: Codable, Hashable, Sendable { + /// The type of the event. Always `response.reasoning_summary_part.added`. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDeltaEvent/type`. + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_reasoning_delta = "response.reasoning.delta" + case response_reasoningSummaryPart_added = "response.reasoning_summary_part.added" } - /// The type of the event. Always 'response.reasoning.delta'. + /// The type of the event. Always `response.reasoning_summary_part.added`. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/type`. + public var _type: Components.Schemas.ResponseReasoningSummaryPartAddedEvent._TypePayload + /// The ID of the item this summary part is associated with. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDeltaEvent/type`. - public var _type: Components.Schemas.ResponseReasoningDeltaEvent._TypePayload - /// The unique identifier of the item for which reasoning is being updated. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDeltaEvent/item_id`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/item_id`. public var itemId: Swift.String - /// The index of the output item in the response's output array. + /// The index of the output item this summary part is associated with. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDeltaEvent/output_index`. + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/output_index`. public var outputIndex: Swift.Int - /// The index of the reasoning content part within the output item. + /// The index of the summary part within the reasoning summary. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDeltaEvent/content_index`. - public var contentIndex: Swift.Int - /// The partial update to the reasoning content. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDeltaEvent/delta`. - public var delta: OpenAPIRuntime.OpenAPIObjectContainer + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/summary_index`. + public var summaryIndex: Swift.Int /// The sequence number of this event. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDeltaEvent/sequence_number`. + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/sequence_number`. public var sequenceNumber: Swift.Int - /// Creates a new `ResponseReasoningDeltaEvent`. + /// The summary part that was added. /// - /// - Parameters: - /// - _type: The type of the event. Always 'response.reasoning.delta'. - /// - itemId: The unique identifier of the item for which reasoning is being updated. - /// - outputIndex: The index of the output item in the response's output array. - /// - contentIndex: The index of the reasoning content part within the output item. - /// - delta: The partial update to the reasoning content. - /// - sequenceNumber: The sequence number of this event. - public init( - _type: Components.Schemas.ResponseReasoningDeltaEvent._TypePayload, - itemId: Swift.String, - outputIndex: Swift.Int, - contentIndex: Swift.Int, - delta: OpenAPIRuntime.OpenAPIObjectContainer, - sequenceNumber: Swift.Int - ) { - self._type = _type - self.itemId = itemId - self.outputIndex = outputIndex - self.contentIndex = contentIndex - self.delta = delta - self.sequenceNumber = sequenceNumber - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case itemId = "item_id" - case outputIndex = "output_index" - case contentIndex = "content_index" - case delta - case sequenceNumber = "sequence_number" - } - } - /// Emitted when the reasoning content is finalized for an item. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDoneEvent`. - public struct ResponseReasoningDoneEvent: Codable, Hashable, Sendable { - /// The type of the event. Always 'response.reasoning.done'. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDoneEvent/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_reasoning_done = "response.reasoning.done" + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part`. + public struct PartPayload: Codable, Hashable, Sendable { + /// The type of the summary part. Always `summary_text`. + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case summaryText = "summary_text" + } + /// The type of the summary part. Always `summary_text`. + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part/type`. + public var _type: Components.Schemas.ResponseReasoningSummaryPartAddedEvent.PartPayload._TypePayload + /// The text of the summary part. + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part/text`. + public var text: Swift.String + /// Creates a new `PartPayload`. + /// + /// - Parameters: + /// - _type: The type of the summary part. Always `summary_text`. + /// - text: The text of the summary part. + public init( + _type: Components.Schemas.ResponseReasoningSummaryPartAddedEvent.PartPayload._TypePayload, + text: Swift.String + ) { + self._type = _type + self.text = text + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case text + } } - /// The type of the event. Always 'response.reasoning.done'. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDoneEvent/type`. - public var _type: Components.Schemas.ResponseReasoningDoneEvent._TypePayload - /// The unique identifier of the item for which reasoning is finalized. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDoneEvent/item_id`. - public var itemId: Swift.String - /// The index of the output item in the response's output array. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDoneEvent/output_index`. - public var outputIndex: Swift.Int - /// The index of the reasoning content part within the output item. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDoneEvent/content_index`. - public var contentIndex: Swift.Int - /// The finalized reasoning text. + /// The summary part that was added. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDoneEvent/text`. - public var text: Swift.String - /// The sequence number of this event. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningDoneEvent/sequence_number`. - public var sequenceNumber: Swift.Int - /// Creates a new `ResponseReasoningDoneEvent`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part`. + public var part: Components.Schemas.ResponseReasoningSummaryPartAddedEvent.PartPayload + /// Creates a new `ResponseReasoningSummaryPartAddedEvent`. /// /// - Parameters: - /// - _type: The type of the event. Always 'response.reasoning.done'. - /// - itemId: The unique identifier of the item for which reasoning is finalized. - /// - outputIndex: The index of the output item in the response's output array. - /// - contentIndex: The index of the reasoning content part within the output item. - /// - text: The finalized reasoning text. + /// - _type: The type of the event. Always `response.reasoning_summary_part.added`. + /// - itemId: The ID of the item this summary part is associated with. + /// - outputIndex: The index of the output item this summary part is associated with. + /// - summaryIndex: The index of the summary part within the reasoning summary. /// - sequenceNumber: The sequence number of this event. + /// - part: The summary part that was added. public init( - _type: Components.Schemas.ResponseReasoningDoneEvent._TypePayload, + _type: Components.Schemas.ResponseReasoningSummaryPartAddedEvent._TypePayload, itemId: Swift.String, outputIndex: Swift.Int, - contentIndex: Swift.Int, - text: Swift.String, - sequenceNumber: Swift.Int + summaryIndex: Swift.Int, + sequenceNumber: Swift.Int, + part: Components.Schemas.ResponseReasoningSummaryPartAddedEvent.PartPayload ) { self._type = _type self.itemId = itemId self.outputIndex = outputIndex - self.contentIndex = contentIndex - self.text = text + self.summaryIndex = summaryIndex self.sequenceNumber = sequenceNumber + self.part = part } public enum CodingKeys: String, CodingKey { case _type = "type" case itemId = "item_id" case outputIndex = "output_index" - case contentIndex = "content_index" - case text + case summaryIndex = "summary_index" case sequenceNumber = "sequence_number" + case part } } - /// Emitted when there is a delta (partial update) to the reasoning summary content. - /// + /// Emitted when a reasoning summary part is completed. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDeltaEvent`. - public struct ResponseReasoningSummaryDeltaEvent: Codable, Hashable, Sendable { - /// The type of the event. Always 'response.reasoning_summary.delta'. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent`. + public struct ResponseReasoningSummaryPartDoneEvent: Codable, Hashable, Sendable { + /// The type of the event. Always `response.reasoning_summary_part.done`. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDeltaEvent/type`. + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_reasoningSummary_delta = "response.reasoning_summary.delta" + case response_reasoningSummaryPart_done = "response.reasoning_summary_part.done" } - /// The type of the event. Always 'response.reasoning_summary.delta'. + /// The type of the event. Always `response.reasoning_summary_part.done`. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDeltaEvent/type`. - public var _type: Components.Schemas.ResponseReasoningSummaryDeltaEvent._TypePayload - /// The unique identifier of the item for which the reasoning summary is being updated. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDeltaEvent/item_id`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/type`. + public var _type: Components.Schemas.ResponseReasoningSummaryPartDoneEvent._TypePayload + /// The ID of the item this summary part is associated with. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/item_id`. public var itemId: Swift.String - /// The index of the output item in the response's output array. + /// The index of the output item this summary part is associated with. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDeltaEvent/output_index`. + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/output_index`. public var outputIndex: Swift.Int - /// The index of the summary part within the output item. + /// The index of the summary part within the reasoning summary. + /// /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDeltaEvent/summary_index`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/summary_index`. public var summaryIndex: Swift.Int /// The sequence number of this event. /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDeltaEvent/sequence_number`. + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/sequence_number`. public var sequenceNumber: Swift.Int - /// The partial update to the reasoning summary content. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDeltaEvent/delta`. - public var delta: OpenAPIRuntime.OpenAPIObjectContainer - /// Creates a new `ResponseReasoningSummaryDeltaEvent`. - /// - /// - Parameters: - /// - _type: The type of the event. Always 'response.reasoning_summary.delta'. - /// - itemId: The unique identifier of the item for which the reasoning summary is being updated. - /// - outputIndex: The index of the output item in the response's output array. - /// - summaryIndex: The index of the summary part within the output item. - /// - sequenceNumber: The sequence number of this event. - /// - delta: The partial update to the reasoning summary content. - public init( - _type: Components.Schemas.ResponseReasoningSummaryDeltaEvent._TypePayload, - itemId: Swift.String, - outputIndex: Swift.Int, - summaryIndex: Swift.Int, - sequenceNumber: Swift.Int, - delta: OpenAPIRuntime.OpenAPIObjectContainer - ) { - self._type = _type - self.itemId = itemId - self.outputIndex = outputIndex - self.summaryIndex = summaryIndex - self.sequenceNumber = sequenceNumber - self.delta = delta - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case itemId = "item_id" - case outputIndex = "output_index" - case summaryIndex = "summary_index" - case sequenceNumber = "sequence_number" - case delta - } - } - /// Emitted when the reasoning summary content is finalized for an item. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDoneEvent`. - public struct ResponseReasoningSummaryDoneEvent: Codable, Hashable, Sendable { - /// The type of the event. Always 'response.reasoning_summary.done'. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDoneEvent/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_reasoningSummary_done = "response.reasoning_summary.done" - } - /// The type of the event. Always 'response.reasoning_summary.done'. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDoneEvent/type`. - public var _type: Components.Schemas.ResponseReasoningSummaryDoneEvent._TypePayload - /// The unique identifier of the item for which the reasoning summary is finalized. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDoneEvent/item_id`. - public var itemId: Swift.String - /// The index of the output item in the response's output array. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDoneEvent/output_index`. - public var outputIndex: Swift.Int - /// The index of the summary part within the output item. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDoneEvent/summary_index`. - public var summaryIndex: Swift.Int - /// The finalized reasoning summary text. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDoneEvent/text`. - public var text: Swift.String - /// The sequence number of this event. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryDoneEvent/sequence_number`. - public var sequenceNumber: Swift.Int - /// Creates a new `ResponseReasoningSummaryDoneEvent`. - /// - /// - Parameters: - /// - _type: The type of the event. Always 'response.reasoning_summary.done'. - /// - itemId: The unique identifier of the item for which the reasoning summary is finalized. - /// - outputIndex: The index of the output item in the response's output array. - /// - summaryIndex: The index of the summary part within the output item. - /// - text: The finalized reasoning summary text. - /// - sequenceNumber: The sequence number of this event. - public init( - _type: Components.Schemas.ResponseReasoningSummaryDoneEvent._TypePayload, - itemId: Swift.String, - outputIndex: Swift.Int, - summaryIndex: Swift.Int, - text: Swift.String, - sequenceNumber: Swift.Int - ) { - self._type = _type - self.itemId = itemId - self.outputIndex = outputIndex - self.summaryIndex = summaryIndex - self.text = text - self.sequenceNumber = sequenceNumber - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case itemId = "item_id" - case outputIndex = "output_index" - case summaryIndex = "summary_index" - case text - case sequenceNumber = "sequence_number" - } - } - /// Emitted when a new reasoning summary part is added. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent`. - public struct ResponseReasoningSummaryPartAddedEvent: Codable, Hashable, Sendable { - /// The type of the event. Always `response.reasoning_summary_part.added`. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_reasoningSummaryPart_added = "response.reasoning_summary_part.added" - } - /// The type of the event. Always `response.reasoning_summary_part.added`. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/type`. - public var _type: Components.Schemas.ResponseReasoningSummaryPartAddedEvent._TypePayload - /// The ID of the item this summary part is associated with. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/item_id`. - public var itemId: Swift.String - /// The index of the output item this summary part is associated with. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/output_index`. - public var outputIndex: Swift.Int - /// The index of the summary part within the reasoning summary. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/summary_index`. - public var summaryIndex: Swift.Int - /// The sequence number of this event. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/sequence_number`. - public var sequenceNumber: Swift.Int - /// The summary part that was added. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part`. - public struct PartPayload: Codable, Hashable, Sendable { - /// The type of the summary part. Always `summary_text`. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case summaryText = "summary_text" - } - /// The type of the summary part. Always `summary_text`. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part/type`. - public var _type: Components.Schemas.ResponseReasoningSummaryPartAddedEvent.PartPayload._TypePayload - /// The text of the summary part. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part/text`. - public var text: Swift.String - /// Creates a new `PartPayload`. - /// - /// - Parameters: - /// - _type: The type of the summary part. Always `summary_text`. - /// - text: The text of the summary part. - public init( - _type: Components.Schemas.ResponseReasoningSummaryPartAddedEvent.PartPayload._TypePayload, - text: Swift.String - ) { - self._type = _type - self.text = text - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case text - } - } - /// The summary part that was added. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartAddedEvent/part`. - public var part: Components.Schemas.ResponseReasoningSummaryPartAddedEvent.PartPayload - /// Creates a new `ResponseReasoningSummaryPartAddedEvent`. - /// - /// - Parameters: - /// - _type: The type of the event. Always `response.reasoning_summary_part.added`. - /// - itemId: The ID of the item this summary part is associated with. - /// - outputIndex: The index of the output item this summary part is associated with. - /// - summaryIndex: The index of the summary part within the reasoning summary. - /// - sequenceNumber: The sequence number of this event. - /// - part: The summary part that was added. - public init( - _type: Components.Schemas.ResponseReasoningSummaryPartAddedEvent._TypePayload, - itemId: Swift.String, - outputIndex: Swift.Int, - summaryIndex: Swift.Int, - sequenceNumber: Swift.Int, - part: Components.Schemas.ResponseReasoningSummaryPartAddedEvent.PartPayload - ) { - self._type = _type - self.itemId = itemId - self.outputIndex = outputIndex - self.summaryIndex = summaryIndex - self.sequenceNumber = sequenceNumber - self.part = part - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case itemId = "item_id" - case outputIndex = "output_index" - case summaryIndex = "summary_index" - case sequenceNumber = "sequence_number" - case part - } - } - /// Emitted when a reasoning summary part is completed. - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent`. - public struct ResponseReasoningSummaryPartDoneEvent: Codable, Hashable, Sendable { - /// The type of the event. Always `response.reasoning_summary_part.done`. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_reasoningSummaryPart_done = "response.reasoning_summary_part.done" - } - /// The type of the event. Always `response.reasoning_summary_part.done`. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/type`. - public var _type: Components.Schemas.ResponseReasoningSummaryPartDoneEvent._TypePayload - /// The ID of the item this summary part is associated with. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/item_id`. - public var itemId: Swift.String - /// The index of the output item this summary part is associated with. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/output_index`. - public var outputIndex: Swift.Int - /// The index of the summary part within the reasoning summary. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/summary_index`. - public var summaryIndex: Swift.Int - /// The sequence number of this event. - /// - /// - /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/sequence_number`. - public var sequenceNumber: Swift.Int - /// The completed summary part. + /// The completed summary part. /// /// /// - Remark: Generated from `#/components/schemas/ResponseReasoningSummaryPartDoneEvent/part`. @@ -8295,58 +8718,58 @@ public enum Components { case sequenceNumber = "sequence_number" } } - /// Emitted when there is a partial refusal text. + /// Emitted when a delta is added to a reasoning text. /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent`. - public struct ResponseRefusalDeltaEvent: Codable, Hashable, Sendable { - /// The type of the event. Always `response.refusal.delta`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDeltaEvent`. + public struct ResponseReasoningTextDeltaEvent: Codable, Hashable, Sendable { + /// The type of the event. Always `response.reasoning_text.delta`. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/type`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDeltaEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_refusal_delta = "response.refusal.delta" + case response_reasoningText_delta = "response.reasoning_text.delta" } - /// The type of the event. Always `response.refusal.delta`. + /// The type of the event. Always `response.reasoning_text.delta`. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/type`. - public var _type: Components.Schemas.ResponseRefusalDeltaEvent._TypePayload - /// The ID of the output item that the refusal text is added to. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDeltaEvent/type`. + public var _type: Components.Schemas.ResponseReasoningTextDeltaEvent._TypePayload + /// The ID of the item this reasoning text delta is associated with. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/item_id`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDeltaEvent/item_id`. public var itemId: Swift.String - /// The index of the output item that the refusal text is added to. + /// The index of the output item this reasoning text delta is associated with. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/output_index`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDeltaEvent/output_index`. public var outputIndex: Swift.Int - /// The index of the content part that the refusal text is added to. + /// The index of the reasoning content part this delta is associated with. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/content_index`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDeltaEvent/content_index`. public var contentIndex: Swift.Int - /// The refusal text that is added. + /// The text delta that was added to the reasoning content. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/delta`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDeltaEvent/delta`. public var delta: Swift.String /// The sequence number of this event. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/sequence_number`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDeltaEvent/sequence_number`. public var sequenceNumber: Swift.Int - /// Creates a new `ResponseRefusalDeltaEvent`. + /// Creates a new `ResponseReasoningTextDeltaEvent`. /// /// - Parameters: - /// - _type: The type of the event. Always `response.refusal.delta`. - /// - itemId: The ID of the output item that the refusal text is added to. - /// - outputIndex: The index of the output item that the refusal text is added to. - /// - contentIndex: The index of the content part that the refusal text is added to. - /// - delta: The refusal text that is added. + /// - _type: The type of the event. Always `response.reasoning_text.delta`. + /// - itemId: The ID of the item this reasoning text delta is associated with. + /// - outputIndex: The index of the output item this reasoning text delta is associated with. + /// - contentIndex: The index of the reasoning content part this delta is associated with. + /// - delta: The text delta that was added to the reasoning content. /// - sequenceNumber: The sequence number of this event. public init( - _type: Components.Schemas.ResponseRefusalDeltaEvent._TypePayload, + _type: Components.Schemas.ResponseReasoningTextDeltaEvent._TypePayload, itemId: Swift.String, outputIndex: Swift.Int, contentIndex: Swift.Int, @@ -8369,28 +8792,176 @@ public enum Components { case sequenceNumber = "sequence_number" } } - /// Emitted when refusal text is finalized. + /// Emitted when a reasoning text is completed. /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDoneEvent`. - public struct ResponseRefusalDoneEvent: Codable, Hashable, Sendable { - /// The type of the event. Always `response.refusal.done`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDoneEvent`. + public struct ResponseReasoningTextDoneEvent: Codable, Hashable, Sendable { + /// The type of the event. Always `response.reasoning_text.done`. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDoneEvent/type`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDoneEvent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case response_refusal_done = "response.refusal.done" + case response_reasoningText_done = "response.reasoning_text.done" } - /// The type of the event. Always `response.refusal.done`. + /// The type of the event. Always `response.reasoning_text.done`. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDoneEvent/type`. - public var _type: Components.Schemas.ResponseRefusalDoneEvent._TypePayload - /// The ID of the output item that the refusal text is finalized. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDoneEvent/type`. + public var _type: Components.Schemas.ResponseReasoningTextDoneEvent._TypePayload + /// The ID of the item this reasoning text is associated with. /// /// - /// - Remark: Generated from `#/components/schemas/ResponseRefusalDoneEvent/item_id`. + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDoneEvent/item_id`. public var itemId: Swift.String - /// The index of the output item that the refusal text is finalized. + /// The index of the output item this reasoning text is associated with. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDoneEvent/output_index`. + public var outputIndex: Swift.Int + /// The index of the reasoning content part. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDoneEvent/content_index`. + public var contentIndex: Swift.Int + /// The full text of the completed reasoning content. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDoneEvent/text`. + public var text: Swift.String + /// The sequence number of this event. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseReasoningTextDoneEvent/sequence_number`. + public var sequenceNumber: Swift.Int + /// Creates a new `ResponseReasoningTextDoneEvent`. + /// + /// - Parameters: + /// - _type: The type of the event. Always `response.reasoning_text.done`. + /// - itemId: The ID of the item this reasoning text is associated with. + /// - outputIndex: The index of the output item this reasoning text is associated with. + /// - contentIndex: The index of the reasoning content part. + /// - text: The full text of the completed reasoning content. + /// - sequenceNumber: The sequence number of this event. + public init( + _type: Components.Schemas.ResponseReasoningTextDoneEvent._TypePayload, + itemId: Swift.String, + outputIndex: Swift.Int, + contentIndex: Swift.Int, + text: Swift.String, + sequenceNumber: Swift.Int + ) { + self._type = _type + self.itemId = itemId + self.outputIndex = outputIndex + self.contentIndex = contentIndex + self.text = text + self.sequenceNumber = sequenceNumber + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case itemId = "item_id" + case outputIndex = "output_index" + case contentIndex = "content_index" + case text + case sequenceNumber = "sequence_number" + } + } + /// Emitted when there is a partial refusal text. + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent`. + public struct ResponseRefusalDeltaEvent: Codable, Hashable, Sendable { + /// The type of the event. Always `response.refusal.delta`. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case response_refusal_delta = "response.refusal.delta" + } + /// The type of the event. Always `response.refusal.delta`. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/type`. + public var _type: Components.Schemas.ResponseRefusalDeltaEvent._TypePayload + /// The ID of the output item that the refusal text is added to. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/item_id`. + public var itemId: Swift.String + /// The index of the output item that the refusal text is added to. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/output_index`. + public var outputIndex: Swift.Int + /// The index of the content part that the refusal text is added to. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/content_index`. + public var contentIndex: Swift.Int + /// The refusal text that is added. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/delta`. + public var delta: Swift.String + /// The sequence number of this event. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDeltaEvent/sequence_number`. + public var sequenceNumber: Swift.Int + /// Creates a new `ResponseRefusalDeltaEvent`. + /// + /// - Parameters: + /// - _type: The type of the event. Always `response.refusal.delta`. + /// - itemId: The ID of the output item that the refusal text is added to. + /// - outputIndex: The index of the output item that the refusal text is added to. + /// - contentIndex: The index of the content part that the refusal text is added to. + /// - delta: The refusal text that is added. + /// - sequenceNumber: The sequence number of this event. + public init( + _type: Components.Schemas.ResponseRefusalDeltaEvent._TypePayload, + itemId: Swift.String, + outputIndex: Swift.Int, + contentIndex: Swift.Int, + delta: Swift.String, + sequenceNumber: Swift.Int + ) { + self._type = _type + self.itemId = itemId + self.outputIndex = outputIndex + self.contentIndex = contentIndex + self.delta = delta + self.sequenceNumber = sequenceNumber + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case itemId = "item_id" + case outputIndex = "output_index" + case contentIndex = "content_index" + case delta + case sequenceNumber = "sequence_number" + } + } + /// Emitted when refusal text is finalized. + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDoneEvent`. + public struct ResponseRefusalDoneEvent: Codable, Hashable, Sendable { + /// The type of the event. Always `response.refusal.done`. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDoneEvent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case response_refusal_done = "response.refusal.done" + } + /// The type of the event. Always `response.refusal.done`. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDoneEvent/type`. + public var _type: Components.Schemas.ResponseRefusalDoneEvent._TypePayload + /// The ID of the output item that the refusal text is finalized. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseRefusalDoneEvent/item_id`. + public var itemId: Swift.String + /// The index of the output item that the refusal text is finalized. /// /// /// - Remark: Generated from `#/components/schemas/ResponseRefusalDoneEvent/output_index`. @@ -8502,55 +9073,55 @@ public enum Components { /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value28`. public var value28: Components.Schemas.ResponseReasoningSummaryTextDoneEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value29`. - public var value29: Components.Schemas.ResponseRefusalDeltaEvent? + public var value29: Components.Schemas.ResponseReasoningTextDeltaEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value30`. - public var value30: Components.Schemas.ResponseRefusalDoneEvent? + public var value30: Components.Schemas.ResponseReasoningTextDoneEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value31`. - public var value31: Components.Schemas.ResponseTextDeltaEvent? + public var value31: Components.Schemas.ResponseRefusalDeltaEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value32`. - public var value32: Components.Schemas.ResponseTextDoneEvent? + public var value32: Components.Schemas.ResponseRefusalDoneEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value33`. - public var value33: Components.Schemas.ResponseWebSearchCallCompletedEvent? + public var value33: Components.Schemas.ResponseTextDeltaEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value34`. - public var value34: Components.Schemas.ResponseWebSearchCallInProgressEvent? + public var value34: Components.Schemas.ResponseTextDoneEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value35`. - public var value35: Components.Schemas.ResponseWebSearchCallSearchingEvent? + public var value35: Components.Schemas.ResponseWebSearchCallCompletedEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value36`. - public var value36: Components.Schemas.ResponseImageGenCallCompletedEvent? + public var value36: Components.Schemas.ResponseWebSearchCallInProgressEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value37`. - public var value37: Components.Schemas.ResponseImageGenCallGeneratingEvent? + public var value37: Components.Schemas.ResponseWebSearchCallSearchingEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value38`. - public var value38: Components.Schemas.ResponseImageGenCallInProgressEvent? + public var value38: Components.Schemas.ResponseImageGenCallCompletedEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value39`. - public var value39: Components.Schemas.ResponseImageGenCallPartialImageEvent? + public var value39: Components.Schemas.ResponseImageGenCallGeneratingEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value40`. - public var value40: Components.Schemas.ResponseMCPCallArgumentsDeltaEvent? + public var value40: Components.Schemas.ResponseImageGenCallInProgressEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value41`. - public var value41: Components.Schemas.ResponseMCPCallArgumentsDoneEvent? + public var value41: Components.Schemas.ResponseImageGenCallPartialImageEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value42`. - public var value42: Components.Schemas.ResponseMCPCallCompletedEvent? + public var value42: Components.Schemas.ResponseMCPCallArgumentsDeltaEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value43`. - public var value43: Components.Schemas.ResponseMCPCallFailedEvent? + public var value43: Components.Schemas.ResponseMCPCallArgumentsDoneEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value44`. - public var value44: Components.Schemas.ResponseMCPCallInProgressEvent? + public var value44: Components.Schemas.ResponseMCPCallCompletedEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value45`. - public var value45: Components.Schemas.ResponseMCPListToolsCompletedEvent? + public var value45: Components.Schemas.ResponseMCPCallFailedEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value46`. - public var value46: Components.Schemas.ResponseMCPListToolsFailedEvent? + public var value46: Components.Schemas.ResponseMCPCallInProgressEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value47`. - public var value47: Components.Schemas.ResponseMCPListToolsInProgressEvent? + public var value47: Components.Schemas.ResponseMCPListToolsCompletedEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value48`. - public var value48: Components.Schemas.ResponseOutputTextAnnotationAddedEvent? + public var value48: Components.Schemas.ResponseMCPListToolsFailedEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value49`. - public var value49: Components.Schemas.ResponseQueuedEvent? + public var value49: Components.Schemas.ResponseMCPListToolsInProgressEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value50`. - public var value50: Components.Schemas.ResponseReasoningDeltaEvent? + public var value50: Components.Schemas.ResponseOutputTextAnnotationAddedEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value51`. - public var value51: Components.Schemas.ResponseReasoningDoneEvent? + public var value51: Components.Schemas.ResponseQueuedEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value52`. - public var value52: Components.Schemas.ResponseReasoningSummaryDeltaEvent? + public var value52: Components.Schemas.ResponseCustomToolCallInputDeltaEvent? /// - Remark: Generated from `#/components/schemas/ResponseStreamEvent/value53`. - public var value53: Components.Schemas.ResponseReasoningSummaryDoneEvent? + public var value53: Components.Schemas.ResponseCustomToolCallInputDoneEvent? /// Creates a new `ResponseStreamEvent`. /// /// - Parameters: @@ -8636,31 +9207,31 @@ public enum Components { value26: Components.Schemas.ResponseReasoningSummaryPartDoneEvent? = nil, value27: Components.Schemas.ResponseReasoningSummaryTextDeltaEvent? = nil, value28: Components.Schemas.ResponseReasoningSummaryTextDoneEvent? = nil, - value29: Components.Schemas.ResponseRefusalDeltaEvent? = nil, - value30: Components.Schemas.ResponseRefusalDoneEvent? = nil, - value31: Components.Schemas.ResponseTextDeltaEvent? = nil, - value32: Components.Schemas.ResponseTextDoneEvent? = nil, - value33: Components.Schemas.ResponseWebSearchCallCompletedEvent? = nil, - value34: Components.Schemas.ResponseWebSearchCallInProgressEvent? = nil, - value35: Components.Schemas.ResponseWebSearchCallSearchingEvent? = nil, - value36: Components.Schemas.ResponseImageGenCallCompletedEvent? = nil, - value37: Components.Schemas.ResponseImageGenCallGeneratingEvent? = nil, - value38: Components.Schemas.ResponseImageGenCallInProgressEvent? = nil, - value39: Components.Schemas.ResponseImageGenCallPartialImageEvent? = nil, - value40: Components.Schemas.ResponseMCPCallArgumentsDeltaEvent? = nil, - value41: Components.Schemas.ResponseMCPCallArgumentsDoneEvent? = nil, - value42: Components.Schemas.ResponseMCPCallCompletedEvent? = nil, - value43: Components.Schemas.ResponseMCPCallFailedEvent? = nil, - value44: Components.Schemas.ResponseMCPCallInProgressEvent? = nil, - value45: Components.Schemas.ResponseMCPListToolsCompletedEvent? = nil, - value46: Components.Schemas.ResponseMCPListToolsFailedEvent? = nil, - value47: Components.Schemas.ResponseMCPListToolsInProgressEvent? = nil, - value48: Components.Schemas.ResponseOutputTextAnnotationAddedEvent? = nil, - value49: Components.Schemas.ResponseQueuedEvent? = nil, - value50: Components.Schemas.ResponseReasoningDeltaEvent? = nil, - value51: Components.Schemas.ResponseReasoningDoneEvent? = nil, - value52: Components.Schemas.ResponseReasoningSummaryDeltaEvent? = nil, - value53: Components.Schemas.ResponseReasoningSummaryDoneEvent? = nil + value29: Components.Schemas.ResponseReasoningTextDeltaEvent? = nil, + value30: Components.Schemas.ResponseReasoningTextDoneEvent? = nil, + value31: Components.Schemas.ResponseRefusalDeltaEvent? = nil, + value32: Components.Schemas.ResponseRefusalDoneEvent? = nil, + value33: Components.Schemas.ResponseTextDeltaEvent? = nil, + value34: Components.Schemas.ResponseTextDoneEvent? = nil, + value35: Components.Schemas.ResponseWebSearchCallCompletedEvent? = nil, + value36: Components.Schemas.ResponseWebSearchCallInProgressEvent? = nil, + value37: Components.Schemas.ResponseWebSearchCallSearchingEvent? = nil, + value38: Components.Schemas.ResponseImageGenCallCompletedEvent? = nil, + value39: Components.Schemas.ResponseImageGenCallGeneratingEvent? = nil, + value40: Components.Schemas.ResponseImageGenCallInProgressEvent? = nil, + value41: Components.Schemas.ResponseImageGenCallPartialImageEvent? = nil, + value42: Components.Schemas.ResponseMCPCallArgumentsDeltaEvent? = nil, + value43: Components.Schemas.ResponseMCPCallArgumentsDoneEvent? = nil, + value44: Components.Schemas.ResponseMCPCallCompletedEvent? = nil, + value45: Components.Schemas.ResponseMCPCallFailedEvent? = nil, + value46: Components.Schemas.ResponseMCPCallInProgressEvent? = nil, + value47: Components.Schemas.ResponseMCPListToolsCompletedEvent? = nil, + value48: Components.Schemas.ResponseMCPListToolsFailedEvent? = nil, + value49: Components.Schemas.ResponseMCPListToolsInProgressEvent? = nil, + value50: Components.Schemas.ResponseOutputTextAnnotationAddedEvent? = nil, + value51: Components.Schemas.ResponseQueuedEvent? = nil, + value52: Components.Schemas.ResponseCustomToolCallInputDeltaEvent? = nil, + value53: Components.Schemas.ResponseCustomToolCallInputDoneEvent? = nil ) { self.value1 = value1 self.value2 = value2 @@ -8716,8 +9287,8 @@ public enum Components { self.value52 = value52 self.value53 = value53 } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self.value1 = try .init(from: decoder) } catch { @@ -9044,7 +9615,7 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try self.value1?.encode(to: encoder) try self.value2?.encode(to: encoder) try self.value3?.encode(to: encoder) @@ -9100,6 +9671,33 @@ public enum Components { try self.value53?.encode(to: encoder) } } + /// Options for streaming responses. Only set this when you set `stream: true`. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseStreamOptions`. + public struct ResponseStreamOptions: Codable, Hashable, Sendable { + /// When true, stream obfuscation will be enabled. Stream obfuscation adds + /// random characters to an `obfuscation` field on streaming delta events to + /// normalize payload sizes as a mitigation to certain side-channel attacks. + /// These obfuscation fields are included by default, but add a small amount + /// of overhead to the data stream. You can set `include_obfuscation` to + /// false to optimize for bandwidth if you trust the network links between + /// your application and the OpenAI API. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseStreamOptions/include_obfuscation`. + public var includeObfuscation: Swift.Bool? + /// Creates a new `ResponseStreamOptions`. + /// + /// - Parameters: + /// - includeObfuscation: When true, stream obfuscation will be enabled. Stream obfuscation adds + public init(includeObfuscation: Swift.Bool? = nil) { + self.includeObfuscation = includeObfuscation + } + public enum CodingKeys: String, CodingKey { + case includeObfuscation = "include_obfuscation" + } + } /// Emitted when there is an additional text delta. /// /// - Remark: Generated from `#/components/schemas/ResponseTextDeltaEvent`. @@ -9140,6 +9738,11 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseTextDeltaEvent/sequence_number`. public var sequenceNumber: Swift.Int + /// The log probabilities of the tokens in the delta. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseTextDeltaEvent/logprobs`. + public var logprobs: [Components.Schemas.ResponseLogProb] /// Creates a new `ResponseTextDeltaEvent`. /// /// - Parameters: @@ -9149,13 +9752,15 @@ public enum Components { /// - contentIndex: The index of the content part that the text delta was added to. /// - delta: The text delta that was added. /// - sequenceNumber: The sequence number for this event. + /// - logprobs: The log probabilities of the tokens in the delta. public init( _type: Components.Schemas.ResponseTextDeltaEvent._TypePayload, itemId: Swift.String, outputIndex: Swift.Int, contentIndex: Swift.Int, delta: Swift.String, - sequenceNumber: Swift.Int + sequenceNumber: Swift.Int, + logprobs: [Components.Schemas.ResponseLogProb] ) { self._type = _type self.itemId = itemId @@ -9163,6 +9768,7 @@ public enum Components { self.contentIndex = contentIndex self.delta = delta self.sequenceNumber = sequenceNumber + self.logprobs = logprobs } public enum CodingKeys: String, CodingKey { case _type = "type" @@ -9171,6 +9777,7 @@ public enum Components { case contentIndex = "content_index" case delta case sequenceNumber = "sequence_number" + case logprobs } } /// Emitted when text content is finalized. @@ -9213,6 +9820,11 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseTextDoneEvent/sequence_number`. public var sequenceNumber: Swift.Int + /// The log probabilities of the tokens in the delta. + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseTextDoneEvent/logprobs`. + public var logprobs: [Components.Schemas.ResponseLogProb] /// Creates a new `ResponseTextDoneEvent`. /// /// - Parameters: @@ -9222,13 +9834,15 @@ public enum Components { /// - contentIndex: The index of the content part that the text content is finalized. /// - text: The text content that is finalized. /// - sequenceNumber: The sequence number for this event. + /// - logprobs: The log probabilities of the tokens in the delta. public init( _type: Components.Schemas.ResponseTextDoneEvent._TypePayload, itemId: Swift.String, outputIndex: Swift.Int, contentIndex: Swift.Int, text: Swift.String, - sequenceNumber: Swift.Int + sequenceNumber: Swift.Int, + logprobs: [Components.Schemas.ResponseLogProb] ) { self._type = _type self.itemId = itemId @@ -9236,6 +9850,7 @@ public enum Components { self.contentIndex = contentIndex self.text = text self.sequenceNumber = sequenceNumber + self.logprobs = logprobs } public enum CodingKeys: String, CodingKey { case _type = "type" @@ -9244,6 +9859,36 @@ public enum Components { case contentIndex = "content_index" case text case sequenceNumber = "sequence_number" + case logprobs + } + } + /// Configuration options for a text response from the model. Can be plain + /// text or structured JSON data. Learn more: + /// - [Text inputs and outputs](/docs/guides/text) + /// - [Structured Outputs](/docs/guides/structured-outputs) + /// + /// + /// - Remark: Generated from `#/components/schemas/ResponseTextParam`. + public struct ResponseTextParam: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/ResponseTextParam/format`. + public var format: Components.Schemas.TextResponseFormatConfiguration? + /// - Remark: Generated from `#/components/schemas/ResponseTextParam/verbosity`. + public var verbosity: Components.Schemas.Verbosity? + /// Creates a new `ResponseTextParam`. + /// + /// - Parameters: + /// - format: + /// - verbosity: + public init( + format: Components.Schemas.TextResponseFormatConfiguration? = nil, + verbosity: Components.Schemas.Verbosity? = nil + ) { + self.format = format + self.verbosity = verbosity + } + public enum CodingKeys: String, CodingKey { + case format + case verbosity } } /// Represents token usage details including input tokens, output tokens, @@ -9506,113 +10151,13 @@ public enum Components { case sequenceNumber = "sequence_number" } } - /// A screenshot action. - /// - /// - /// - Remark: Generated from `#/components/schemas/Screenshot`. - public struct Screenshot: Codable, Hashable, Sendable { - /// Specifies the event type. For a screenshot action, this property is - /// always set to `screenshot`. - /// - /// - /// - Remark: Generated from `#/components/schemas/Screenshot/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case screenshot = "screenshot" - } - /// Specifies the event type. For a screenshot action, this property is - /// always set to `screenshot`. - /// - /// - /// - Remark: Generated from `#/components/schemas/Screenshot/type`. - public var _type: Components.Schemas.Screenshot._TypePayload - /// Creates a new `Screenshot`. - /// - /// - Parameters: - /// - _type: Specifies the event type. For a screenshot action, this property is - public init(_type: Components.Schemas.Screenshot._TypePayload) { - self._type = _type - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - } - } - /// A scroll action. - /// - /// - /// - Remark: Generated from `#/components/schemas/Scroll`. - public struct Scroll: Codable, Hashable, Sendable { - /// Specifies the event type. For a scroll action, this property is - /// always set to `scroll`. - /// - /// - /// - Remark: Generated from `#/components/schemas/Scroll/type`. - @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case scroll = "scroll" - } - /// Specifies the event type. For a scroll action, this property is - /// always set to `scroll`. - /// - /// - /// - Remark: Generated from `#/components/schemas/Scroll/type`. - public var _type: Components.Schemas.Scroll._TypePayload - /// The x-coordinate where the scroll occurred. - /// - /// - /// - Remark: Generated from `#/components/schemas/Scroll/x`. - public var x: Swift.Int - /// The y-coordinate where the scroll occurred. - /// - /// - /// - Remark: Generated from `#/components/schemas/Scroll/y`. - public var y: Swift.Int - /// The horizontal scroll distance. - /// - /// - /// - Remark: Generated from `#/components/schemas/Scroll/scroll_x`. - public var scrollX: Swift.Int - /// The vertical scroll distance. - /// - /// - /// - Remark: Generated from `#/components/schemas/Scroll/scroll_y`. - public var scrollY: Swift.Int - /// Creates a new `Scroll`. - /// - /// - Parameters: - /// - _type: Specifies the event type. For a scroll action, this property is - /// - x: The x-coordinate where the scroll occurred. - /// - y: The y-coordinate where the scroll occurred. - /// - scrollX: The horizontal scroll distance. - /// - scrollY: The vertical scroll distance. - public init( - _type: Components.Schemas.Scroll._TypePayload, - x: Swift.Int, - y: Swift.Int, - scrollX: Swift.Int, - scrollY: Swift.Int - ) { - self._type = _type - self.x = x - self.y = y - self.scrollX = scrollX - self.scrollY = scrollY - } - public enum CodingKeys: String, CodingKey { - case _type = "type" - case x - case y - case scrollX = "scroll_x" - case scrollY = "scroll_y" - } - } - /// Specifies the latency tier to use for processing the request. This parameter is relevant for customers subscribed to the scale tier service: - /// - If set to 'auto', and the Project is Scale tier enabled, the system - /// will utilize scale tier credits until they are exhausted. - /// - If set to 'auto', and the Project is not Scale tier enabled, the request will be processed using the default service tier with a lower uptime SLA and no latency guarantee. - /// - If set to 'default', the request will be processed using the default service tier with a lower uptime SLA and no latency guarantee. - /// - If set to 'flex', the request will be processed with the Flex Processing service tier. [Learn more](/docs/guides/flex-processing). + /// Specifies the processing type used for serving the request. + /// - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'. + /// - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model. + /// - If set to '[flex](/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier. /// - When not set, the default behavior is 'auto'. /// - /// When this parameter is set, the response body will include the `service_tier` utilized. + /// When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter. /// /// /// - Remark: Generated from `#/components/schemas/ServiceTier`. @@ -9621,6 +10166,7 @@ public enum Components { case _default = "default" case flex = "flex" case scale = "scale" + case priority = "priority" } /// An object specifying the format that the model must output. /// @@ -9645,8 +10191,8 @@ public enum Components { case TextResponseFormatJsonSchema(Components.Schemas.TextResponseFormatJsonSchema) /// - Remark: Generated from `#/components/schemas/TextResponseFormatConfiguration/case3`. case ResponseFormatJsonObject(Components.Schemas.ResponseFormatJsonObject) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self = .ResponseFormatText(try .init(from: decoder)) return @@ -9671,7 +10217,7 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .ResponseFormatText(value): try value.encode(to: encoder) @@ -9712,13 +10258,7 @@ 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). - /// - /// + public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/TextResponseFormatJsonSchema/strict`. public var strict: Swift.Bool? /// Creates a new `TextResponseFormatJsonSchema`. @@ -9728,7 +10268,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: Whether to enable strict schema adherence when generating the output. + /// - strict: public init( _type: Components.Schemas.TextResponseFormatJsonSchema._TypePayload, description: Swift.String? = nil, @@ -9759,22 +10299,36 @@ public enum Components { case functionTool(Components.Schemas.FunctionTool) /// - Remark: Generated from `#/components/schemas/Tool/FileSearchTool`. case fileSearchTool(Components.Schemas.FileSearchTool) - /// - Remark: Generated from `#/components/schemas/Tool/WebSearchPreviewTool`. - case webSearchPreviewTool(Components.Schemas.WebSearchPreviewTool) + /// - Remark: Generated from `#/components/schemas/Tool/ComputerTool`. + case computerTool(Components.Schemas.ComputerTool) /// - Remark: Generated from `#/components/schemas/Tool/ComputerUsePreviewTool`. case computerUsePreviewTool(Components.Schemas.ComputerUsePreviewTool) + /// - Remark: Generated from `#/components/schemas/Tool/WebSearchTool`. + case webSearchTool(Components.Schemas.WebSearchTool) /// - Remark: Generated from `#/components/schemas/Tool/MCPTool`. case mcpTool(Components.Schemas.MCPTool) /// - Remark: Generated from `#/components/schemas/Tool/CodeInterpreterTool`. case codeInterpreterTool(Components.Schemas.CodeInterpreterTool) /// - Remark: Generated from `#/components/schemas/Tool/ImageGenTool`. case imageGenTool(Components.Schemas.ImageGenTool) - /// - Remark: Generated from `#/components/schemas/Tool/LocalShellTool`. - case localShellTool(Components.Schemas.LocalShellTool) + /// - Remark: Generated from `#/components/schemas/Tool/LocalShellToolParam`. + case localShellToolParam(Components.Schemas.LocalShellToolParam) + /// - Remark: Generated from `#/components/schemas/Tool/FunctionShellToolParam`. + case functionShellToolParam(Components.Schemas.FunctionShellToolParam) + /// - Remark: Generated from `#/components/schemas/Tool/CustomToolParam`. + case customToolParam(Components.Schemas.CustomToolParam) + /// - Remark: Generated from `#/components/schemas/Tool/NamespaceToolParam`. + case namespaceToolParam(Components.Schemas.NamespaceToolParam) + /// - Remark: Generated from `#/components/schemas/Tool/ToolSearchToolParam`. + case toolSearchToolParam(Components.Schemas.ToolSearchToolParam) + /// - Remark: Generated from `#/components/schemas/Tool/WebSearchPreviewTool`. + case webSearchPreviewTool(Components.Schemas.WebSearchPreviewTool) + /// - Remark: Generated from `#/components/schemas/Tool/ApplyPatchToolParam`. + case applyPatchToolParam(Components.Schemas.ApplyPatchToolParam) public enum CodingKeys: String, CodingKey { case _type = "type" } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let discriminator = try container.decode( Swift.String.self, @@ -9785,18 +10339,32 @@ public enum Components { self = .functionTool(try .init(from: decoder)) case "FileSearchTool", "#/components/schemas/FileSearchTool": self = .fileSearchTool(try .init(from: decoder)) - case "WebSearchPreviewTool", "#/components/schemas/WebSearchPreviewTool": - self = .webSearchPreviewTool(try .init(from: decoder)) + case "ComputerTool", "#/components/schemas/ComputerTool": + self = .computerTool(try .init(from: decoder)) case "ComputerUsePreviewTool", "#/components/schemas/ComputerUsePreviewTool": self = .computerUsePreviewTool(try .init(from: decoder)) + case "WebSearchTool", "#/components/schemas/WebSearchTool": + self = .webSearchTool(try .init(from: decoder)) case "MCPTool", "#/components/schemas/MCPTool": self = .mcpTool(try .init(from: decoder)) case "CodeInterpreterTool", "#/components/schemas/CodeInterpreterTool": self = .codeInterpreterTool(try .init(from: decoder)) case "ImageGenTool", "#/components/schemas/ImageGenTool": self = .imageGenTool(try .init(from: decoder)) - case "LocalShellTool", "#/components/schemas/LocalShellTool": - self = .localShellTool(try .init(from: decoder)) + case "LocalShellToolParam", "#/components/schemas/LocalShellToolParam": + self = .localShellToolParam(try .init(from: decoder)) + case "FunctionShellToolParam", "#/components/schemas/FunctionShellToolParam": + self = .functionShellToolParam(try .init(from: decoder)) + case "CustomToolParam", "#/components/schemas/CustomToolParam": + self = .customToolParam(try .init(from: decoder)) + case "NamespaceToolParam", "#/components/schemas/NamespaceToolParam": + self = .namespaceToolParam(try .init(from: decoder)) + case "ToolSearchToolParam", "#/components/schemas/ToolSearchToolParam": + self = .toolSearchToolParam(try .init(from: decoder)) + case "WebSearchPreviewTool", "#/components/schemas/WebSearchPreviewTool": + self = .webSearchPreviewTool(try .init(from: decoder)) + case "ApplyPatchToolParam", "#/components/schemas/ApplyPatchToolParam": + self = .applyPatchToolParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( discriminatorKey: CodingKeys._type, @@ -9805,27 +10373,185 @@ public enum Components { ) } } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .functionTool(value): try value.encode(to: encoder) case let .fileSearchTool(value): try value.encode(to: encoder) - case let .webSearchPreviewTool(value): + case let .computerTool(value): try value.encode(to: encoder) case let .computerUsePreviewTool(value): try value.encode(to: encoder) + case let .webSearchTool(value): + try value.encode(to: encoder) case let .mcpTool(value): try value.encode(to: encoder) case let .codeInterpreterTool(value): try value.encode(to: encoder) case let .imageGenTool(value): try value.encode(to: encoder) - case let .localShellTool(value): + case let .localShellToolParam(value): + try value.encode(to: encoder) + case let .functionShellToolParam(value): + try value.encode(to: encoder) + case let .customToolParam(value): + try value.encode(to: encoder) + case let .namespaceToolParam(value): + try value.encode(to: encoder) + case let .toolSearchToolParam(value): + try value.encode(to: encoder) + case let .webSearchPreviewTool(value): + try value.encode(to: encoder) + case let .applyPatchToolParam(value): try value.encode(to: encoder) } } } + /// Constrains the tools available to the model to a pre-defined set. + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceAllowed`. + public struct ToolChoiceAllowed: Codable, Hashable, Sendable { + /// Allowed tool configuration type. Always `allowed_tools`. + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceAllowed/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case allowedTools = "allowed_tools" + } + /// Allowed tool configuration type. Always `allowed_tools`. + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceAllowed/type`. + public var _type: Components.Schemas.ToolChoiceAllowed._TypePayload + /// Constrains the tools available to the model to a pre-defined set. + /// + /// `auto` allows the model to pick from among the allowed tools and generate a + /// message. + /// + /// `required` requires the model to call one or more of the allowed tools. + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceAllowed/mode`. + @frozen public enum ModePayload: String, Codable, Hashable, Sendable, CaseIterable { + case auto = "auto" + case required = "required" + } + /// Constrains the tools available to the model to a pre-defined set. + /// + /// `auto` allows the model to pick from among the allowed tools and generate a + /// message. + /// + /// `required` requires the model to call one or more of the allowed tools. + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceAllowed/mode`. + public var mode: Components.Schemas.ToolChoiceAllowed.ModePayload + /// A tool definition that the model should be allowed to call. + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceAllowed/ToolsPayload`. + public struct ToolsPayloadPayload: Codable, Hashable, Sendable { + /// A container of undocumented properties. + public var additionalProperties: OpenAPIRuntime.OpenAPIObjectContainer + /// Creates a new `ToolsPayloadPayload`. + /// + /// - Parameters: + /// - additionalProperties: A container of undocumented properties. + public init(additionalProperties: OpenAPIRuntime.OpenAPIObjectContainer = .init()) { + self.additionalProperties = additionalProperties + } + public init(from decoder: any Swift.Decoder) throws { + additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) + } + public func encode(to encoder: any Swift.Encoder) throws { + try encoder.encodeAdditionalProperties(additionalProperties) + } + } + /// A list of tool definitions that the model should be allowed to call. + /// + /// For the Responses API, the list of tool definitions might look like: + /// ```json + /// [ + /// { "type": "function", "name": "get_weather" }, + /// { "type": "mcp", "server_label": "deepwiki" }, + /// { "type": "image_generation" } + /// ] + /// ``` + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceAllowed/tools`. + public typealias ToolsPayload = [Components.Schemas.ToolChoiceAllowed.ToolsPayloadPayload] + /// A list of tool definitions that the model should be allowed to call. + /// + /// For the Responses API, the list of tool definitions might look like: + /// ```json + /// [ + /// { "type": "function", "name": "get_weather" }, + /// { "type": "mcp", "server_label": "deepwiki" }, + /// { "type": "image_generation" } + /// ] + /// ``` + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceAllowed/tools`. + public var tools: Components.Schemas.ToolChoiceAllowed.ToolsPayload + /// Creates a new `ToolChoiceAllowed`. + /// + /// - Parameters: + /// - _type: Allowed tool configuration type. Always `allowed_tools`. + /// - mode: Constrains the tools available to the model to a pre-defined set. + /// - tools: A list of tool definitions that the model should be allowed to call. + public init( + _type: Components.Schemas.ToolChoiceAllowed._TypePayload, + mode: Components.Schemas.ToolChoiceAllowed.ModePayload, + tools: Components.Schemas.ToolChoiceAllowed.ToolsPayload + ) { + self._type = _type + self.mode = mode + self.tools = tools + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case mode + case tools + } + } + /// Use this option to force the model to call a specific custom tool. + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceCustom`. + public struct ToolChoiceCustom: Codable, Hashable, Sendable { + /// For custom tool calling, the type is always `custom`. + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceCustom/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case custom = "custom" + } + /// For custom tool calling, the type is always `custom`. + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceCustom/type`. + public var _type: Components.Schemas.ToolChoiceCustom._TypePayload + /// The name of the custom tool to call. + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceCustom/name`. + public var name: Swift.String + /// Creates a new `ToolChoiceCustom`. + /// + /// - Parameters: + /// - _type: For custom tool calling, the type is always `custom`. + /// - name: The name of the custom tool to call. + public init( + _type: Components.Schemas.ToolChoiceCustom._TypePayload, + name: Swift.String + ) { + self._type = _type + self.name = name + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case name + } + } /// Use this option to force the model to call a specific function. /// /// @@ -9862,6 +10588,50 @@ public enum Components { case name } } + /// Use this option to force the model to call a specific tool on a remote MCP server. + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceMCP`. + public struct ToolChoiceMCP: Codable, Hashable, Sendable { + /// For MCP tools, the type is always `mcp`. + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceMCP/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case mcp = "mcp" + } + /// For MCP tools, the type is always `mcp`. + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceMCP/type`. + public var _type: Components.Schemas.ToolChoiceMCP._TypePayload + /// The label of the MCP server to use. + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceMCP/server_label`. + public var serverLabel: Swift.String + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ToolChoiceMCP/name`. + public var name: Swift.String? + /// Creates a new `ToolChoiceMCP`. + /// + /// - Parameters: + /// - _type: For MCP tools, the type is always `mcp`. + /// - serverLabel: The label of the MCP server to use. + /// - name: + public init( + _type: Components.Schemas.ToolChoiceMCP._TypePayload, + serverLabel: Swift.String, + name: Swift.String? = nil + ) { + self._type = _type + self.serverLabel = serverLabel + self.name = name + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case serverLabel = "server_label" + case name + } + } /// Controls which (if any) tool is called by the model. /// /// `none` means the model will not call any tool and instead generates a message. @@ -9878,6 +10648,106 @@ public enum Components { case auto = "auto" case required = "required" } + /// How the model should select which tool (or tools) to use when generating + /// a response. See the `tools` parameter to see how to specify which tools + /// the model can call. + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolChoiceParam`. + @frozen public enum ToolChoiceParam: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/ToolChoiceParam/case1`. + case ToolChoiceOptions(Components.Schemas.ToolChoiceOptions) + /// - Remark: Generated from `#/components/schemas/ToolChoiceParam/case2`. + case ToolChoiceAllowed(Components.Schemas.ToolChoiceAllowed) + /// - Remark: Generated from `#/components/schemas/ToolChoiceParam/case3`. + case ToolChoiceTypes(Components.Schemas.ToolChoiceTypes) + /// - Remark: Generated from `#/components/schemas/ToolChoiceParam/case4`. + case ToolChoiceFunction(Components.Schemas.ToolChoiceFunction) + /// - Remark: Generated from `#/components/schemas/ToolChoiceParam/case5`. + case ToolChoiceMCP(Components.Schemas.ToolChoiceMCP) + /// - Remark: Generated from `#/components/schemas/ToolChoiceParam/case6`. + case ToolChoiceCustom(Components.Schemas.ToolChoiceCustom) + /// - Remark: Generated from `#/components/schemas/ToolChoiceParam/case7`. + case SpecificApplyPatchParam(Components.Schemas.SpecificApplyPatchParam) + /// - Remark: Generated from `#/components/schemas/ToolChoiceParam/case8`. + case SpecificFunctionShellParam(Components.Schemas.SpecificFunctionShellParam) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self = .ToolChoiceOptions(try decoder.decodeFromSingleValueContainer()) + return + } catch { + errors.append(error) + } + do { + self = .ToolChoiceAllowed(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .ToolChoiceTypes(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .ToolChoiceFunction(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .ToolChoiceMCP(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .ToolChoiceCustom(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .SpecificApplyPatchParam(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .SpecificFunctionShellParam(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + throw Swift.DecodingError.failedToDecodeOneOfSchema( + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .ToolChoiceOptions(value): + try encoder.encodeToSingleValueContainer(value) + case let .ToolChoiceAllowed(value): + try value.encode(to: encoder) + case let .ToolChoiceTypes(value): + try value.encode(to: encoder) + case let .ToolChoiceFunction(value): + try value.encode(to: encoder) + case let .ToolChoiceMCP(value): + try value.encode(to: encoder) + case let .ToolChoiceCustom(value): + try value.encode(to: encoder) + case let .SpecificApplyPatchParam(value): + try value.encode(to: encoder) + case let .SpecificFunctionShellParam(value): + try value.encode(to: encoder) + } + } + } /// Indicates that the model should use a built-in tool to generate a response. /// [Learn more about built-in tools](/docs/guides/tools). /// @@ -9890,9 +10760,10 @@ public enum Components { /// Allowed values are: /// - `file_search` /// - `web_search_preview` + /// - `computer` /// - `computer_use_preview` + /// - `computer_use` /// - `code_interpreter` - /// - `mcp` /// - `image_generation` /// /// @@ -9900,11 +10771,12 @@ public enum Components { @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { case fileSearch = "file_search" case webSearchPreview = "web_search_preview" + case computer = "computer" case computerUsePreview = "computer_use_preview" + case computerUse = "computer_use" case webSearchPreview20250311 = "web_search_preview_2025_03_11" case imageGeneration = "image_generation" case codeInterpreter = "code_interpreter" - case mcp = "mcp" } /// The type of hosted tool the model should to use. Learn more about /// [built-in tools](/docs/guides/tools). @@ -9912,9 +10784,10 @@ public enum Components { /// Allowed values are: /// - `file_search` /// - `web_search_preview` + /// - `computer` /// - `computer_use_preview` + /// - `computer_use` /// - `code_interpreter` - /// - `mcp` /// - `image_generation` /// /// @@ -9931,6 +10804,26 @@ public enum Components { case _type = "type" } } + /// An array of tools the model may call while generating a response. You + /// can specify which tool to use by setting the `tool_choice` parameter. + /// + /// We support the following categories of tools: + /// - **Built-in tools**: Tools that are provided by OpenAI that extend the + /// model's capabilities, like [web search](/docs/guides/tools-web-search) + /// or [file search](/docs/guides/tools-file-search). Learn more about + /// [built-in tools](/docs/guides/tools). + /// - **MCP Tools**: Integrations with third-party systems via custom MCP servers + /// or predefined connectors such as Google Drive and SharePoint. Learn more about + /// [MCP Tools](/docs/guides/tools-connectors-mcp). + /// - **Function calls (custom tools)**: Functions that are defined by you, + /// enabling the model to call your own code with strongly typed arguments + /// and outputs. Learn more about + /// [function calling](/docs/guides/function-calling). You can also use + /// custom tools to call your own code. + /// + /// + /// - Remark: Generated from `#/components/schemas/ToolsArray`. + public typealias ToolsArray = [Components.Schemas.Tool] /// Emitted when there is an additional text delta. This is also the first event emitted when the transcription starts. Only emitted when you [create a transcription](/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`. /// /// - Remark: Generated from `#/components/schemas/TranscriptTextDeltaEvent`. @@ -10000,25 +10893,34 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/TranscriptTextDeltaEvent/logprobs`. public var logprobs: Components.Schemas.TranscriptTextDeltaEvent.LogprobsPayload? + /// Identifier of the diarized segment that this delta belongs to. Only present when using `gpt-4o-transcribe-diarize`. + /// + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextDeltaEvent/segment_id`. + public var segmentId: Swift.String? /// Creates a new `TranscriptTextDeltaEvent`. /// /// - Parameters: /// - _type: The type of the event. Always `transcript.text.delta`. /// - delta: The text delta that was additionally transcribed. /// - logprobs: The log probabilities of the delta. Only included if you [create a transcription](/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`. + /// - segmentId: Identifier of the diarized segment that this delta belongs to. Only present when using `gpt-4o-transcribe-diarize`. public init( _type: Components.Schemas.TranscriptTextDeltaEvent._TypePayload, delta: Swift.String, - logprobs: Components.Schemas.TranscriptTextDeltaEvent.LogprobsPayload? = nil + logprobs: Components.Schemas.TranscriptTextDeltaEvent.LogprobsPayload? = nil, + segmentId: Swift.String? = nil ) { self._type = _type self.delta = delta self.logprobs = logprobs + self.segmentId = segmentId } public enum CodingKeys: String, CodingKey { case _type = "type" case delta case logprobs + case segmentId = "segment_id" } } /// Emitted when the transcription is complete. Contains the complete transcription text. Only emitted when you [create a transcription](/docs/api-reference/audio/create-transcription) with the `Stream` parameter set to `true`. @@ -10090,196 +10992,422 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/TranscriptTextDoneEvent/logprobs`. public var logprobs: Components.Schemas.TranscriptTextDoneEvent.LogprobsPayload? + /// - Remark: Generated from `#/components/schemas/TranscriptTextDoneEvent/usage`. + public var usage: Components.Schemas.TranscriptTextUsageTokens? /// Creates a new `TranscriptTextDoneEvent`. /// /// - Parameters: /// - _type: The type of the event. Always `transcript.text.done`. /// - text: The text that was transcribed. /// - logprobs: The log probabilities of the individual tokens in the transcription. Only included if you [create a transcription](/docs/api-reference/audio/create-transcription) with the `include[]` parameter set to `logprobs`. + /// - usage: public init( _type: Components.Schemas.TranscriptTextDoneEvent._TypePayload, text: Swift.String, - logprobs: Components.Schemas.TranscriptTextDoneEvent.LogprobsPayload? = nil + logprobs: Components.Schemas.TranscriptTextDoneEvent.LogprobsPayload? = nil, + usage: Components.Schemas.TranscriptTextUsageTokens? = nil ) { self._type = _type self.text = text self.logprobs = logprobs + self.usage = usage } public enum CodingKeys: String, CodingKey { case _type = "type" case text case logprobs + case usage } } - /// - Remark: Generated from `#/components/schemas/TranscriptionInclude`. - @frozen public enum TranscriptionInclude: String, Codable, Hashable, Sendable, CaseIterable { - case logprobs = "logprobs" - } - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment`. - public struct TranscriptionSegment: Codable, Hashable, Sendable { - /// Unique identifier of the segment. + /// Emitted when a diarized transcription returns a completed segment with speaker information. Only emitted when you [create a transcription](/docs/api-reference/audio/create-transcription) with `stream` set to `true` and `response_format` set to `diarized_json`. + /// + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextSegmentEvent`. + public struct TranscriptTextSegmentEvent: Codable, Hashable, Sendable { + /// The type of the event. Always `transcript.text.segment`. /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/id`. - public var id: Swift.Int - /// Seek offset of the segment. + /// - Remark: Generated from `#/components/schemas/TranscriptTextSegmentEvent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case transcript_text_segment = "transcript.text.segment" + } + /// The type of the event. Always `transcript.text.segment`. /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/seek`. - public var seek: Swift.Int - /// Start time of the segment in seconds. + /// - Remark: Generated from `#/components/schemas/TranscriptTextSegmentEvent/type`. + public var _type: Components.Schemas.TranscriptTextSegmentEvent._TypePayload + /// Unique identifier for the segment. /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/start`. + /// - Remark: Generated from `#/components/schemas/TranscriptTextSegmentEvent/id`. + public var id: Swift.String + /// Start timestamp of the segment in seconds. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextSegmentEvent/start`. public var start: Swift.Float - /// End time of the segment in seconds. + /// End timestamp of the segment in seconds. /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/end`. + /// - Remark: Generated from `#/components/schemas/TranscriptTextSegmentEvent/end`. public var end: Swift.Float - /// Text content of the segment. + /// Transcript text for this segment. /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/text`. + /// - Remark: Generated from `#/components/schemas/TranscriptTextSegmentEvent/text`. public var text: Swift.String - /// Array of token IDs for the text content. - /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/tokens`. - public var tokens: [Swift.Int] - /// Temperature parameter used for generating the segment. - /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/temperature`. - public var temperature: Swift.Float - /// Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. - /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/avg_logprob`. - public var avgLogprob: Swift.Float - /// Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. - /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/compression_ratio`. - public var compressionRatio: Swift.Float - /// Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. + /// Speaker label for this segment. /// - /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/no_speech_prob`. - public var noSpeechProb: Swift.Float - /// Creates a new `TranscriptionSegment`. + /// - Remark: Generated from `#/components/schemas/TranscriptTextSegmentEvent/speaker`. + public var speaker: Swift.String + /// Creates a new `TranscriptTextSegmentEvent`. /// /// - Parameters: - /// - id: Unique identifier of the segment. - /// - seek: Seek offset of the segment. - /// - start: Start time of the segment in seconds. - /// - end: End time of the segment in seconds. - /// - text: Text content of the segment. - /// - tokens: Array of token IDs for the text content. - /// - temperature: Temperature parameter used for generating the segment. - /// - avgLogprob: Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. - /// - compressionRatio: Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. - /// - noSpeechProb: Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. + /// - _type: The type of the event. Always `transcript.text.segment`. + /// - id: Unique identifier for the segment. + /// - start: Start timestamp of the segment in seconds. + /// - end: End timestamp of the segment in seconds. + /// - text: Transcript text for this segment. + /// - speaker: Speaker label for this segment. public init( - id: Swift.Int, - seek: Swift.Int, + _type: Components.Schemas.TranscriptTextSegmentEvent._TypePayload, + id: Swift.String, start: Swift.Float, end: Swift.Float, text: Swift.String, - tokens: [Swift.Int], - temperature: Swift.Float, - avgLogprob: Swift.Float, - compressionRatio: Swift.Float, - noSpeechProb: Swift.Float + speaker: Swift.String ) { + self._type = _type self.id = id - self.seek = seek self.start = start self.end = end self.text = text - self.tokens = tokens - self.temperature = temperature - self.avgLogprob = avgLogprob - self.compressionRatio = compressionRatio - self.noSpeechProb = noSpeechProb + self.speaker = speaker } public enum CodingKeys: String, CodingKey { + case _type = "type" case id - case seek case start case end case text - case tokens - case temperature - case avgLogprob = "avg_logprob" - case compressionRatio = "compression_ratio" - case noSpeechProb = "no_speech_prob" + case speaker } } - /// - Remark: Generated from `#/components/schemas/TranscriptionWord`. - public struct TranscriptionWord: Codable, Hashable, Sendable { - /// The text content of the word. + /// Usage statistics for models billed by audio input duration. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageDuration`. + public struct TranscriptTextUsageDuration: Codable, Hashable, Sendable { + /// The type of the usage object. Always `duration` for this variant. /// - /// - Remark: Generated from `#/components/schemas/TranscriptionWord/word`. - public var word: Swift.String - /// Start time of the word in seconds. + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageDuration/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case duration = "duration" + } + /// The type of the usage object. Always `duration` for this variant. /// - /// - Remark: Generated from `#/components/schemas/TranscriptionWord/start`. - public var start: Swift.Float - /// End time of the word in seconds. + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageDuration/type`. + public var _type: Components.Schemas.TranscriptTextUsageDuration._TypePayload + /// Duration of the input audio in seconds. /// - /// - Remark: Generated from `#/components/schemas/TranscriptionWord/end`. - public var end: Swift.Float - /// Creates a new `TranscriptionWord`. + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageDuration/seconds`. + public var seconds: Swift.Double + /// Creates a new `TranscriptTextUsageDuration`. /// /// - Parameters: - /// - word: The text content of the word. - /// - start: Start time of the word in seconds. - /// - end: End time of the word in seconds. + /// - _type: The type of the usage object. Always `duration` for this variant. + /// - seconds: Duration of the input audio in seconds. public init( - word: Swift.String, - start: Swift.Float, - end: Swift.Float + _type: Components.Schemas.TranscriptTextUsageDuration._TypePayload, + seconds: Swift.Double ) { - self.word = word - self.start = start - self.end = end + self._type = _type + self.seconds = seconds } public enum CodingKeys: String, CodingKey { - case word - case start - case end + case _type = "type" + case seconds } } - /// An action to type in text. + /// Usage statistics for models billed by token usage. /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens`. + public struct TranscriptTextUsageTokens: Codable, Hashable, Sendable { + /// The type of the usage object. Always `tokens` for this variant. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case tokens = "tokens" + } + /// The type of the usage object. Always `tokens` for this variant. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens/type`. + public var _type: Components.Schemas.TranscriptTextUsageTokens._TypePayload + /// Number of input tokens billed for this request. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens/input_tokens`. + public var inputTokens: Swift.Int + /// Details about the input tokens billed for this request. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens/input_token_details`. + public struct InputTokenDetailsPayload: Codable, Hashable, Sendable { + /// Number of text tokens billed for this request. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens/input_token_details/text_tokens`. + public var textTokens: Swift.Int? + /// Number of audio tokens billed for this request. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens/input_token_details/audio_tokens`. + public var audioTokens: Swift.Int? + /// Creates a new `InputTokenDetailsPayload`. + /// + /// - Parameters: + /// - textTokens: Number of text tokens billed for this request. + /// - audioTokens: Number of audio tokens billed for this request. + public init( + textTokens: Swift.Int? = nil, + audioTokens: Swift.Int? = nil + ) { + self.textTokens = textTokens + self.audioTokens = audioTokens + } + public enum CodingKeys: String, CodingKey { + case textTokens = "text_tokens" + case audioTokens = "audio_tokens" + } + } + /// Details about the input tokens billed for this request. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens/input_token_details`. + public var inputTokenDetails: Components.Schemas.TranscriptTextUsageTokens.InputTokenDetailsPayload? + /// Number of output tokens generated. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens/output_tokens`. + public var outputTokens: Swift.Int + /// Total number of tokens used (input + output). + /// + /// - Remark: Generated from `#/components/schemas/TranscriptTextUsageTokens/total_tokens`. + public var totalTokens: Swift.Int + /// Creates a new `TranscriptTextUsageTokens`. + /// + /// - Parameters: + /// - _type: The type of the usage object. Always `tokens` for this variant. + /// - inputTokens: Number of input tokens billed for this request. + /// - inputTokenDetails: Details about the input tokens billed for this request. + /// - outputTokens: Number of output tokens generated. + /// - totalTokens: Total number of tokens used (input + output). + public init( + _type: Components.Schemas.TranscriptTextUsageTokens._TypePayload, + inputTokens: Swift.Int, + inputTokenDetails: Components.Schemas.TranscriptTextUsageTokens.InputTokenDetailsPayload? = nil, + outputTokens: Swift.Int, + totalTokens: Swift.Int + ) { + self._type = _type + self.inputTokens = inputTokens + self.inputTokenDetails = inputTokenDetails + self.outputTokens = outputTokens + self.totalTokens = totalTokens + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case inputTokens = "input_tokens" + case inputTokenDetails = "input_token_details" + case outputTokens = "output_tokens" + case totalTokens = "total_tokens" + } + } + /// A segment of diarized transcript text with speaker metadata. /// - /// - Remark: Generated from `#/components/schemas/Type`. - public struct _Type: Codable, Hashable, Sendable { - /// Specifies the event type. For a type action, this property is - /// always set to `type`. + /// - Remark: Generated from `#/components/schemas/TranscriptionDiarizedSegment`. + public struct TranscriptionDiarizedSegment: Codable, Hashable, Sendable { + /// The type of the segment. Always `transcript.text.segment`. /// /// - /// - Remark: Generated from `#/components/schemas/Type/type`. + /// - Remark: Generated from `#/components/schemas/TranscriptionDiarizedSegment/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case _type = "type" + case transcript_text_segment = "transcript.text.segment" } - /// Specifies the event type. For a type action, this property is - /// always set to `type`. + /// The type of the segment. Always `transcript.text.segment`. /// /// - /// - Remark: Generated from `#/components/schemas/Type/type`. - public var _type: Components.Schemas._Type._TypePayload - /// The text to type. + /// - Remark: Generated from `#/components/schemas/TranscriptionDiarizedSegment/type`. + public var _type: Components.Schemas.TranscriptionDiarizedSegment._TypePayload + /// Unique identifier for the segment. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionDiarizedSegment/id`. + public var id: Swift.String + /// Start timestamp of the segment in seconds. /// + /// - Remark: Generated from `#/components/schemas/TranscriptionDiarizedSegment/start`. + public var start: Swift.Float + /// End timestamp of the segment in seconds. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionDiarizedSegment/end`. + public var end: Swift.Float + /// Transcript text for this segment. /// - /// - Remark: Generated from `#/components/schemas/Type/text`. + /// - Remark: Generated from `#/components/schemas/TranscriptionDiarizedSegment/text`. public var text: Swift.String - /// Creates a new `_Type`. + /// Speaker label for this segment. When known speakers are provided, the label matches `known_speaker_names[]`. Otherwise speakers are labeled sequentially using capital letters (`A`, `B`, ...). + /// + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionDiarizedSegment/speaker`. + public var speaker: Swift.String + /// Creates a new `TranscriptionDiarizedSegment`. /// /// - Parameters: - /// - _type: Specifies the event type. For a type action, this property is - /// - text: The text to type. + /// - _type: The type of the segment. Always `transcript.text.segment`. + /// - id: Unique identifier for the segment. + /// - start: Start timestamp of the segment in seconds. + /// - end: End timestamp of the segment in seconds. + /// - text: Transcript text for this segment. + /// - speaker: Speaker label for this segment. When known speakers are provided, the label matches `known_speaker_names[]`. Otherwise speakers are labeled sequentially using capital letters (`A`, `B`, ...). public init( - _type: Components.Schemas._Type._TypePayload, - text: Swift.String + _type: Components.Schemas.TranscriptionDiarizedSegment._TypePayload, + id: Swift.String, + start: Swift.Float, + end: Swift.Float, + text: Swift.String, + speaker: Swift.String ) { self._type = _type + self.id = id + self.start = start + self.end = end self.text = text + self.speaker = speaker } public enum CodingKeys: String, CodingKey { case _type = "type" + case id + case start + case end + case text + case speaker + } + } + /// - Remark: Generated from `#/components/schemas/TranscriptionInclude`. + @frozen public enum TranscriptionInclude: String, Codable, Hashable, Sendable, CaseIterable { + case logprobs = "logprobs" + } + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment`. + public struct TranscriptionSegment: Codable, Hashable, Sendable { + /// Unique identifier of the segment. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/id`. + public var id: Swift.Int + /// Seek offset of the segment. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/seek`. + public var seek: Swift.Int + /// Start time of the segment in seconds. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/start`. + public var start: Swift.Float + /// End time of the segment in seconds. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/end`. + public var end: Swift.Float + /// Text content of the segment. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/text`. + public var text: Swift.String + /// Array of token IDs for the text content. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/tokens`. + public var tokens: [Swift.Int] + /// Temperature parameter used for generating the segment. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/temperature`. + public var temperature: Swift.Float + /// Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/avg_logprob`. + public var avgLogprob: Swift.Float + /// Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/compression_ratio`. + public var compressionRatio: Swift.Float + /// Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionSegment/no_speech_prob`. + public var noSpeechProb: Swift.Float + /// Creates a new `TranscriptionSegment`. + /// + /// - Parameters: + /// - id: Unique identifier of the segment. + /// - seek: Seek offset of the segment. + /// - start: Start time of the segment in seconds. + /// - end: End time of the segment in seconds. + /// - text: Text content of the segment. + /// - tokens: Array of token IDs for the text content. + /// - temperature: Temperature parameter used for generating the segment. + /// - avgLogprob: Average logprob of the segment. If the value is lower than -1, consider the logprobs failed. + /// - compressionRatio: Compression ratio of the segment. If the value is greater than 2.4, consider the compression failed. + /// - noSpeechProb: Probability of no speech in the segment. If the value is higher than 1.0 and the `avg_logprob` is below -1, consider this segment silent. + public init( + id: Swift.Int, + seek: Swift.Int, + start: Swift.Float, + end: Swift.Float, + text: Swift.String, + tokens: [Swift.Int], + temperature: Swift.Float, + avgLogprob: Swift.Float, + compressionRatio: Swift.Float, + noSpeechProb: Swift.Float + ) { + self.id = id + self.seek = seek + self.start = start + self.end = end + self.text = text + self.tokens = tokens + self.temperature = temperature + self.avgLogprob = avgLogprob + self.compressionRatio = compressionRatio + self.noSpeechProb = noSpeechProb + } + public enum CodingKeys: String, CodingKey { + case id + case seek + case start + case end case text + case tokens + case temperature + case avgLogprob = "avg_logprob" + case compressionRatio = "compression_ratio" + case noSpeechProb = "no_speech_prob" + } + } + /// - Remark: Generated from `#/components/schemas/TranscriptionWord`. + public struct TranscriptionWord: Codable, Hashable, Sendable { + /// The text content of the word. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionWord/word`. + public var word: Swift.String + /// Start time of the word in seconds. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionWord/start`. + public var start: Swift.Float + /// End time of the word in seconds. + /// + /// - Remark: Generated from `#/components/schemas/TranscriptionWord/end`. + public var end: Swift.Float + /// Creates a new `TranscriptionWord`. + /// + /// - Parameters: + /// - word: The text content of the word. + /// - start: Start time of the word in seconds. + /// - end: End time of the word in seconds. + public init( + word: Swift.String, + start: Swift.Float, + end: Swift.Float + ) { + self.word = word + self.start = start + self.end = end + } + public enum CodingKeys: String, CodingKey { + case word + case start + case end } } /// - Remark: Generated from `#/components/schemas/VadConfig`. @@ -10338,7 +11466,7 @@ public enum Components { case silenceDurationMs = "silence_duration_ms" case threshold } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) self._type = try container.decode( Components.Schemas.VadConfig._TypePayload.self, @@ -10381,8 +11509,8 @@ public enum Components { case case2(Swift.Double) /// - Remark: Generated from `#/components/schemas/VectorStoreFileAttributes/additionalProperties/case3`. case case3(Swift.Bool) - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { self = .case1(try decoder.decodeFromSingleValueContainer()) return @@ -10407,7 +11535,7 @@ public enum Components { errors: errors ) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { case let .case1(value): try encoder.encodeToSingleValueContainer(value) @@ -10427,81 +11555,309 @@ public enum Components { public init(additionalProperties: [String: Components.Schemas.VectorStoreFileAttributes.AdditionalPropertiesPayload] = .init()) { self.additionalProperties = additionalProperties } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { try encoder.encodeAdditionalProperties(additionalProperties) } } - /// A wait action. + /// Constrains the verbosity of the model's response. Lower values will result in + /// more concise responses, while higher values will result in more verbose responses. + /// Currently supported values are `low`, `medium`, and `high`. /// /// - /// - Remark: Generated from `#/components/schemas/Wait`. - public struct Wait: Codable, Hashable, Sendable { - /// Specifies the event type. For a wait action, this property is - /// always set to `wait`. + /// - Remark: Generated from `#/components/schemas/Verbosity`. + @frozen public enum Verbosity: String, Codable, Hashable, Sendable, CaseIterable { + case low = "low" + case medium = "medium" + case high = "high" + } + /// Action type "find_in_page": Searches for a pattern within a loaded page. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionFind`. + public struct WebSearchActionFind: Codable, Hashable, Sendable { + /// The action type. /// /// - /// - Remark: Generated from `#/components/schemas/Wait/type`. + /// - Remark: Generated from `#/components/schemas/WebSearchActionFind/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case wait = "wait" + case findInPage = "find_in_page" } - /// Specifies the event type. For a wait action, this property is - /// always set to `wait`. + /// The action type. + /// /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionFind/type`. + public var _type: Components.Schemas.WebSearchActionFind._TypePayload + /// The URL of the page searched for the pattern. /// - /// - Remark: Generated from `#/components/schemas/Wait/type`. - public var _type: Components.Schemas.Wait._TypePayload - /// Creates a new `Wait`. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionFind/url`. + public var url: Swift.String + /// The pattern or text to search for within the page. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionFind/pattern`. + public var pattern: Swift.String + /// Creates a new `WebSearchActionFind`. /// /// - Parameters: - /// - _type: Specifies the event type. For a wait action, this property is - public init(_type: Components.Schemas.Wait._TypePayload) { + /// - _type: The action type. + /// - url: The URL of the page searched for the pattern. + /// - pattern: The pattern or text to search for within the page. + public init( + _type: Components.Schemas.WebSearchActionFind._TypePayload, + url: Swift.String, + pattern: Swift.String + ) { self._type = _type + self.url = url + self.pattern = pattern } public enum CodingKeys: String, CodingKey { case _type = "type" + case url + case pattern } } - /// 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. - /// + /// Action type "open_page" - Opens a specific URL from search results. /// - /// - Remark: Generated from `#/components/schemas/WebSearchContextSize`. - @frozen public enum WebSearchContextSize: String, Codable, Hashable, Sendable, CaseIterable { - case low = "low" - case medium = "medium" - case high = "high" - } - /// Approximate location parameters for the search. /// - /// - Remark: Generated from `#/components/schemas/WebSearchLocation`. - public struct WebSearchLocation: Codable, Hashable, Sendable { - /// 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/WebSearchActionOpenPage`. + public struct WebSearchActionOpenPage: Codable, Hashable, Sendable { + /// The action type. /// /// - /// - Remark: Generated from `#/components/schemas/WebSearchLocation/country`. - public var country: Swift.String? - /// Free text input for the region of the user, e.g. `California`. - /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionOpenPage/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case openPage = "open_page" + } + /// The action type. /// - /// - Remark: Generated from `#/components/schemas/WebSearchLocation/region`. - public var region: Swift.String? - /// Free text input for the city of the user, e.g. `San Francisco`. /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionOpenPage/type`. + public var _type: Components.Schemas.WebSearchActionOpenPage._TypePayload + /// The URL opened by the model. /// - /// - Remark: Generated from `#/components/schemas/WebSearchLocation/city`. - public var city: Swift.String? - /// The [IANA timezone](https://timeapi.io/documentation/iana-timezones) - /// of the user, e.g. `America/Los_Angeles`. + public typealias String = Swift.String + /// The URL opened by the model. /// /// - /// - Remark: Generated from `#/components/schemas/WebSearchLocation/timezone`. - public var timezone: Swift.String? - /// Creates a new `WebSearchLocation`. + /// - Remark: Generated from `#/components/schemas/WebSearchActionOpenPage/url`. + public var url: Swift.String? + /// Creates a new `WebSearchActionOpenPage`. + /// + /// - Parameters: + /// - _type: The action type. + /// - url: The URL opened by the model. + public init( + _type: Components.Schemas.WebSearchActionOpenPage._TypePayload, + url: Swift.String? = nil + ) { + self._type = _type + self.url = url + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case url + } + } + /// Action type "search" - Performs a web search query. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch`. + public struct WebSearchActionSearch: Codable, Hashable, Sendable { + /// The action type. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case search = "search" + } + /// The action type. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/type`. + public var _type: Components.Schemas.WebSearchActionSearch._TypePayload + /// [DEPRECATED] The search query. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/query`. + public var query: Swift.String + /// The search queries. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/queries`. + public var queries: [Swift.String]? + /// A source used in the search. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/SourcesPayload`. + public struct SourcesPayloadPayload: Codable, Hashable, Sendable { + /// The type of source. Always `url`. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/SourcesPayload/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case url = "url" + } + /// The type of source. Always `url`. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/SourcesPayload/type`. + public var _type: Components.Schemas.WebSearchActionSearch.SourcesPayloadPayload._TypePayload + /// The URL of the source. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/SourcesPayload/url`. + public var url: Swift.String + /// Creates a new `SourcesPayloadPayload`. + /// + /// - Parameters: + /// - _type: The type of source. Always `url`. + /// - url: The URL of the source. + public init( + _type: Components.Schemas.WebSearchActionSearch.SourcesPayloadPayload._TypePayload, + url: Swift.String + ) { + self._type = _type + self.url = url + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case url + } + } + /// The sources used in the search. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/sources`. + public typealias SourcesPayload = [Components.Schemas.WebSearchActionSearch.SourcesPayloadPayload] + /// The sources used in the search. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/sources`. + public var sources: Components.Schemas.WebSearchActionSearch.SourcesPayload? + /// Creates a new `WebSearchActionSearch`. + /// + /// - Parameters: + /// - _type: The action type. + /// - query: [DEPRECATED] The search query. + /// - queries: The search queries. + /// - sources: The sources used in the search. + public init( + _type: Components.Schemas.WebSearchActionSearch._TypePayload, + query: Swift.String, + queries: [Swift.String]? = nil, + sources: Components.Schemas.WebSearchActionSearch.SourcesPayload? = nil + ) { + self._type = _type + self.query = query + self.queries = queries + self.sources = sources + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case query + case queries + case sources + } + } + /// The approximate location of the user. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation`. + public struct WebSearchApproximateLocation: Codable, Hashable, Sendable { + /// The type of location approximation. Always `approximate`. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case approximate = "approximate" + } + /// The type of location approximation. Always `approximate`. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/type`. + public var _type: Components.Schemas.WebSearchApproximateLocation._TypePayload? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/country`. + public var country: Swift.String? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/region`. + public var region: Swift.String? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/city`. + public var city: Swift.String? + public typealias String = Swift.String + /// - 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: + public init( + _type: Components.Schemas.WebSearchApproximateLocation._TypePayload? = nil, + country: Swift.String? = nil, + region: Swift.String? = nil, + city: Swift.String? = nil, + timezone: Swift.String? = nil + ) { + self._type = _type + self.country = country + self.region = region + self.city = city + self.timezone = timezone + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case country + case region + case city + case timezone + } + } + /// 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. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchContextSize`. + @frozen public enum WebSearchContextSize: String, Codable, Hashable, Sendable, CaseIterable { + case low = "low" + case medium = "medium" + case high = "high" + } + /// Approximate location parameters for the search. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchLocation`. + public struct WebSearchLocation: Codable, Hashable, Sendable { + /// 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/WebSearchLocation/country`. + public var country: Swift.String? + /// Free text input for the region of the user, e.g. `California`. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchLocation/region`. + public var region: Swift.String? + /// Free text input for the city of the user, e.g. `San Francisco`. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchLocation/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/WebSearchLocation/timezone`. + public var timezone: Swift.String? + /// Creates a new `WebSearchLocation`. /// /// - Parameters: /// - country: The two-letter @@ -10526,6 +11882,83 @@ public enum Components { case timezone } } + /// Search the Internet for sources related to the prompt. Learn more about the + /// [web search tool](/docs/guides/tools-web-search). + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchTool`. + public struct WebSearchTool: Codable, Hashable, Sendable { + /// The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchTool/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case webSearch = "web_search" + case webSearch20250826 = "web_search_2025_08_26" + } + /// The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchTool/type`. + public var _type: Components.Schemas.WebSearchTool._TypePayload + /// Filters for the search. + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchTool/filters`. + public struct FiltersPayload: Codable, Hashable, Sendable { + public typealias String = [Swift.String] + /// - Remark: Generated from `#/components/schemas/WebSearchTool/filters/allowed_domains`. + public var allowedDomains: [Swift.String]? + /// Creates a new `FiltersPayload`. + /// + /// - Parameters: + /// - allowedDomains: + public init(allowedDomains: [Swift.String]? = nil) { + self.allowedDomains = allowedDomains + } + public enum CodingKeys: String, CodingKey { + case allowedDomains = "allowed_domains" + } + } + /// - Remark: Generated from `#/components/schemas/WebSearchTool/filters`. + public var filters: Components.Schemas.WebSearchTool.FiltersPayload? + /// - Remark: Generated from `#/components/schemas/WebSearchTool/user_location`. + public var userLocation: Components.Schemas.WebSearchApproximateLocation? + /// 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. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchTool/search_context_size`. + @frozen public enum SearchContextSizePayload: String, Codable, Hashable, Sendable, CaseIterable { + case low = "low" + case medium = "medium" + case high = "high" + } + /// 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. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchTool/search_context_size`. + public var searchContextSize: Components.Schemas.WebSearchTool.SearchContextSizePayload? + /// Creates a new `WebSearchTool`. + /// + /// - Parameters: + /// - _type: The type of the web search tool. One of `web_search` or `web_search_2025_08_26`. + /// - filters: + /// - 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( + _type: Components.Schemas.WebSearchTool._TypePayload, + filters: Components.Schemas.WebSearchTool.FiltersPayload? = nil, + userLocation: Components.Schemas.WebSearchApproximateLocation? = nil, + searchContextSize: Components.Schemas.WebSearchTool.SearchContextSizePayload? = nil + ) { + self._type = _type + self.filters = filters + self.userLocation = userLocation + self.searchContextSize = searchContextSize + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case filters + case userLocation = "user_location" + case searchContextSize = "search_context_size" + } + } /// The results of a web search tool call. See the /// [web search guide](/docs/guides/tools-web-search) for more information. /// @@ -10564,1301 +11997,4612 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/WebSearchToolCall/status`. public var status: Components.Schemas.WebSearchToolCall.StatusPayload + /// An object describing the specific action taken in this web search call. + /// Includes details on how the model used the web (search, open_page, find_in_page). + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchToolCall/action`. + @frozen public enum ActionPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/WebSearchToolCall/action/WebSearchActionSearch`. + case webSearchActionSearch(Components.Schemas.WebSearchActionSearch) + /// - Remark: Generated from `#/components/schemas/WebSearchToolCall/action/WebSearchActionOpenPage`. + case webSearchActionOpenPage(Components.Schemas.WebSearchActionOpenPage) + /// - Remark: Generated from `#/components/schemas/WebSearchToolCall/action/WebSearchActionFind`. + case webSearchActionFind(Components.Schemas.WebSearchActionFind) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "WebSearchActionSearch", "#/components/schemas/WebSearchActionSearch": + self = .webSearchActionSearch(try .init(from: decoder)) + case "WebSearchActionOpenPage", "#/components/schemas/WebSearchActionOpenPage": + self = .webSearchActionOpenPage(try .init(from: decoder)) + case "WebSearchActionFind", "#/components/schemas/WebSearchActionFind": + self = .webSearchActionFind(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .webSearchActionSearch(value): + try value.encode(to: encoder) + case let .webSearchActionOpenPage(value): + try value.encode(to: encoder) + case let .webSearchActionFind(value): + try value.encode(to: encoder) + } + } + } + /// An object describing the specific action taken in this web search call. + /// Includes details on how the model used the web (search, open_page, find_in_page). + /// + /// + /// - Remark: Generated from `#/components/schemas/WebSearchToolCall/action`. + public var action: Components.Schemas.WebSearchToolCall.ActionPayload /// Creates a new `WebSearchToolCall`. /// /// - Parameters: /// - id: The unique ID of the web search tool call. /// - _type: The type of the web search tool call. Always `web_search_call`. /// - status: The status of the web search tool call. + /// - action: An object describing the specific action taken in this web search call. public init( id: Swift.String, _type: Components.Schemas.WebSearchToolCall._TypePayload, - status: Components.Schemas.WebSearchToolCall.StatusPayload + status: Components.Schemas.WebSearchToolCall.StatusPayload, + action: Components.Schemas.WebSearchToolCall.ActionPayload ) { self.id = id self._type = _type self.status = status + self.action = action } public enum CodingKeys: String, CodingKey { case id case _type = "type" case status + case action } } - /// A text input to the model. - /// - /// - Remark: Generated from `#/components/schemas/InputTextContent`. - public struct InputTextContent: Codable, Hashable, Sendable { - /// The type of the input item. Always `input_text`. + /// - Remark: Generated from `#/components/schemas/SkillReferenceParam`. + public struct SkillReferenceParam: Codable, Hashable, Sendable { + /// References a skill created with the /v1/skills endpoint. /// - /// - Remark: Generated from `#/components/schemas/InputTextContent/type`. + /// - Remark: Generated from `#/components/schemas/SkillReferenceParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case inputText = "input_text" + case skillReference = "skill_reference" } - /// The type of the input item. Always `input_text`. + /// References a skill created with the /v1/skills endpoint. /// - /// - Remark: Generated from `#/components/schemas/InputTextContent/type`. - public var _type: Components.Schemas.InputTextContent._TypePayload - /// The text input to the model. + /// - Remark: Generated from `#/components/schemas/SkillReferenceParam/type`. + public var _type: Components.Schemas.SkillReferenceParam._TypePayload + /// The ID of the referenced skill. /// - /// - Remark: Generated from `#/components/schemas/InputTextContent/text`. - public var text: Swift.String - /// Creates a new `InputTextContent`. + /// - Remark: Generated from `#/components/schemas/SkillReferenceParam/skill_id`. + public var skillId: Swift.String + /// Optional skill version. Use a positive integer or 'latest'. Omit for default. + /// + /// - Remark: Generated from `#/components/schemas/SkillReferenceParam/version`. + public var version: Swift.String? + /// Creates a new `SkillReferenceParam`. /// /// - Parameters: - /// - _type: The type of the input item. Always `input_text`. - /// - text: The text input to the model. + /// - _type: References a skill created with the /v1/skills endpoint. + /// - skillId: The ID of the referenced skill. + /// - version: Optional skill version. Use a positive integer or 'latest'. Omit for default. public init( - _type: Components.Schemas.InputTextContent._TypePayload, - text: Swift.String + _type: Components.Schemas.SkillReferenceParam._TypePayload, + skillId: Swift.String, + version: Swift.String? = nil ) { self._type = _type - self.text = text + self.skillId = skillId + self.version = version } public enum CodingKeys: String, CodingKey { case _type = "type" - case text + case skillId = "skill_id" + case version } } - /// An image input to the model. Learn about [image inputs](/docs/guides/vision). + /// Inline skill payload /// - /// - Remark: Generated from `#/components/schemas/InputImageContent`. - public struct InputImageContent: Codable, Hashable, Sendable { - /// The type of the input item. Always `input_image`. + /// - Remark: Generated from `#/components/schemas/InlineSkillSourceParam`. + public struct InlineSkillSourceParam: Codable, Hashable, Sendable { + /// The type of the inline skill source. Must be `base64`. /// - /// - Remark: Generated from `#/components/schemas/InputImageContent/type`. + /// - Remark: Generated from `#/components/schemas/InlineSkillSourceParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case inputImage = "input_image" + case base64 = "base64" } - /// The type of the input item. Always `input_image`. + /// The type of the inline skill source. Must be `base64`. /// - /// - Remark: Generated from `#/components/schemas/InputImageContent/type`. - public var _type: Components.Schemas.InputImageContent._TypePayload - /// - Remark: Generated from `#/components/schemas/InputImageContent/image_url`. - public struct ImageUrlPayload: Codable, Hashable, Sendable { - /// 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/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/InputImageContent/image_url/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `ImageUrlPayload`. - /// - /// - Parameters: - /// - value1: The URL of the image to be sent to the model. A fully qualified URL or base64 encoded image in a data URL. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + /// - Remark: Generated from `#/components/schemas/InlineSkillSourceParam/type`. + public var _type: Components.Schemas.InlineSkillSourceParam._TypePayload + /// The media type of the inline skill payload. Must be `application/zip`. + /// + /// - Remark: Generated from `#/components/schemas/InlineSkillSourceParam/media_type`. + @frozen public enum MediaTypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case applicationZip = "application/zip" } - /// - Remark: Generated from `#/components/schemas/InputImageContent/image_url`. - public var imageUrl: Components.Schemas.InputImageContent.ImageUrlPayload? - /// - Remark: Generated from `#/components/schemas/InputImageContent/file_id`. - public struct FileIdPayload: Codable, Hashable, Sendable { - /// The ID of the file to be sent to the model. - /// - /// - Remark: Generated from `#/components/schemas/InputImageContent/file_id/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/InputImageContent/file_id/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `FileIdPayload`. - /// - /// - Parameters: - /// - value1: The ID of the file to be sent to the model. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + /// The media type of the inline skill payload. Must be `application/zip`. + /// + /// - Remark: Generated from `#/components/schemas/InlineSkillSourceParam/media_type`. + public var mediaType: Components.Schemas.InlineSkillSourceParam.MediaTypePayload + /// Base64-encoded skill zip bundle. + /// + /// - Remark: Generated from `#/components/schemas/InlineSkillSourceParam/data`. + public var data: Swift.String + /// Creates a new `InlineSkillSourceParam`. + /// + /// - Parameters: + /// - _type: The type of the inline skill source. Must be `base64`. + /// - mediaType: The media type of the inline skill payload. Must be `application/zip`. + /// - data: Base64-encoded skill zip bundle. + public init( + _type: Components.Schemas.InlineSkillSourceParam._TypePayload, + mediaType: Components.Schemas.InlineSkillSourceParam.MediaTypePayload, + data: Swift.String + ) { + self._type = _type + self.mediaType = mediaType + self.data = data } - /// - Remark: Generated from `#/components/schemas/InputImageContent/file_id`. - public var fileId: Components.Schemas.InputImageContent.FileIdPayload? - /// The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. + public enum CodingKeys: String, CodingKey { + case _type = "type" + case mediaType = "media_type" + case data + } + } + /// - Remark: Generated from `#/components/schemas/InlineSkillParam`. + public struct InlineSkillParam: Codable, Hashable, Sendable { + /// Defines an inline skill for this request. /// - /// - Remark: Generated from `#/components/schemas/InputImageContent/detail`. - @frozen public enum DetailPayload: String, Codable, Hashable, Sendable, CaseIterable { - case low = "low" - case high = "high" - case auto = "auto" + /// - Remark: Generated from `#/components/schemas/InlineSkillParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case inline = "inline" } - /// The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. + /// Defines an inline skill for this request. /// - /// - Remark: Generated from `#/components/schemas/InputImageContent/detail`. - public var detail: Components.Schemas.InputImageContent.DetailPayload - /// Creates a new `InputImageContent`. + /// - Remark: Generated from `#/components/schemas/InlineSkillParam/type`. + public var _type: Components.Schemas.InlineSkillParam._TypePayload + /// The name of the skill. + /// + /// - Remark: Generated from `#/components/schemas/InlineSkillParam/name`. + public var name: Swift.String + /// The description of the skill. + /// + /// - Remark: Generated from `#/components/schemas/InlineSkillParam/description`. + public var description: Swift.String + /// Inline skill payload + /// + /// - Remark: Generated from `#/components/schemas/InlineSkillParam/source`. + public var source: Components.Schemas.InlineSkillSourceParam + /// Creates a new `InlineSkillParam`. /// /// - Parameters: - /// - _type: The type of the input item. Always `input_image`. - /// - imageUrl: - /// - fileId: - /// - detail: The detail level of the image to be sent to the model. One of `high`, `low`, or `auto`. Defaults to `auto`. + /// - _type: Defines an inline skill for this request. + /// - name: The name of the skill. + /// - description: The description of the skill. + /// - source: Inline skill payload public init( - _type: Components.Schemas.InputImageContent._TypePayload, - imageUrl: Components.Schemas.InputImageContent.ImageUrlPayload? = nil, - fileId: Components.Schemas.InputImageContent.FileIdPayload? = nil, - detail: Components.Schemas.InputImageContent.DetailPayload + _type: Components.Schemas.InlineSkillParam._TypePayload, + name: Swift.String, + description: Swift.String, + source: Components.Schemas.InlineSkillSourceParam ) { self._type = _type - self.imageUrl = imageUrl - self.fileId = fileId - self.detail = detail + self.name = name + self.description = description + self.source = source } public enum CodingKeys: String, CodingKey { case _type = "type" - case imageUrl = "image_url" - case fileId = "file_id" - case detail + case name + case description + case source } } - /// A file input to the model. - /// - /// - Remark: Generated from `#/components/schemas/InputFileContent`. - public struct InputFileContent: Codable, Hashable, Sendable { - /// The type of the input item. Always `input_file`. + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyDisabledParam`. + public struct ContainerNetworkPolicyDisabledParam: Codable, Hashable, Sendable { + /// Disable outbound network access. Always `disabled`. /// - /// - Remark: Generated from `#/components/schemas/InputFileContent/type`. + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyDisabledParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case inputFile = "input_file" + case disabled = "disabled" } - /// The type of the input item. Always `input_file`. + /// Disable outbound network access. Always `disabled`. /// - /// - Remark: Generated from `#/components/schemas/InputFileContent/type`. - public var _type: Components.Schemas.InputFileContent._TypePayload - /// - Remark: Generated from `#/components/schemas/InputFileContent/file_id`. - public struct FileIdPayload: Codable, Hashable, Sendable { - /// The ID of the file to be sent to the model. - /// - /// - Remark: Generated from `#/components/schemas/InputFileContent/file_id/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/InputFileContent/file_id/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `FileIdPayload`. - /// - /// - Parameters: - /// - value1: The ID of the file to be sent to the model. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyDisabledParam/type`. + public var _type: Components.Schemas.ContainerNetworkPolicyDisabledParam._TypePayload + /// Creates a new `ContainerNetworkPolicyDisabledParam`. + /// + /// - Parameters: + /// - _type: Disable outbound network access. Always `disabled`. + public init(_type: Components.Schemas.ContainerNetworkPolicyDisabledParam._TypePayload) { + self._type = _type } - /// - Remark: Generated from `#/components/schemas/InputFileContent/file_id`. - public var fileId: Components.Schemas.InputFileContent.FileIdPayload? - /// The name of the file to be sent to the model. + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyDomainSecretParam`. + public struct ContainerNetworkPolicyDomainSecretParam: Codable, Hashable, Sendable { + /// The domain associated with the secret. /// - /// - Remark: Generated from `#/components/schemas/InputFileContent/filename`. - public var filename: Swift.String? - /// The content of the file to be sent to the model. + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyDomainSecretParam/domain`. + public var domain: Swift.String + /// The name of the secret to inject for the domain. /// + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyDomainSecretParam/name`. + public var name: Swift.String + /// The secret value to inject for the domain. /// - /// - Remark: Generated from `#/components/schemas/InputFileContent/file_data`. - public var fileData: Swift.String? - /// Creates a new `InputFileContent`. + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyDomainSecretParam/value`. + public var value: Swift.String + /// Creates a new `ContainerNetworkPolicyDomainSecretParam`. /// /// - Parameters: - /// - _type: The type of the input item. Always `input_file`. - /// - fileId: - /// - filename: The name of the file to be sent to the model. - /// - fileData: The content of the file to be sent to the model. + /// - domain: The domain associated with the secret. + /// - name: The name of the secret to inject for the domain. + /// - value: The secret value to inject for the domain. public init( - _type: Components.Schemas.InputFileContent._TypePayload, - fileId: Components.Schemas.InputFileContent.FileIdPayload? = nil, - filename: Swift.String? = nil, - fileData: Swift.String? = nil + domain: Swift.String, + name: Swift.String, + value: Swift.String + ) { + self.domain = domain + self.name = name + self.value = value + } + public enum CodingKeys: String, CodingKey { + case domain + case name + case value + } + } + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyAllowlistParam`. + public struct ContainerNetworkPolicyAllowlistParam: Codable, Hashable, Sendable { + /// Allow outbound network access only to specified domains. Always `allowlist`. + /// + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyAllowlistParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case allowlist = "allowlist" + } + /// Allow outbound network access only to specified domains. Always `allowlist`. + /// + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyAllowlistParam/type`. + public var _type: Components.Schemas.ContainerNetworkPolicyAllowlistParam._TypePayload + /// A list of allowed domains when type is `allowlist`. + /// + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyAllowlistParam/allowed_domains`. + public var allowedDomains: [Swift.String] + /// Optional domain-scoped secrets for allowlisted domains. + /// + /// - Remark: Generated from `#/components/schemas/ContainerNetworkPolicyAllowlistParam/domain_secrets`. + public var domainSecrets: [Components.Schemas.ContainerNetworkPolicyDomainSecretParam]? + /// Creates a new `ContainerNetworkPolicyAllowlistParam`. + /// + /// - Parameters: + /// - _type: Allow outbound network access only to specified domains. Always `allowlist`. + /// - allowedDomains: A list of allowed domains when type is `allowlist`. + /// - domainSecrets: Optional domain-scoped secrets for allowlisted domains. + public init( + _type: Components.Schemas.ContainerNetworkPolicyAllowlistParam._TypePayload, + allowedDomains: [Swift.String], + domainSecrets: [Components.Schemas.ContainerNetworkPolicyDomainSecretParam]? = nil ) { self._type = _type - self.fileId = fileId - self.filename = filename - self.fileData = fileData + self.allowedDomains = allowedDomains + self.domainSecrets = domainSecrets } public enum CodingKeys: String, CodingKey { case _type = "type" - case fileId = "file_id" - case filename - case fileData = "file_data" + case allowedDomains = "allowed_domains" + case domainSecrets = "domain_secrets" } } - /// Defines a function in your own code the model can choose to call. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling). + /// 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/FunctionTool`. - public struct FunctionTool: Codable, Hashable, Sendable { - /// The type of the function tool. Always `function`. + /// - Remark: Generated from `#/components/schemas/IncludeEnum`. + @frozen public enum IncludeEnum: String, Codable, Hashable, Sendable, CaseIterable { + case fileSearchCall_results = "file_search_call.results" + case webSearchCall_results = "web_search_call.results" + case webSearchCall_action_sources = "web_search_call.action.sources" + case message_inputImage_imageUrl = "message.input_image.image_url" + case computerCallOutput_output_imageUrl = "computer_call_output.output.image_url" + case codeInterpreterCall_outputs = "code_interpreter_call.outputs" + case reasoning_encryptedContent = "reasoning.encrypted_content" + case message_outputText_logprobs = "message.output_text.logprobs" + } + /// A text input to the model. + /// + /// - Remark: Generated from `#/components/schemas/InputTextContent`. + public struct InputTextContent: Codable, Hashable, Sendable { + /// The type of the input item. Always `input_text`. /// - /// - Remark: Generated from `#/components/schemas/FunctionTool/type`. + /// - Remark: Generated from `#/components/schemas/InputTextContent/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case function = "function" + case inputText = "input_text" } - /// The type of the function tool. Always `function`. + /// The type of the input item. Always `input_text`. /// - /// - Remark: Generated from `#/components/schemas/FunctionTool/type`. - public var _type: Components.Schemas.FunctionTool._TypePayload - /// The name of the function to call. + /// - Remark: Generated from `#/components/schemas/InputTextContent/type`. + public var _type: Components.Schemas.InputTextContent._TypePayload + /// The text input to the model. /// - /// - Remark: Generated from `#/components/schemas/FunctionTool/name`. - public var name: Swift.String - /// - Remark: Generated from `#/components/schemas/FunctionTool/description`. - public struct DescriptionPayload: Codable, Hashable, Sendable { - /// 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/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/FunctionTool/description/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `DescriptionPayload`. - /// - /// - Parameters: - /// - value1: A description of the function. Used by the model to determine whether or not to call the function. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/FunctionTool/description`. - public var description: Components.Schemas.FunctionTool.DescriptionPayload? - /// - Remark: Generated from `#/components/schemas/FunctionTool/parameters`. - public struct ParametersPayload: Codable, Hashable, Sendable { - /// A JSON schema object describing the parameters of the function. - /// - /// - Remark: Generated from `#/components/schemas/FunctionTool/parameters/value1`. - public struct Value1Payload: Codable, Hashable, Sendable { - /// A container of undocumented properties. - public var additionalProperties: [String: OpenAPIRuntime.OpenAPIValueContainer] - /// Creates a new `Value1Payload`. - /// - /// - Parameters: - /// - additionalProperties: A container of undocumented properties. - public init(additionalProperties: [String: OpenAPIRuntime.OpenAPIValueContainer] = .init()) { - self.additionalProperties = additionalProperties - } - public init(from decoder: any Decoder) throws { - additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeAdditionalProperties(additionalProperties) - } - } - /// A JSON schema object describing the parameters of the function. - /// - /// - Remark: Generated from `#/components/schemas/FunctionTool/parameters/value1`. - public var value1: Components.Schemas.FunctionTool.ParametersPayload.Value1Payload? - /// - Remark: Generated from `#/components/schemas/FunctionTool/parameters/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `ParametersPayload`. - /// - /// - Parameters: - /// - value1: A JSON schema object describing the parameters of the function. - /// - value2: - public init( - value1: Components.Schemas.FunctionTool.ParametersPayload.Value1Payload? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try self.value1?.encode(to: encoder) - try self.value2?.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/FunctionTool/parameters`. - public var parameters: Components.Schemas.FunctionTool.ParametersPayload - /// - Remark: Generated from `#/components/schemas/FunctionTool/strict`. - public struct StrictPayload: Codable, Hashable, Sendable { - /// Whether to enforce strict parameter validation. Default `true`. - /// - /// - Remark: Generated from `#/components/schemas/FunctionTool/strict/value1`. - public var value1: Swift.Bool? - /// - Remark: Generated from `#/components/schemas/FunctionTool/strict/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `StrictPayload`. - /// - /// - Parameters: - /// - value1: Whether to enforce strict parameter validation. Default `true`. - /// - value2: - public init( - value1: Swift.Bool? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/FunctionTool/strict`. - public var strict: Components.Schemas.FunctionTool.StrictPayload - /// Creates a new `FunctionTool`. + /// - Remark: Generated from `#/components/schemas/InputTextContent/text`. + public var text: Swift.String + /// Creates a new `InputTextContent`. /// /// - Parameters: - /// - _type: The type of the function tool. Always `function`. - /// - name: The name of the function to call. - /// - description: - /// - parameters: - /// - strict: + /// - _type: The type of the input item. Always `input_text`. + /// - text: The text input to the model. public init( - _type: Components.Schemas.FunctionTool._TypePayload, - name: Swift.String, - description: Components.Schemas.FunctionTool.DescriptionPayload? = nil, - parameters: Components.Schemas.FunctionTool.ParametersPayload, - strict: Components.Schemas.FunctionTool.StrictPayload + _type: Components.Schemas.InputTextContent._TypePayload, + text: Swift.String ) { self._type = _type - self.name = name - self.description = description - self.parameters = parameters - self.strict = strict + self.text = text } public enum CodingKeys: String, CodingKey { case _type = "type" - case name - case description - case parameters - case strict + case text } } - /// - Remark: Generated from `#/components/schemas/RankingOptions`. - public struct RankingOptions: Codable, Hashable, Sendable { - /// The ranker to use for the file search. + /// A citation to a file. + /// + /// - Remark: Generated from `#/components/schemas/FileCitationBody`. + public struct FileCitationBody: Codable, Hashable, Sendable { + /// The type of the file citation. Always `file_citation`. /// - /// - Remark: Generated from `#/components/schemas/RankingOptions/ranker`. - @frozen public enum RankerPayload: String, Codable, Hashable, Sendable, CaseIterable { - case auto = "auto" - case default20241115 = "default-2024-11-15" + /// - Remark: Generated from `#/components/schemas/FileCitationBody/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case fileCitation = "file_citation" } - /// The ranker to use for the file search. + /// The type of the file citation. Always `file_citation`. /// - /// - Remark: Generated from `#/components/schemas/RankingOptions/ranker`. - public var ranker: Components.Schemas.RankingOptions.RankerPayload? - /// The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results. + /// - Remark: Generated from `#/components/schemas/FileCitationBody/type`. + public var _type: Components.Schemas.FileCitationBody._TypePayload + /// The ID of the file. /// - /// - Remark: Generated from `#/components/schemas/RankingOptions/score_threshold`. - public var scoreThreshold: Swift.Double? - /// Creates a new `RankingOptions`. + /// - Remark: Generated from `#/components/schemas/FileCitationBody/file_id`. + public var fileId: Swift.String + /// The index of the file in the list of files. + /// + /// - Remark: Generated from `#/components/schemas/FileCitationBody/index`. + public var index: Swift.Int + /// The filename of the file cited. + /// + /// - Remark: Generated from `#/components/schemas/FileCitationBody/filename`. + public var filename: Swift.String + /// Creates a new `FileCitationBody`. /// /// - Parameters: - /// - ranker: The ranker to use for the file search. - /// - scoreThreshold: The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results. + /// - _type: The type of the file citation. Always `file_citation`. + /// - fileId: The ID of the file. + /// - index: The index of the file in the list of files. + /// - filename: The filename of the file cited. public init( - ranker: Components.Schemas.RankingOptions.RankerPayload? = nil, - scoreThreshold: Swift.Double? = nil + _type: Components.Schemas.FileCitationBody._TypePayload, + fileId: Swift.String, + index: Swift.Int, + filename: Swift.String ) { - self.ranker = ranker - self.scoreThreshold = scoreThreshold + self._type = _type + self.fileId = fileId + self.index = index + self.filename = filename } public enum CodingKeys: String, CodingKey { - case ranker - case scoreThreshold = "score_threshold" + case _type = "type" + case fileId = "file_id" + case index + case filename } } - /// - Remark: Generated from `#/components/schemas/Filters`. - public struct Filters: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/Filters/value1`. - public var value1: Components.Schemas.ComparisonFilter? - /// - Remark: Generated from `#/components/schemas/Filters/value2`. - public var value2: Components.Schemas.CompoundFilter? - /// Creates a new `Filters`. + /// A citation for a web resource used to generate a model response. + /// + /// - Remark: Generated from `#/components/schemas/UrlCitationBody`. + public struct UrlCitationBody: Codable, Hashable, Sendable { + /// The type of the URL citation. Always `url_citation`. + /// + /// - Remark: Generated from `#/components/schemas/UrlCitationBody/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case urlCitation = "url_citation" + } + /// The type of the URL citation. Always `url_citation`. + /// + /// - Remark: Generated from `#/components/schemas/UrlCitationBody/type`. + public var _type: Components.Schemas.UrlCitationBody._TypePayload + /// The URL of the web resource. + /// + /// - Remark: Generated from `#/components/schemas/UrlCitationBody/url`. + public var url: Swift.String + /// The index of the first character of the URL citation in the message. + /// + /// - Remark: Generated from `#/components/schemas/UrlCitationBody/start_index`. + public var startIndex: Swift.Int + /// The index of the last character of the URL citation in the message. + /// + /// - Remark: Generated from `#/components/schemas/UrlCitationBody/end_index`. + public var endIndex: Swift.Int + /// The title of the web resource. + /// + /// - Remark: Generated from `#/components/schemas/UrlCitationBody/title`. + public var title: Swift.String + /// Creates a new `UrlCitationBody`. /// /// - Parameters: - /// - value1: - /// - value2: + /// - _type: The type of the URL citation. Always `url_citation`. + /// - url: The URL of the web resource. + /// - startIndex: The index of the first character of the URL citation in the message. + /// - endIndex: The index of the last character of the URL citation in the message. + /// - title: The title of the web resource. public init( - value1: Components.Schemas.ComparisonFilter? = nil, - value2: Components.Schemas.CompoundFilter? = nil + _type: Components.Schemas.UrlCitationBody._TypePayload, + url: Swift.String, + startIndex: Swift.Int, + endIndex: Swift.Int, + title: Swift.String ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try .init(from: decoder) - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) + self._type = _type + self.url = url + self.startIndex = startIndex + self.endIndex = endIndex + self.title = title } - public func encode(to encoder: any Encoder) throws { - try self.value1?.encode(to: encoder) - try self.value2?.encode(to: encoder) + public enum CodingKeys: String, CodingKey { + case _type = "type" + case url + case startIndex = "start_index" + case endIndex = "end_index" + case title } } - /// A tool that searches for relevant content from uploaded files. Learn more about the [file search tool](https://platform.openai.com/docs/guides/tools-file-search). + /// A citation for a container file used to generate a model response. /// - /// - Remark: Generated from `#/components/schemas/FileSearchTool`. - public struct FileSearchTool: Codable, Hashable, Sendable { - /// The type of the file search tool. Always `file_search`. + /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody`. + public struct ContainerFileCitationBody: Codable, Hashable, Sendable { + /// The type of the container file citation. Always `container_file_citation`. /// - /// - Remark: Generated from `#/components/schemas/FileSearchTool/type`. + /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case fileSearch = "file_search" + case containerFileCitation = "container_file_citation" } - /// The type of the file search tool. Always `file_search`. + /// The type of the container file citation. Always `container_file_citation`. /// - /// - Remark: Generated from `#/components/schemas/FileSearchTool/type`. - public var _type: Components.Schemas.FileSearchTool._TypePayload - /// The IDs of the vector stores to search. + /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/type`. + public var _type: Components.Schemas.ContainerFileCitationBody._TypePayload + /// The ID of the container file. /// - /// - Remark: Generated from `#/components/schemas/FileSearchTool/vector_store_ids`. - public var vectorStoreIds: [Swift.String] - /// The maximum number of results to return. This number should be between 1 and 50 inclusive. + /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/container_id`. + public var containerId: Swift.String + /// The ID of the file. + /// + /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/file_id`. + public var fileId: Swift.String + /// The index of the first character of the container file citation in the message. + /// + /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/start_index`. + public var startIndex: Swift.Int + /// The index of the last character of the container file citation in the message. + /// + /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/end_index`. + public var endIndex: Swift.Int + /// The filename of the container file cited. + /// + /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/filename`. + public var filename: Swift.String + /// Creates a new `ContainerFileCitationBody`. + /// + /// - Parameters: + /// - _type: The type of the container file citation. Always `container_file_citation`. + /// - containerId: The ID of the container file. + /// - fileId: The ID of the file. + /// - startIndex: The index of the first character of the container file citation in the message. + /// - endIndex: The index of the last character of the container file citation in the message. + /// - filename: The filename of the container file cited. + public init( + _type: Components.Schemas.ContainerFileCitationBody._TypePayload, + containerId: Swift.String, + fileId: Swift.String, + startIndex: Swift.Int, + endIndex: Swift.Int, + filename: Swift.String + ) { + self._type = _type + self.containerId = containerId + self.fileId = fileId + self.startIndex = startIndex + self.endIndex = endIndex + self.filename = filename + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case containerId = "container_id" + case fileId = "file_id" + case startIndex = "start_index" + case endIndex = "end_index" + case filename + } + } + /// An annotation that applies to a span of output text. + /// + /// - Remark: Generated from `#/components/schemas/Annotation`. + @frozen public enum Annotation: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/Annotation/FileCitationBody`. + case fileCitationBody(Components.Schemas.FileCitationBody) + /// - Remark: Generated from `#/components/schemas/Annotation/UrlCitationBody`. + case urlCitationBody(Components.Schemas.UrlCitationBody) + /// - Remark: Generated from `#/components/schemas/Annotation/ContainerFileCitationBody`. + case containerFileCitationBody(Components.Schemas.ContainerFileCitationBody) + /// - Remark: Generated from `#/components/schemas/Annotation/FilePath`. + case filePath(Components.Schemas.FilePath) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "FileCitationBody", "#/components/schemas/FileCitationBody": + self = .fileCitationBody(try .init(from: decoder)) + case "UrlCitationBody", "#/components/schemas/UrlCitationBody": + self = .urlCitationBody(try .init(from: decoder)) + case "ContainerFileCitationBody", "#/components/schemas/ContainerFileCitationBody": + self = .containerFileCitationBody(try .init(from: decoder)) + case "FilePath", "#/components/schemas/FilePath": + self = .filePath(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .fileCitationBody(value): + try value.encode(to: encoder) + case let .urlCitationBody(value): + try value.encode(to: encoder) + case let .containerFileCitationBody(value): + try value.encode(to: encoder) + case let .filePath(value): + try value.encode(to: encoder) + } + } + } + /// The top log probability of a token. + /// + /// - Remark: Generated from `#/components/schemas/TopLogProb`. + public struct TopLogProb: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/TopLogProb/token`. + public var token: Swift.String + /// - Remark: Generated from `#/components/schemas/TopLogProb/logprob`. + public var logprob: Swift.Double + /// - Remark: Generated from `#/components/schemas/TopLogProb/bytes`. + public var bytes: [Swift.Int] + /// Creates a new `TopLogProb`. + /// + /// - Parameters: + /// - token: + /// - logprob: + /// - bytes: + public init( + token: Swift.String, + logprob: Swift.Double, + bytes: [Swift.Int] + ) { + self.token = token + self.logprob = logprob + self.bytes = bytes + } + public enum CodingKeys: String, CodingKey { + case token + case logprob + case bytes + } + } + /// The log probability of a token. + /// + /// - Remark: Generated from `#/components/schemas/LogProb`. + public struct LogProb: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/LogProb/token`. + public var token: Swift.String + /// - Remark: Generated from `#/components/schemas/LogProb/logprob`. + public var logprob: Swift.Double + /// - Remark: Generated from `#/components/schemas/LogProb/bytes`. + public var bytes: [Swift.Int] + /// - Remark: Generated from `#/components/schemas/LogProb/top_logprobs`. + public var topLogprobs: [Components.Schemas.TopLogProb] + /// Creates a new `LogProb`. + /// + /// - Parameters: + /// - token: + /// - logprob: + /// - bytes: + /// - topLogprobs: + public init( + token: Swift.String, + logprob: Swift.Double, + bytes: [Swift.Int], + topLogprobs: [Components.Schemas.TopLogProb] + ) { + self.token = token + self.logprob = logprob + self.bytes = bytes + self.topLogprobs = topLogprobs + } + public enum CodingKeys: String, CodingKey { + case token + case logprob + case bytes + case topLogprobs = "top_logprobs" + } + } + /// A text output from the model. + /// + /// - Remark: Generated from `#/components/schemas/OutputTextContent`. + public struct OutputTextContent: Codable, Hashable, Sendable { + /// The type of the output text. Always `output_text`. + /// + /// - Remark: Generated from `#/components/schemas/OutputTextContent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case outputText = "output_text" + } + /// The type of the output text. Always `output_text`. + /// + /// - Remark: Generated from `#/components/schemas/OutputTextContent/type`. + public var _type: Components.Schemas.OutputTextContent._TypePayload + /// The text output from the model. + /// + /// - Remark: Generated from `#/components/schemas/OutputTextContent/text`. + public var text: Swift.String + /// The annotations of the text output. + /// + /// - Remark: Generated from `#/components/schemas/OutputTextContent/annotations`. + public var annotations: [Components.Schemas.Annotation] + /// - Remark: Generated from `#/components/schemas/OutputTextContent/logprobs`. + public var logprobs: [Components.Schemas.LogProb] + /// Creates a new `OutputTextContent`. + /// + /// - Parameters: + /// - _type: The type of the output text. Always `output_text`. + /// - text: The text output from the model. + /// - annotations: The annotations of the text output. + /// - logprobs: + public init( + _type: Components.Schemas.OutputTextContent._TypePayload, + text: Swift.String, + annotations: [Components.Schemas.Annotation], + logprobs: [Components.Schemas.LogProb] + ) { + self._type = _type + self.text = text + self.annotations = annotations + self.logprobs = logprobs + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case text + case annotations + case logprobs + } + } + /// A summary text from the model. + /// + /// - Remark: Generated from `#/components/schemas/SummaryTextContent`. + public struct SummaryTextContent: Codable, Hashable, Sendable { + /// The type of the object. Always `summary_text`. + /// + /// - Remark: Generated from `#/components/schemas/SummaryTextContent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case summaryText = "summary_text" + } + /// The type of the object. Always `summary_text`. + /// + /// - Remark: Generated from `#/components/schemas/SummaryTextContent/type`. + public var _type: Components.Schemas.SummaryTextContent._TypePayload + /// A summary of the reasoning output from the model so far. + /// + /// - Remark: Generated from `#/components/schemas/SummaryTextContent/text`. + public var text: Swift.String + /// Creates a new `SummaryTextContent`. + /// + /// - Parameters: + /// - _type: The type of the object. Always `summary_text`. + /// - text: A summary of the reasoning output from the model so far. + public init( + _type: Components.Schemas.SummaryTextContent._TypePayload, + text: Swift.String + ) { + self._type = _type + self.text = text + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case text + } + } + /// Reasoning text from the model. + /// + /// - Remark: Generated from `#/components/schemas/ReasoningTextContent`. + public struct ReasoningTextContent: Codable, Hashable, Sendable { + /// The type of the reasoning text. Always `reasoning_text`. + /// + /// - Remark: Generated from `#/components/schemas/ReasoningTextContent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case reasoningText = "reasoning_text" + } + /// The type of the reasoning text. Always `reasoning_text`. + /// + /// - Remark: Generated from `#/components/schemas/ReasoningTextContent/type`. + public var _type: Components.Schemas.ReasoningTextContent._TypePayload + /// The reasoning text from the model. + /// + /// - Remark: Generated from `#/components/schemas/ReasoningTextContent/text`. + public var text: Swift.String + /// Creates a new `ReasoningTextContent`. + /// + /// - Parameters: + /// - _type: The type of the reasoning text. Always `reasoning_text`. + /// - text: The reasoning text from the model. + public init( + _type: Components.Schemas.ReasoningTextContent._TypePayload, + text: Swift.String + ) { + self._type = _type + self.text = text + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case text + } + } + /// A refusal from the model. + /// + /// - Remark: Generated from `#/components/schemas/RefusalContent`. + public struct RefusalContent: Codable, Hashable, Sendable { + /// The type of the refusal. Always `refusal`. + /// + /// - Remark: Generated from `#/components/schemas/RefusalContent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case refusal = "refusal" + } + /// The type of the refusal. Always `refusal`. + /// + /// - Remark: Generated from `#/components/schemas/RefusalContent/type`. + public var _type: Components.Schemas.RefusalContent._TypePayload + /// The refusal explanation from the model. + /// + /// - Remark: Generated from `#/components/schemas/RefusalContent/refusal`. + public var refusal: Swift.String + /// Creates a new `RefusalContent`. + /// + /// - Parameters: + /// - _type: The type of the refusal. Always `refusal`. + /// - refusal: The refusal explanation from the model. + public init( + _type: Components.Schemas.RefusalContent._TypePayload, + refusal: Swift.String + ) { + self._type = _type + self.refusal = refusal + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case refusal + } + } + /// - Remark: Generated from `#/components/schemas/ImageDetail`. + @frozen public enum ImageDetail: String, Codable, Hashable, Sendable, CaseIterable { + case low = "low" + case high = "high" + case auto = "auto" + case original = "original" + } + /// An image input to the model. Learn about [image inputs](/docs/guides/vision). + /// + /// - Remark: Generated from `#/components/schemas/InputImageContent`. + public struct InputImageContent: Codable, Hashable, Sendable { + /// The type of the input item. Always `input_image`. + /// + /// - Remark: Generated from `#/components/schemas/InputImageContent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case inputImage = "input_image" + } + /// The type of the input item. Always `input_image`. + /// + /// - Remark: Generated from `#/components/schemas/InputImageContent/type`. + public var _type: Components.Schemas.InputImageContent._TypePayload + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/InputImageContent/image_url`. + public var imageUrl: Swift.String? + public typealias String = Swift.String + /// - 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`. + /// + /// - Remark: Generated from `#/components/schemas/InputImageContent/detail`. + public var detail: Components.Schemas.ImageDetail + /// Creates a new `InputImageContent`. + /// + /// - Parameters: + /// - _type: The type of the input item. Always `input_image`. + /// - imageUrl: + /// - fileId: + /// - 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, + imageUrl: Swift.String? = nil, + fileId: Swift.String? = nil, + detail: Components.Schemas.ImageDetail + ) { + self._type = _type + self.imageUrl = imageUrl + self.fileId = fileId + self.detail = detail + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case imageUrl = "image_url" + case fileId = "file_id" + case detail + } + } + /// - Remark: Generated from `#/components/schemas/FileInputDetail`. + @frozen public enum FileInputDetail: String, Codable, Hashable, Sendable, CaseIterable { + case low = "low" + case high = "high" + } + /// A file input to the model. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContent`. + public struct InputFileContent: Codable, Hashable, Sendable { + /// The type of the input item. Always `input_file`. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContent/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case inputFile = "input_file" + } + /// The type of the input item. Always `input_file`. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContent/type`. + public var _type: Components.Schemas.InputFileContent._TypePayload + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/InputFileContent/file_id`. + public var fileId: Swift.String? + /// The name of the file to be sent to the model. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContent/filename`. + public var filename: Swift.String? + /// The content of the file to be sent to the model. + /// + /// + /// - Remark: Generated from `#/components/schemas/InputFileContent/file_data`. + public var fileData: Swift.String? + /// The URL of the file to be sent to the model. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContent/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`. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContent/detail`. + public var detail: Components.Schemas.FileInputDetail? + /// Creates a new `InputFileContent`. + /// + /// - Parameters: + /// - _type: The type of the input item. Always `input_file`. + /// - fileId: + /// - 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. + /// - 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.InputFileContent._TypePayload, + fileId: Swift.String? = nil, + filename: Swift.String? = nil, + fileData: Swift.String? = nil, + fileUrl: Swift.String? = nil, + detail: Components.Schemas.FileInputDetail? = nil + ) { + self._type = _type + self.fileId = fileId + self.filename = filename + self.fileData = fileData + self.fileUrl = fileUrl + self.detail = detail + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case fileId = "file_id" + case filename + case fileData = "file_data" + case fileUrl = "file_url" + case detail + } + } + /// - Remark: Generated from `#/components/schemas/FunctionCallStatus`. + @frozen public enum FunctionCallStatus: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + case incomplete = "incomplete" + } + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputStatusEnum`. + @frozen public enum FunctionCallOutputStatusEnum: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + case incomplete = "incomplete" + } + /// - Remark: Generated from `#/components/schemas/ClickButtonType`. + @frozen public enum ClickButtonType: String, Codable, Hashable, Sendable, CaseIterable { + case left = "left" + case right = "right" + case wheel = "wheel" + case back = "back" + case forward = "forward" + } + /// A click action. + /// + /// - Remark: Generated from `#/components/schemas/ClickParam`. + public struct ClickParam: Codable, Hashable, Sendable { + /// Specifies the event type. For a click action, this property is always `click`. + /// + /// - Remark: Generated from `#/components/schemas/ClickParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case click = "click" + } + /// Specifies the event type. For a click action, this property is always `click`. + /// + /// - Remark: Generated from `#/components/schemas/ClickParam/type`. + public var _type: Components.Schemas.ClickParam._TypePayload + /// Indicates which mouse button was pressed during the click. One of `left`, `right`, `wheel`, `back`, or `forward`. + /// + /// - Remark: Generated from `#/components/schemas/ClickParam/button`. + public var button: Components.Schemas.ClickButtonType + /// The x-coordinate where the click occurred. + /// + /// - Remark: Generated from `#/components/schemas/ClickParam/x`. + public var x: Swift.Int + /// The y-coordinate where the click occurred. + /// + /// - Remark: Generated from `#/components/schemas/ClickParam/y`. + public var y: Swift.Int + public typealias String = [Swift.String] + /// - Remark: Generated from `#/components/schemas/ClickParam/keys`. + public var keys: [Swift.String]? + /// Creates a new `ClickParam`. + /// + /// - Parameters: + /// - _type: Specifies the event type. For a click action, this property is always `click`. + /// - 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: + public init( + _type: Components.Schemas.ClickParam._TypePayload, + button: Components.Schemas.ClickButtonType, + x: Swift.Int, + y: Swift.Int, + keys: [Swift.String]? = nil + ) { + self._type = _type + self.button = button + self.x = x + self.y = y + self.keys = keys + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case button + case x + case y + case keys + } + } + /// A double click action. + /// + /// - Remark: Generated from `#/components/schemas/DoubleClickAction`. + public struct DoubleClickAction: Codable, Hashable, Sendable { + /// Specifies the event type. For a double click action, this property is always set to `double_click`. + /// + /// - Remark: Generated from `#/components/schemas/DoubleClickAction/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case doubleClick = "double_click" + } + /// Specifies the event type. For a double click action, this property is always set to `double_click`. + /// + /// - Remark: Generated from `#/components/schemas/DoubleClickAction/type`. + public var _type: Components.Schemas.DoubleClickAction._TypePayload + /// The x-coordinate where the double click occurred. + /// + /// - Remark: Generated from `#/components/schemas/DoubleClickAction/x`. + public var x: Swift.Int + /// The y-coordinate where the double click occurred. + /// + /// - Remark: Generated from `#/components/schemas/DoubleClickAction/y`. + public var y: Swift.Int + public typealias String = [Swift.String] + /// - Remark: Generated from `#/components/schemas/DoubleClickAction/keys`. + public var keys: [Swift.String]? + /// Creates a new `DoubleClickAction`. + /// + /// - Parameters: + /// - _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: + public init( + _type: Components.Schemas.DoubleClickAction._TypePayload, + x: Swift.Int, + y: Swift.Int, + keys: [Swift.String]? = nil + ) { + self._type = _type + self.x = x + self.y = y + self.keys = keys + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case x + case y + case keys + } + } + /// An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`. + /// + /// - Remark: Generated from `#/components/schemas/CoordParam`. + public struct CoordParam: Codable, Hashable, Sendable { + /// The x-coordinate. + /// + /// - Remark: Generated from `#/components/schemas/CoordParam/x`. + public var x: Swift.Int + /// The y-coordinate. + /// + /// - Remark: Generated from `#/components/schemas/CoordParam/y`. + public var y: Swift.Int + /// Creates a new `CoordParam`. + /// + /// - Parameters: + /// - x: The x-coordinate. + /// - y: The y-coordinate. + public init( + x: Swift.Int, + y: Swift.Int + ) { + self.x = x + self.y = y + } + public enum CodingKeys: String, CodingKey { + case x + case y + } + } + /// A drag action. + /// + /// - Remark: Generated from `#/components/schemas/DragParam`. + public struct DragParam: Codable, Hashable, Sendable { + /// Specifies the event type. For a drag action, this property is always set to `drag`. + /// + /// - Remark: Generated from `#/components/schemas/DragParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case drag = "drag" + } + /// Specifies the event type. For a drag action, this property is always set to `drag`. + /// + /// - Remark: Generated from `#/components/schemas/DragParam/type`. + public var _type: Components.Schemas.DragParam._TypePayload + /// An array of coordinates representing the path of the drag action. Coordinates will appear as an array of objects, eg + /// ``` + /// [ + /// { x: 100, y: 200 }, + /// { x: 200, y: 300 } + /// ] + /// ``` + /// + /// - Remark: Generated from `#/components/schemas/DragParam/path`. + public var path: [Components.Schemas.CoordParam] + public typealias String = [Swift.String] + /// - Remark: Generated from `#/components/schemas/DragParam/keys`. + public var keys: [Swift.String]? + /// Creates a new `DragParam`. + /// + /// - 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: + public init( + _type: Components.Schemas.DragParam._TypePayload, + path: [Components.Schemas.CoordParam], + keys: [Swift.String]? = nil + ) { + self._type = _type + self.path = path + self.keys = keys + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case path + case keys + } + } + /// A collection of keypresses the model would like to perform. + /// + /// - Remark: Generated from `#/components/schemas/KeyPressAction`. + public struct KeyPressAction: Codable, Hashable, Sendable { + /// Specifies the event type. For a keypress action, this property is always set to `keypress`. + /// + /// - Remark: Generated from `#/components/schemas/KeyPressAction/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case keypress = "keypress" + } + /// Specifies the event type. For a keypress action, this property is always set to `keypress`. + /// + /// - Remark: Generated from `#/components/schemas/KeyPressAction/type`. + public var _type: Components.Schemas.KeyPressAction._TypePayload + /// The combination of keys the model is requesting to be pressed. This is an array of strings, each representing a key. + /// + /// - Remark: Generated from `#/components/schemas/KeyPressAction/keys`. + public var keys: [Swift.String] + /// Creates a new `KeyPressAction`. + /// + /// - Parameters: + /// - _type: Specifies the event type. For a keypress action, this property is always set to `keypress`. + /// - keys: The combination of keys the model is requesting to be pressed. This is an array of strings, each representing a key. + public init( + _type: Components.Schemas.KeyPressAction._TypePayload, + keys: [Swift.String] + ) { + self._type = _type + self.keys = keys + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case keys + } + } + /// A mouse move action. + /// + /// - Remark: Generated from `#/components/schemas/MoveParam`. + public struct MoveParam: Codable, Hashable, Sendable { + /// Specifies the event type. For a move action, this property is always set to `move`. + /// + /// - Remark: Generated from `#/components/schemas/MoveParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case move = "move" + } + /// Specifies the event type. For a move action, this property is always set to `move`. + /// + /// - Remark: Generated from `#/components/schemas/MoveParam/type`. + public var _type: Components.Schemas.MoveParam._TypePayload + /// The x-coordinate to move to. + /// + /// - Remark: Generated from `#/components/schemas/MoveParam/x`. + public var x: Swift.Int + /// The y-coordinate to move to. + /// + /// - Remark: Generated from `#/components/schemas/MoveParam/y`. + public var y: Swift.Int + public typealias String = [Swift.String] + /// - Remark: Generated from `#/components/schemas/MoveParam/keys`. + public var keys: [Swift.String]? + /// Creates a new `MoveParam`. + /// + /// - Parameters: + /// - _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: + public init( + _type: Components.Schemas.MoveParam._TypePayload, + x: Swift.Int, + y: Swift.Int, + keys: [Swift.String]? = nil + ) { + self._type = _type + self.x = x + self.y = y + self.keys = keys + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case x + case y + case keys + } + } + /// A screenshot action. + /// + /// - Remark: Generated from `#/components/schemas/ScreenshotParam`. + public struct ScreenshotParam: Codable, Hashable, Sendable { + /// Specifies the event type. For a screenshot action, this property is always set to `screenshot`. + /// + /// - Remark: Generated from `#/components/schemas/ScreenshotParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case screenshot = "screenshot" + } + /// Specifies the event type. For a screenshot action, this property is always set to `screenshot`. + /// + /// - Remark: Generated from `#/components/schemas/ScreenshotParam/type`. + public var _type: Components.Schemas.ScreenshotParam._TypePayload + /// Creates a new `ScreenshotParam`. + /// + /// - Parameters: + /// - _type: Specifies the event type. For a screenshot action, this property is always set to `screenshot`. + public init(_type: Components.Schemas.ScreenshotParam._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// A scroll action. + /// + /// - Remark: Generated from `#/components/schemas/ScrollParam`. + public struct ScrollParam: Codable, Hashable, Sendable { + /// Specifies the event type. For a scroll action, this property is always set to `scroll`. + /// + /// - Remark: Generated from `#/components/schemas/ScrollParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case scroll = "scroll" + } + /// Specifies the event type. For a scroll action, this property is always set to `scroll`. + /// + /// - Remark: Generated from `#/components/schemas/ScrollParam/type`. + public var _type: Components.Schemas.ScrollParam._TypePayload + /// The x-coordinate where the scroll occurred. + /// + /// - Remark: Generated from `#/components/schemas/ScrollParam/x`. + public var x: Swift.Int + /// The y-coordinate where the scroll occurred. + /// + /// - Remark: Generated from `#/components/schemas/ScrollParam/y`. + public var y: Swift.Int + /// The horizontal scroll distance. + /// + /// - Remark: Generated from `#/components/schemas/ScrollParam/scroll_x`. + public var scrollX: Swift.Int + /// The vertical scroll distance. + /// + /// - Remark: Generated from `#/components/schemas/ScrollParam/scroll_y`. + public var scrollY: Swift.Int + public typealias String = [Swift.String] + /// - Remark: Generated from `#/components/schemas/ScrollParam/keys`. + public var keys: [Swift.String]? + /// Creates a new `ScrollParam`. + /// + /// - Parameters: + /// - _type: Specifies the event type. For a scroll action, this property is always set to `scroll`. + /// - x: The x-coordinate where the scroll occurred. + /// - y: The y-coordinate where the scroll occurred. + /// - scrollX: The horizontal scroll distance. + /// - scrollY: The vertical scroll distance. + /// - keys: + public init( + _type: Components.Schemas.ScrollParam._TypePayload, + x: Swift.Int, + y: Swift.Int, + scrollX: Swift.Int, + scrollY: Swift.Int, + keys: [Swift.String]? = nil + ) { + self._type = _type + self.x = x + self.y = y + self.scrollX = scrollX + self.scrollY = scrollY + self.keys = keys + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case x + case y + case scrollX = "scroll_x" + case scrollY = "scroll_y" + case keys + } + } + /// An action to type in text. + /// + /// - Remark: Generated from `#/components/schemas/TypeParam`. + public struct TypeParam: Codable, Hashable, Sendable { + /// Specifies the event type. For a type action, this property is always set to `type`. + /// + /// - Remark: Generated from `#/components/schemas/TypeParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case _type = "type" + } + /// Specifies the event type. For a type action, this property is always set to `type`. + /// + /// - Remark: Generated from `#/components/schemas/TypeParam/type`. + public var _type: Components.Schemas.TypeParam._TypePayload + /// The text to type. + /// + /// - Remark: Generated from `#/components/schemas/TypeParam/text`. + public var text: Swift.String + /// Creates a new `TypeParam`. + /// + /// - Parameters: + /// - _type: Specifies the event type. For a type action, this property is always set to `type`. + /// - text: The text to type. + public init( + _type: Components.Schemas.TypeParam._TypePayload, + text: Swift.String + ) { + self._type = _type + self.text = text + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case text + } + } + /// A wait action. + /// + /// - Remark: Generated from `#/components/schemas/WaitParam`. + public struct WaitParam: Codable, Hashable, Sendable { + /// Specifies the event type. For a wait action, this property is always set to `wait`. + /// + /// - Remark: Generated from `#/components/schemas/WaitParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case wait = "wait" + } + /// Specifies the event type. For a wait action, this property is always set to `wait`. + /// + /// - Remark: Generated from `#/components/schemas/WaitParam/type`. + public var _type: Components.Schemas.WaitParam._TypePayload + /// Creates a new `WaitParam`. + /// + /// - Parameters: + /// - _type: Specifies the event type. For a wait action, this property is always set to `wait`. + public init(_type: Components.Schemas.WaitParam._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// A pending safety check for the computer call. + /// + /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam`. + public struct ComputerCallSafetyCheckParam: Codable, Hashable, Sendable { + /// The ID of the pending safety check. + /// + /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/id`. + public var id: Swift.String + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/code`. + public var code: Swift.String? + public typealias String = Swift.String + /// - 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: + public init( + id: Swift.String, + code: Swift.String? = nil, + message: Swift.String? = nil + ) { + self.id = id + self.code = code + self.message = message + } + public enum CodingKeys: String, CodingKey { + case id + case code + case message + } + } + /// - Remark: Generated from `#/components/schemas/ComputerCallOutputStatus`. + @frozen public enum ComputerCallOutputStatus: String, Codable, Hashable, Sendable, CaseIterable { + case completed = "completed" + case incomplete = "incomplete" + case failed = "failed" + } + /// - Remark: Generated from `#/components/schemas/ToolSearchExecutionType`. + @frozen public enum ToolSearchExecutionType: String, Codable, Hashable, Sendable, CaseIterable { + case server = "server" + case client = "client" + } + /// - Remark: Generated from `#/components/schemas/ToolSearchCall`. + public struct ToolSearchCall: Codable, Hashable, Sendable { + /// The type of the item. Always `tool_search_call`. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchCall/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case toolSearchCall = "tool_search_call" + } + /// The type of the item. Always `tool_search_call`. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchCall/type`. + public var _type: Components.Schemas.ToolSearchCall._TypePayload + /// The unique ID of the tool search call item. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchCall/id`. + public var id: Swift.String + public typealias String = Swift.String + /// - 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. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchCall/execution`. + public var execution: Components.Schemas.ToolSearchExecutionType + /// Arguments used for the tool search call. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchCall/arguments`. + public var arguments: OpenAPIRuntime.OpenAPIValueContainer + /// The status of the tool search call item that was recorded. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchCall/status`. + public var status: Components.Schemas.FunctionCallStatus + /// The identifier of the actor that created the item. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchCall/created_by`. + public var createdBy: Swift.String? + /// Creates a new `ToolSearchCall`. + /// + /// - Parameters: + /// - _type: The type of the item. Always `tool_search_call`. + /// - id: The unique ID of the tool search call item. + /// - callId: + /// - 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. + /// - createdBy: The identifier of the actor that created the item. + public init( + _type: Components.Schemas.ToolSearchCall._TypePayload, + id: Swift.String, + callId: Swift.String? = nil, + execution: Components.Schemas.ToolSearchExecutionType, + arguments: OpenAPIRuntime.OpenAPIValueContainer, + status: Components.Schemas.FunctionCallStatus, + createdBy: Swift.String? = nil + ) { + self._type = _type + self.id = id + self.callId = callId + self.execution = execution + self.arguments = arguments + self.status = status + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case id + case callId = "call_id" + case execution + case arguments + case status + case createdBy = "created_by" + } + } + /// Defines a function in your own code the model can choose to call. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling). + /// + /// - Remark: Generated from `#/components/schemas/FunctionTool`. + public struct FunctionTool: Codable, Hashable, Sendable { + /// The type of the function tool. Always `function`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionTool/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case function = "function" + } + /// The type of the function tool. Always `function`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionTool/type`. + public var _type: Components.Schemas.FunctionTool._TypePayload + /// The name of the function to call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionTool/name`. + public var name: Swift.String + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/FunctionTool/description`. + public var description: Swift.String? + /// A JSON schema object describing the parameters of the function. + /// + /// - Remark: Generated from `#/components/schemas/FunctionTool/parameters`. + public struct ParametersPayload: Codable, Hashable, Sendable { + /// A container of undocumented properties. + public var additionalProperties: [String: OpenAPIRuntime.OpenAPIValueContainer] + /// Creates a new `ParametersPayload`. + /// + /// - Parameters: + /// - additionalProperties: A container of undocumented properties. + public init(additionalProperties: [String: OpenAPIRuntime.OpenAPIValueContainer] = .init()) { + self.additionalProperties = additionalProperties + } + public init(from decoder: any Swift.Decoder) throws { + additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) + } + public func encode(to encoder: any Swift.Encoder) throws { + try encoder.encodeAdditionalProperties(additionalProperties) + } + } + /// - Remark: Generated from `#/components/schemas/FunctionTool/parameters`. + public var parameters: Components.Schemas.FunctionTool.ParametersPayload? + public typealias Bool = Swift.Bool + /// - Remark: Generated from `#/components/schemas/FunctionTool/strict`. + public var strict: Swift.Bool? + /// Whether this function is deferred and loaded via tool search. + /// + /// - Remark: Generated from `#/components/schemas/FunctionTool/defer_loading`. + public var deferLoading: Swift.Bool? + /// Creates a new `FunctionTool`. + /// + /// - Parameters: + /// - _type: The type of the function tool. Always `function`. + /// - name: The name of the function to call. + /// - description: + /// - parameters: + /// - strict: + /// - deferLoading: Whether this function is deferred and loaded via tool search. + public init( + _type: Components.Schemas.FunctionTool._TypePayload, + name: Swift.String, + description: Swift.String? = nil, + parameters: Components.Schemas.FunctionTool.ParametersPayload? = nil, + strict: Swift.Bool? = nil, + deferLoading: Swift.Bool? = nil + ) { + self._type = _type + self.name = name + self.description = description + self.parameters = parameters + self.strict = strict + self.deferLoading = deferLoading + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case name + case description + case parameters + case strict + case deferLoading = "defer_loading" + } + } + /// - Remark: Generated from `#/components/schemas/RankerVersionType`. + @frozen public enum RankerVersionType: String, Codable, Hashable, Sendable, CaseIterable { + case auto = "auto" + case default20241115 = "default-2024-11-15" + } + /// - Remark: Generated from `#/components/schemas/HybridSearchOptions`. + public struct HybridSearchOptions: Codable, Hashable, Sendable { + /// The weight of the embedding in the reciprocal ranking fusion. + /// + /// - Remark: Generated from `#/components/schemas/HybridSearchOptions/embedding_weight`. + public var embeddingWeight: Swift.Double + /// The weight of the text in the reciprocal ranking fusion. + /// + /// - Remark: Generated from `#/components/schemas/HybridSearchOptions/text_weight`. + public var textWeight: Swift.Double + /// Creates a new `HybridSearchOptions`. + /// + /// - Parameters: + /// - embeddingWeight: The weight of the embedding in the reciprocal ranking fusion. + /// - textWeight: The weight of the text in the reciprocal ranking fusion. + public init( + embeddingWeight: Swift.Double, + textWeight: Swift.Double + ) { + self.embeddingWeight = embeddingWeight + self.textWeight = textWeight + } + public enum CodingKeys: String, CodingKey { + case embeddingWeight = "embedding_weight" + case textWeight = "text_weight" + } + } + /// - Remark: Generated from `#/components/schemas/RankingOptions`. + public struct RankingOptions: Codable, Hashable, Sendable { + /// The ranker to use for the file search. + /// + /// - Remark: Generated from `#/components/schemas/RankingOptions/ranker`. + public var ranker: Components.Schemas.RankerVersionType? + /// The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results. + /// + /// - Remark: Generated from `#/components/schemas/RankingOptions/score_threshold`. + public var scoreThreshold: Swift.Double? + /// Weights that control how reciprocal rank fusion balances semantic embedding matches versus sparse keyword matches when hybrid search is enabled. + /// + /// - Remark: Generated from `#/components/schemas/RankingOptions/hybrid_search`. + public var hybridSearch: Components.Schemas.HybridSearchOptions? + /// Creates a new `RankingOptions`. + /// + /// - Parameters: + /// - ranker: The ranker to use for the file search. + /// - scoreThreshold: The score threshold for the file search, a number between 0 and 1. Numbers closer to 1 will attempt to return only the most relevant results, but may return fewer results. + /// - hybridSearch: Weights that control how reciprocal rank fusion balances semantic embedding matches versus sparse keyword matches when hybrid search is enabled. + public init( + ranker: Components.Schemas.RankerVersionType? = nil, + scoreThreshold: Swift.Double? = nil, + hybridSearch: Components.Schemas.HybridSearchOptions? = nil + ) { + self.ranker = ranker + self.scoreThreshold = scoreThreshold + self.hybridSearch = hybridSearch + } + public enum CodingKeys: String, CodingKey { + case ranker + case scoreThreshold = "score_threshold" + case hybridSearch = "hybrid_search" + } + } + /// - Remark: Generated from `#/components/schemas/Filters`. + public struct Filters: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/Filters/value1`. + public var value1: Components.Schemas.ComparisonFilter? + /// - Remark: Generated from `#/components/schemas/Filters/value2`. + public var value2: Components.Schemas.CompoundFilter? + /// Creates a new `Filters`. + /// + /// - Parameters: + /// - value1: + /// - value2: + public init( + value1: Components.Schemas.ComparisonFilter? = nil, + value2: Components.Schemas.CompoundFilter? = nil + ) { + self.value1 = value1 + self.value2 = value2 + } + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] + do { + self.value1 = try .init(from: decoder) + } catch { + errors.append(error) + } + do { + self.value2 = try .init(from: decoder) + } catch { + errors.append(error) + } + try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( + [ + self.value1, + self.value2 + ], + type: Self.self, + codingPath: decoder.codingPath, + errors: errors + ) + } + public func encode(to encoder: any Swift.Encoder) throws { + try self.value1?.encode(to: encoder) + try self.value2?.encode(to: encoder) + } + } + /// A tool that searches for relevant content from uploaded files. Learn more about the [file search tool](https://platform.openai.com/docs/guides/tools-file-search). + /// + /// - Remark: Generated from `#/components/schemas/FileSearchTool`. + public struct FileSearchTool: Codable, Hashable, Sendable { + /// The type of the file search tool. Always `file_search`. + /// + /// - Remark: Generated from `#/components/schemas/FileSearchTool/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case fileSearch = "file_search" + } + /// The type of the file search tool. Always `file_search`. + /// + /// - Remark: Generated from `#/components/schemas/FileSearchTool/type`. + public var _type: Components.Schemas.FileSearchTool._TypePayload + /// The IDs of the vector stores to search. + /// + /// - Remark: Generated from `#/components/schemas/FileSearchTool/vector_store_ids`. + public var vectorStoreIds: [Swift.String] + /// The maximum number of results to return. This number should be between 1 and 50 inclusive. /// /// - Remark: Generated from `#/components/schemas/FileSearchTool/max_num_results`. public var maxNumResults: Swift.Int? + /// Ranking options for search. + /// /// - 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 struct FiltersPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/FileSearchTool/filters/value1`. - public var value1: Components.Schemas.Filters? - /// - Remark: Generated from `#/components/schemas/FileSearchTool/filters/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `FiltersPayload`. + public var filters: Components.Schemas.Filters? + /// Creates a new `FileSearchTool`. + /// + /// - Parameters: + /// - _type: The type of the file search tool. Always `file_search`. + /// - vectorStoreIds: The IDs of the vector stores to search. + /// - maxNumResults: The maximum number of results to return. This number should be between 1 and 50 inclusive. + /// - rankingOptions: Ranking options for search. + /// - filters: + public init( + _type: Components.Schemas.FileSearchTool._TypePayload, + vectorStoreIds: [Swift.String], + maxNumResults: Swift.Int? = nil, + rankingOptions: Components.Schemas.RankingOptions? = nil, + filters: Components.Schemas.Filters? = nil + ) { + self._type = _type + self.vectorStoreIds = vectorStoreIds + self.maxNumResults = maxNumResults + self.rankingOptions = rankingOptions + self.filters = filters + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case vectorStoreIds = "vector_store_ids" + case maxNumResults = "max_num_results" + case rankingOptions = "ranking_options" + case filters + } + } + /// A tool that controls a virtual computer. Learn more about the [computer tool](https://platform.openai.com/docs/guides/tools-computer-use). + /// + /// - Remark: Generated from `#/components/schemas/ComputerTool`. + public struct ComputerTool: Codable, Hashable, Sendable { + /// The type of the computer tool. Always `computer`. + /// + /// - Remark: Generated from `#/components/schemas/ComputerTool/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case computer = "computer" + } + /// The type of the computer tool. Always `computer`. + /// + /// - Remark: Generated from `#/components/schemas/ComputerTool/type`. + public var _type: Components.Schemas.ComputerTool._TypePayload + /// Creates a new `ComputerTool`. + /// + /// - Parameters: + /// - _type: The type of the computer tool. Always `computer`. + public init(_type: Components.Schemas.ComputerTool._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// - Remark: Generated from `#/components/schemas/ComputerEnvironment`. + @frozen public enum ComputerEnvironment: String, Codable, Hashable, Sendable, CaseIterable { + case windows = "windows" + case mac = "mac" + case linux = "linux" + case ubuntu = "ubuntu" + case browser = "browser" + } + /// A tool that controls a virtual computer. Learn more about the [computer tool](https://platform.openai.com/docs/guides/tools-computer-use). + /// + /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool`. + public struct ComputerUsePreviewTool: Codable, Hashable, Sendable { + /// The type of the computer use tool. Always `computer_use_preview`. + /// + /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case computerUsePreview = "computer_use_preview" + } + /// The type of the computer use tool. Always `computer_use_preview`. + /// + /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/type`. + public var _type: Components.Schemas.ComputerUsePreviewTool._TypePayload + /// The type of computer environment to control. + /// + /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/environment`. + public var environment: Components.Schemas.ComputerEnvironment + /// The width of the computer display. + /// + /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/display_width`. + public var displayWidth: Swift.Int + /// The height of the computer display. + /// + /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/display_height`. + public var displayHeight: Swift.Int + /// Creates a new `ComputerUsePreviewTool`. + /// + /// - Parameters: + /// - _type: The type of the computer use tool. Always `computer_use_preview`. + /// - environment: The type of computer environment to control. + /// - displayWidth: The width of the computer display. + /// - displayHeight: The height of the computer display. + public init( + _type: Components.Schemas.ComputerUsePreviewTool._TypePayload, + environment: Components.Schemas.ComputerEnvironment, + displayWidth: Swift.Int, + displayHeight: Swift.Int + ) { + self._type = _type + self.environment = environment + self.displayWidth = displayWidth + self.displayHeight = displayHeight + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case environment + case displayWidth = "display_width" + case displayHeight = "display_height" + } + } + /// - Remark: Generated from `#/components/schemas/ContainerMemoryLimit`. + @frozen public enum ContainerMemoryLimit: String, Codable, Hashable, Sendable, CaseIterable { + case _1g = "1g" + case _4g = "4g" + case _16g = "16g" + case _64g = "64g" + } + /// Configuration for a code interpreter container. Optionally specify the IDs of the files to run the code on. + /// + /// - Remark: Generated from `#/components/schemas/AutoCodeInterpreterToolParam`. + public struct AutoCodeInterpreterToolParam: Codable, Hashable, Sendable { + /// Always `auto`. + /// + /// - Remark: Generated from `#/components/schemas/AutoCodeInterpreterToolParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case auto = "auto" + } + /// Always `auto`. + /// + /// - Remark: Generated from `#/components/schemas/AutoCodeInterpreterToolParam/type`. + public var _type: Components.Schemas.AutoCodeInterpreterToolParam._TypePayload + /// An optional list of uploaded files to make available to your code. + /// + /// - 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. + /// + /// - Remark: Generated from `#/components/schemas/AutoCodeInterpreterToolParam/network_policy`. + @frozen public enum NetworkPolicyPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/AutoCodeInterpreterToolParam/network_policy/ContainerNetworkPolicyDisabledParam`. + case containerNetworkPolicyDisabledParam(Components.Schemas.ContainerNetworkPolicyDisabledParam) + /// - Remark: Generated from `#/components/schemas/AutoCodeInterpreterToolParam/network_policy/ContainerNetworkPolicyAllowlistParam`. + case containerNetworkPolicyAllowlistParam(Components.Schemas.ContainerNetworkPolicyAllowlistParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "ContainerNetworkPolicyDisabledParam", "#/components/schemas/ContainerNetworkPolicyDisabledParam": + self = .containerNetworkPolicyDisabledParam(try .init(from: decoder)) + case "ContainerNetworkPolicyAllowlistParam", "#/components/schemas/ContainerNetworkPolicyAllowlistParam": + self = .containerNetworkPolicyAllowlistParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .containerNetworkPolicyDisabledParam(value): + try value.encode(to: encoder) + case let .containerNetworkPolicyAllowlistParam(value): + try value.encode(to: encoder) + } + } + } + /// Network access policy for the container. + /// + /// - Remark: Generated from `#/components/schemas/AutoCodeInterpreterToolParam/network_policy`. + public var networkPolicy: Components.Schemas.AutoCodeInterpreterToolParam.NetworkPolicyPayload? + /// Creates a new `AutoCodeInterpreterToolParam`. + /// + /// - Parameters: + /// - _type: Always `auto`. + /// - fileIds: An optional list of uploaded files to make available to your code. + /// - memoryLimit: + /// - networkPolicy: Network access policy for the container. + public init( + _type: Components.Schemas.AutoCodeInterpreterToolParam._TypePayload, + fileIds: [Swift.String]? = nil, + memoryLimit: Components.Schemas.ContainerMemoryLimit? = nil, + networkPolicy: Components.Schemas.AutoCodeInterpreterToolParam.NetworkPolicyPayload? = nil + ) { + self._type = _type + self.fileIds = fileIds + self.memoryLimit = memoryLimit + self.networkPolicy = networkPolicy + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case fileIds = "file_ids" + case memoryLimit = "memory_limit" + case networkPolicy = "network_policy" + } + } + /// Control how much effort the model will exert to match the style and features, especially facial features, of input images. This parameter is only supported for `gpt-image-1` and `gpt-image-1.5` and later models, unsupported for `gpt-image-1-mini`. Supports `high` and `low`. Defaults to `low`. + /// + /// - Remark: Generated from `#/components/schemas/InputFidelity`. + @frozen public enum InputFidelity: String, Codable, Hashable, Sendable, CaseIterable { + case high = "high" + case low = "low" + } + /// - Remark: Generated from `#/components/schemas/ImageGenActionEnum`. + @frozen public enum ImageGenActionEnum: String, Codable, Hashable, Sendable, CaseIterable { + case generate = "generate" + case edit = "edit" + case auto = "auto" + } + /// A tool that allows the model to execute shell commands in a local environment. + /// + /// - Remark: Generated from `#/components/schemas/LocalShellToolParam`. + public struct LocalShellToolParam: Codable, Hashable, Sendable { + /// The type of the local shell tool. Always `local_shell`. + /// + /// - Remark: Generated from `#/components/schemas/LocalShellToolParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case localShell = "local_shell" + } + /// The type of the local shell tool. Always `local_shell`. + /// + /// - Remark: Generated from `#/components/schemas/LocalShellToolParam/type`. + public var _type: Components.Schemas.LocalShellToolParam._TypePayload + /// Creates a new `LocalShellToolParam`. + /// + /// - Parameters: + /// - _type: The type of the local shell tool. Always `local_shell`. + public init(_type: Components.Schemas.LocalShellToolParam._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam`. + public struct ContainerAutoParam: Codable, Hashable, Sendable { + /// Automatically creates a container for this request + /// + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case containerAuto = "container_auto" + } + /// Automatically creates a container for this request + /// + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/type`. + public var _type: Components.Schemas.ContainerAutoParam._TypePayload + /// An optional list of uploaded files to make available to your code. + /// + /// - 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. + /// + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/network_policy`. + @frozen public enum NetworkPolicyPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/network_policy/ContainerNetworkPolicyDisabledParam`. + case containerNetworkPolicyDisabledParam(Components.Schemas.ContainerNetworkPolicyDisabledParam) + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/network_policy/ContainerNetworkPolicyAllowlistParam`. + case containerNetworkPolicyAllowlistParam(Components.Schemas.ContainerNetworkPolicyAllowlistParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "ContainerNetworkPolicyDisabledParam", "#/components/schemas/ContainerNetworkPolicyDisabledParam": + self = .containerNetworkPolicyDisabledParam(try .init(from: decoder)) + case "ContainerNetworkPolicyAllowlistParam", "#/components/schemas/ContainerNetworkPolicyAllowlistParam": + self = .containerNetworkPolicyAllowlistParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .containerNetworkPolicyDisabledParam(value): + try value.encode(to: encoder) + case let .containerNetworkPolicyAllowlistParam(value): + try value.encode(to: encoder) + } + } + } + /// Network access policy for the container. + /// + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/network_policy`. + public var networkPolicy: Components.Schemas.ContainerAutoParam.NetworkPolicyPayload? + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/SkillsPayload`. + @frozen public enum SkillsPayloadPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/SkillsPayload/SkillReferenceParam`. + case skillReferenceParam(Components.Schemas.SkillReferenceParam) + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/SkillsPayload/InlineSkillParam`. + case inlineSkillParam(Components.Schemas.InlineSkillParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "SkillReferenceParam", "#/components/schemas/SkillReferenceParam": + self = .skillReferenceParam(try .init(from: decoder)) + case "InlineSkillParam", "#/components/schemas/InlineSkillParam": + self = .inlineSkillParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .skillReferenceParam(value): + try value.encode(to: encoder) + case let .inlineSkillParam(value): + try value.encode(to: encoder) + } + } + } + /// An optional list of skills referenced by id or inline data. + /// + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/skills`. + public typealias SkillsPayload = [Components.Schemas.ContainerAutoParam.SkillsPayloadPayload] + /// An optional list of skills referenced by id or inline data. + /// + /// - Remark: Generated from `#/components/schemas/ContainerAutoParam/skills`. + public var skills: Components.Schemas.ContainerAutoParam.SkillsPayload? + /// Creates a new `ContainerAutoParam`. + /// + /// - Parameters: + /// - _type: Automatically creates a container for this request + /// - fileIds: An optional list of uploaded files to make available to your code. + /// - memoryLimit: + /// - networkPolicy: Network access policy for the container. + /// - skills: An optional list of skills referenced by id or inline data. + public init( + _type: Components.Schemas.ContainerAutoParam._TypePayload, + fileIds: [Swift.String]? = nil, + memoryLimit: Components.Schemas.ContainerMemoryLimit? = nil, + networkPolicy: Components.Schemas.ContainerAutoParam.NetworkPolicyPayload? = nil, + skills: Components.Schemas.ContainerAutoParam.SkillsPayload? = nil + ) { + self._type = _type + self.fileIds = fileIds + self.memoryLimit = memoryLimit + self.networkPolicy = networkPolicy + self.skills = skills + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case fileIds = "file_ids" + case memoryLimit = "memory_limit" + case networkPolicy = "network_policy" + case skills + } + } + /// - Remark: Generated from `#/components/schemas/LocalSkillParam`. + public struct LocalSkillParam: Codable, Hashable, Sendable { + /// The name of the skill. + /// + /// - Remark: Generated from `#/components/schemas/LocalSkillParam/name`. + public var name: Swift.String + /// The description of the skill. + /// + /// - Remark: Generated from `#/components/schemas/LocalSkillParam/description`. + public var description: Swift.String + /// The path to the directory containing the skill. + /// + /// - Remark: Generated from `#/components/schemas/LocalSkillParam/path`. + public var path: Swift.String + /// Creates a new `LocalSkillParam`. + /// + /// - Parameters: + /// - name: The name of the skill. + /// - description: The description of the skill. + /// - path: The path to the directory containing the skill. + public init( + name: Swift.String, + description: Swift.String, + path: Swift.String + ) { + self.name = name + self.description = description + self.path = path + } + public enum CodingKeys: String, CodingKey { + case name + case description + case path + } + } + /// - Remark: Generated from `#/components/schemas/LocalEnvironmentParam`. + public struct LocalEnvironmentParam: Codable, Hashable, Sendable { + /// Use a local computer environment. + /// + /// - Remark: Generated from `#/components/schemas/LocalEnvironmentParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case local = "local" + } + /// Use a local computer environment. + /// + /// - Remark: Generated from `#/components/schemas/LocalEnvironmentParam/type`. + public var _type: Components.Schemas.LocalEnvironmentParam._TypePayload + /// An optional list of skills. + /// + /// - Remark: Generated from `#/components/schemas/LocalEnvironmentParam/skills`. + public var skills: [Components.Schemas.LocalSkillParam]? + /// Creates a new `LocalEnvironmentParam`. + /// + /// - Parameters: + /// - _type: Use a local computer environment. + /// - skills: An optional list of skills. + public init( + _type: Components.Schemas.LocalEnvironmentParam._TypePayload, + skills: [Components.Schemas.LocalSkillParam]? = nil + ) { + self._type = _type + self.skills = skills + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case skills + } + } + /// - Remark: Generated from `#/components/schemas/ContainerReferenceParam`. + public struct ContainerReferenceParam: Codable, Hashable, Sendable { + /// References a container created with the /v1/containers endpoint + /// + /// - Remark: Generated from `#/components/schemas/ContainerReferenceParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case containerReference = "container_reference" + } + /// References a container created with the /v1/containers endpoint + /// + /// - Remark: Generated from `#/components/schemas/ContainerReferenceParam/type`. + public var _type: Components.Schemas.ContainerReferenceParam._TypePayload + /// The ID of the referenced container. + /// + /// - Remark: Generated from `#/components/schemas/ContainerReferenceParam/container_id`. + public var containerId: Swift.String + /// Creates a new `ContainerReferenceParam`. + /// + /// - Parameters: + /// - _type: References a container created with the /v1/containers endpoint + /// - containerId: The ID of the referenced container. + public init( + _type: Components.Schemas.ContainerReferenceParam._TypePayload, + containerId: Swift.String + ) { + self._type = _type + self.containerId = containerId + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case containerId = "container_id" + } + } + /// A tool that allows the model to execute shell commands. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellToolParam`. + public struct FunctionShellToolParam: Codable, Hashable, Sendable { + /// The type of the shell tool. Always `shell`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellToolParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case shell = "shell" + } + /// The type of the shell tool. Always `shell`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellToolParam/type`. + public var _type: Components.Schemas.FunctionShellToolParam._TypePayload + /// - Remark: Generated from `#/components/schemas/FunctionShellToolParam/environment`. + @frozen public enum EnvironmentPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/FunctionShellToolParam/environment/ContainerAutoParam`. + case containerAutoParam(Components.Schemas.ContainerAutoParam) + /// - Remark: Generated from `#/components/schemas/FunctionShellToolParam/environment/LocalEnvironmentParam`. + case localEnvironmentParam(Components.Schemas.LocalEnvironmentParam) + /// - Remark: Generated from `#/components/schemas/FunctionShellToolParam/environment/ContainerReferenceParam`. + case containerReferenceParam(Components.Schemas.ContainerReferenceParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "ContainerAutoParam", "#/components/schemas/ContainerAutoParam": + self = .containerAutoParam(try .init(from: decoder)) + case "LocalEnvironmentParam", "#/components/schemas/LocalEnvironmentParam": + self = .localEnvironmentParam(try .init(from: decoder)) + case "ContainerReferenceParam", "#/components/schemas/ContainerReferenceParam": + self = .containerReferenceParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .containerAutoParam(value): + try value.encode(to: encoder) + case let .localEnvironmentParam(value): + try value.encode(to: encoder) + case let .containerReferenceParam(value): + try value.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/FunctionShellToolParam/environment`. + public var environment: Components.Schemas.FunctionShellToolParam.EnvironmentPayload? + /// Creates a new `FunctionShellToolParam`. + /// + /// - Parameters: + /// - _type: The type of the shell tool. Always `shell`. + /// - environment: + public init( + _type: Components.Schemas.FunctionShellToolParam._TypePayload, + environment: Components.Schemas.FunctionShellToolParam.EnvironmentPayload? = nil + ) { + self._type = _type + self.environment = environment + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case environment + } + } + /// Unconstrained free-form text. + /// + /// - Remark: Generated from `#/components/schemas/CustomTextFormatParam`. + public struct CustomTextFormatParam: Codable, Hashable, Sendable { + /// Unconstrained text format. Always `text`. + /// + /// - Remark: Generated from `#/components/schemas/CustomTextFormatParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case text = "text" + } + /// Unconstrained text format. Always `text`. + /// + /// - Remark: Generated from `#/components/schemas/CustomTextFormatParam/type`. + public var _type: Components.Schemas.CustomTextFormatParam._TypePayload + /// Creates a new `CustomTextFormatParam`. + /// + /// - Parameters: + /// - _type: Unconstrained text format. Always `text`. + public init(_type: Components.Schemas.CustomTextFormatParam._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// - Remark: Generated from `#/components/schemas/GrammarSyntax1`. + @frozen public enum GrammarSyntax1: String, Codable, Hashable, Sendable, CaseIterable { + case lark = "lark" + case regex = "regex" + } + /// A grammar defined by the user. + /// + /// - Remark: Generated from `#/components/schemas/CustomGrammarFormatParam`. + public struct CustomGrammarFormatParam: Codable, Hashable, Sendable { + /// Grammar format. Always `grammar`. + /// + /// - Remark: Generated from `#/components/schemas/CustomGrammarFormatParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case grammar = "grammar" + } + /// Grammar format. Always `grammar`. + /// + /// - Remark: Generated from `#/components/schemas/CustomGrammarFormatParam/type`. + public var _type: Components.Schemas.CustomGrammarFormatParam._TypePayload + /// The syntax of the grammar definition. One of `lark` or `regex`. + /// + /// - Remark: Generated from `#/components/schemas/CustomGrammarFormatParam/syntax`. + public var syntax: Components.Schemas.GrammarSyntax1 + /// The grammar definition. + /// + /// - Remark: Generated from `#/components/schemas/CustomGrammarFormatParam/definition`. + public var definition: Swift.String + /// Creates a new `CustomGrammarFormatParam`. + /// + /// - Parameters: + /// - _type: Grammar format. Always `grammar`. + /// - syntax: The syntax of the grammar definition. One of `lark` or `regex`. + /// - definition: The grammar definition. + public init( + _type: Components.Schemas.CustomGrammarFormatParam._TypePayload, + syntax: Components.Schemas.GrammarSyntax1, + definition: Swift.String + ) { + self._type = _type + self.syntax = syntax + self.definition = definition + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case syntax + case definition + } + } + /// A custom tool that processes input using a specified format. Learn more about [custom tools](/docs/guides/function-calling#custom-tools) + /// + /// - Remark: Generated from `#/components/schemas/CustomToolParam`. + public struct CustomToolParam: Codable, Hashable, Sendable { + /// The type of the custom tool. Always `custom`. + /// + /// - Remark: Generated from `#/components/schemas/CustomToolParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case custom = "custom" + } + /// The type of the custom tool. Always `custom`. + /// + /// - Remark: Generated from `#/components/schemas/CustomToolParam/type`. + public var _type: Components.Schemas.CustomToolParam._TypePayload + /// The name of the custom tool, used to identify it in tool calls. + /// + /// - Remark: Generated from `#/components/schemas/CustomToolParam/name`. + public var name: Swift.String + /// Optional description of the custom tool, used to provide more context. + /// + /// - Remark: Generated from `#/components/schemas/CustomToolParam/description`. + public var description: Swift.String? + /// The input format for the custom tool. Default is unconstrained text. + /// + /// - Remark: Generated from `#/components/schemas/CustomToolParam/format`. + @frozen public enum FormatPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/CustomToolParam/format/CustomTextFormatParam`. + case customTextFormatParam(Components.Schemas.CustomTextFormatParam) + /// - Remark: Generated from `#/components/schemas/CustomToolParam/format/CustomGrammarFormatParam`. + case customGrammarFormatParam(Components.Schemas.CustomGrammarFormatParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "CustomTextFormatParam", "#/components/schemas/CustomTextFormatParam": + self = .customTextFormatParam(try .init(from: decoder)) + case "CustomGrammarFormatParam", "#/components/schemas/CustomGrammarFormatParam": + self = .customGrammarFormatParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .customTextFormatParam(value): + try value.encode(to: encoder) + case let .customGrammarFormatParam(value): + try value.encode(to: encoder) + } + } + } + /// The input format for the custom tool. Default is unconstrained text. + /// + /// - Remark: Generated from `#/components/schemas/CustomToolParam/format`. + public var format: Components.Schemas.CustomToolParam.FormatPayload? + /// Whether this tool should be deferred and discovered via tool search. + /// + /// - Remark: Generated from `#/components/schemas/CustomToolParam/defer_loading`. + public var deferLoading: Swift.Bool? + /// Creates a new `CustomToolParam`. + /// + /// - Parameters: + /// - _type: The type of the custom tool. Always `custom`. + /// - name: The name of the custom tool, used to identify it in tool calls. + /// - description: Optional description of the custom tool, used to provide more context. + /// - format: The input format for the custom tool. Default is unconstrained text. + /// - deferLoading: Whether this tool should be deferred and discovered via tool search. + public init( + _type: Components.Schemas.CustomToolParam._TypePayload, + name: Swift.String, + description: Swift.String? = nil, + format: Components.Schemas.CustomToolParam.FormatPayload? = nil, + deferLoading: Swift.Bool? = nil + ) { + self._type = _type + self.name = name + self.description = description + self.format = format + self.deferLoading = deferLoading + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case name + case description + case format + case deferLoading = "defer_loading" + } + } + /// - Remark: Generated from `#/components/schemas/EmptyModelParam`. + public typealias EmptyModelParam = OpenAPIRuntime.OpenAPIObjectContainer + /// - Remark: Generated from `#/components/schemas/FunctionToolParam`. + public struct FunctionToolParam: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/FunctionToolParam/name`. + public var name: Swift.String + public typealias String = 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? + public typealias Bool = Swift.Bool + /// - Remark: Generated from `#/components/schemas/FunctionToolParam/strict`. + public var strict: Swift.Bool? + /// - Remark: Generated from `#/components/schemas/FunctionToolParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case function = "function" + } + /// - Remark: Generated from `#/components/schemas/FunctionToolParam/type`. + public var _type: Components.Schemas.FunctionToolParam._TypePayload + /// Whether this function should be deferred and discovered via tool search. + /// + /// - Remark: Generated from `#/components/schemas/FunctionToolParam/defer_loading`. + public var deferLoading: Swift.Bool? + /// Creates a new `FunctionToolParam`. + /// + /// - Parameters: + /// - name: + /// - description: + /// - parameters: + /// - strict: + /// - _type: + /// - deferLoading: Whether this function should be deferred and discovered via tool search. + public init( + name: Swift.String, + description: Swift.String? = nil, + parameters: Components.Schemas.EmptyModelParam? = nil, + strict: Swift.Bool? = nil, + _type: Components.Schemas.FunctionToolParam._TypePayload, + deferLoading: Swift.Bool? = nil + ) { + self.name = name + self.description = description + self.parameters = parameters + self.strict = strict + self._type = _type + self.deferLoading = deferLoading + } + public enum CodingKeys: String, CodingKey { + case name + case description + case parameters + case strict + case _type = "type" + case deferLoading = "defer_loading" + } + } + /// Groups function/custom tools under a shared namespace. + /// + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam`. + public struct NamespaceToolParam: Codable, Hashable, Sendable { + /// The type of the tool. Always `namespace`. + /// + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case namespace = "namespace" + } + /// The type of the tool. Always `namespace`. + /// + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam/type`. + public var _type: Components.Schemas.NamespaceToolParam._TypePayload + /// The namespace name used in tool calls (for example, `crm`). + /// + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam/name`. + public var name: Swift.String + /// A description of the namespace shown to the model. + /// + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam/description`. + public var description: Swift.String + /// A function or custom tool that belongs to a namespace. + /// + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam/ToolsPayload`. + @frozen public enum ToolsPayloadPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam/ToolsPayload/FunctionToolParam`. + case functionToolParam(Components.Schemas.FunctionToolParam) + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam/ToolsPayload/CustomToolParam`. + case customToolParam(Components.Schemas.CustomToolParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "FunctionToolParam", "#/components/schemas/FunctionToolParam": + self = .functionToolParam(try .init(from: decoder)) + case "CustomToolParam", "#/components/schemas/CustomToolParam": + self = .customToolParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .functionToolParam(value): + try value.encode(to: encoder) + case let .customToolParam(value): + try value.encode(to: encoder) + } + } + } + /// The function/custom tools available inside this namespace. + /// + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam/tools`. + public typealias ToolsPayload = [Components.Schemas.NamespaceToolParam.ToolsPayloadPayload] + /// The function/custom tools available inside this namespace. + /// + /// - Remark: Generated from `#/components/schemas/NamespaceToolParam/tools`. + public var tools: Components.Schemas.NamespaceToolParam.ToolsPayload + /// Creates a new `NamespaceToolParam`. + /// + /// - Parameters: + /// - _type: The type of the tool. Always `namespace`. + /// - name: The namespace name used in tool calls (for example, `crm`). + /// - description: A description of the namespace shown to the model. + /// - tools: The function/custom tools available inside this namespace. + public init( + _type: Components.Schemas.NamespaceToolParam._TypePayload, + name: Swift.String, + description: Swift.String, + tools: Components.Schemas.NamespaceToolParam.ToolsPayload + ) { + self._type = _type + self.name = name + self.description = description + self.tools = tools + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case name + case description + case tools + } + } + /// Hosted or BYOT tool search configuration for deferred tools. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchToolParam`. + public struct ToolSearchToolParam: Codable, Hashable, Sendable { + /// The type of the tool. Always `tool_search`. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchToolParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case toolSearch = "tool_search" + } + /// The type of the tool. Always `tool_search`. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchToolParam/type`. + public var _type: Components.Schemas.ToolSearchToolParam._TypePayload + /// Whether tool search is executed by the server or by the client. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchToolParam/execution`. + public var execution: Components.Schemas.ToolSearchExecutionType? + public typealias String = Swift.String + /// - 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`. + /// + /// - Parameters: + /// - _type: The type of the tool. Always `tool_search`. + /// - execution: Whether tool search is executed by the server or by the client. + /// - description: + /// - parameters: + public init( + _type: Components.Schemas.ToolSearchToolParam._TypePayload, + execution: Components.Schemas.ToolSearchExecutionType? = nil, + description: Swift.String? = nil, + parameters: Components.Schemas.EmptyModelParam? = nil + ) { + self._type = _type + self.execution = execution + self.description = description + self.parameters = parameters + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case execution + case description + case parameters + } + } + /// - Remark: Generated from `#/components/schemas/ApproximateLocation`. + public struct ApproximateLocation: Codable, Hashable, Sendable { + /// The type of location approximation. Always `approximate`. + /// + /// - Remark: Generated from `#/components/schemas/ApproximateLocation/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case approximate = "approximate" + } + /// The type of location approximation. Always `approximate`. + /// + /// - Remark: Generated from `#/components/schemas/ApproximateLocation/type`. + public var _type: Components.Schemas.ApproximateLocation._TypePayload + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ApproximateLocation/country`. + public var country: Swift.String? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ApproximateLocation/region`. + public var region: Swift.String? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ApproximateLocation/city`. + public var city: Swift.String? + public typealias String = Swift.String + /// - 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: + public init( + _type: Components.Schemas.ApproximateLocation._TypePayload, + country: Swift.String? = nil, + region: Swift.String? = nil, + city: Swift.String? = nil, + timezone: Swift.String? = nil + ) { + self._type = _type + self.country = country + self.region = region + self.city = city + self.timezone = timezone + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case country + case region + case city + case timezone + } + } + /// - Remark: Generated from `#/components/schemas/SearchContextSize`. + @frozen public enum SearchContextSize: String, Codable, Hashable, Sendable, CaseIterable { + case low = "low" + case medium = "medium" + case high = "high" + } + /// - Remark: Generated from `#/components/schemas/SearchContentType`. + @frozen public enum SearchContentType: String, Codable, Hashable, Sendable, CaseIterable { + case text = "text" + case image = "image" + } + /// This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search). + /// + /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool`. + public struct WebSearchPreviewTool: Codable, Hashable, Sendable { + /// The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case webSearchPreview = "web_search_preview" + case webSearchPreview20250311 = "web_search_preview_2025_03_11" + } + /// The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`. + /// + /// - 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. + /// + /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/search_context_size`. + public var searchContextSize: Components.Schemas.SearchContextSize? + /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/search_content_types`. + public var searchContentTypes: [Components.Schemas.SearchContentType]? + /// Creates a new `WebSearchPreviewTool`. + /// + /// - Parameters: + /// - _type: The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`. + /// - 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. + /// - searchContentTypes: + public init( + _type: Components.Schemas.WebSearchPreviewTool._TypePayload, + userLocation: Components.Schemas.ApproximateLocation? = nil, + searchContextSize: Components.Schemas.SearchContextSize? = nil, + searchContentTypes: [Components.Schemas.SearchContentType]? = nil + ) { + self._type = _type + self.userLocation = userLocation + self.searchContextSize = searchContextSize + self.searchContentTypes = searchContentTypes + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case userLocation = "user_location" + case searchContextSize = "search_context_size" + case searchContentTypes = "search_content_types" + } + } + /// Allows the assistant to create, delete, or update files using unified diffs. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolParam`. + public struct ApplyPatchToolParam: Codable, Hashable, Sendable { + /// The type of the tool. Always `apply_patch`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case applyPatch = "apply_patch" + } + /// The type of the tool. Always `apply_patch`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolParam/type`. + public var _type: Components.Schemas.ApplyPatchToolParam._TypePayload + /// Creates a new `ApplyPatchToolParam`. + /// + /// - Parameters: + /// - _type: The type of the tool. Always `apply_patch`. + public init(_type: Components.Schemas.ApplyPatchToolParam._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// - Remark: Generated from `#/components/schemas/ToolSearchOutput`. + public struct ToolSearchOutput: Codable, Hashable, Sendable { + /// The type of the item. Always `tool_search_output`. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case toolSearchOutput = "tool_search_output" + } + /// The type of the item. Always `tool_search_output`. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/type`. + public var _type: Components.Schemas.ToolSearchOutput._TypePayload + /// The unique ID of the tool search output item. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/id`. + public var id: Swift.String + public typealias String = Swift.String + /// - 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. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/execution`. + public var execution: Components.Schemas.ToolSearchExecutionType + /// The loaded tool definitions returned by tool search. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/tools`. + public var tools: [Components.Schemas.Tool] + /// The status of the tool search output item that was recorded. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/status`. + public var status: Components.Schemas.FunctionCallOutputStatusEnum + /// The identifier of the actor that created the item. + /// + /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/created_by`. + public var createdBy: Swift.String? + /// Creates a new `ToolSearchOutput`. + /// + /// - Parameters: + /// - _type: The type of the item. Always `tool_search_output`. + /// - id: The unique ID of the tool search output item. + /// - callId: + /// - 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. + /// - createdBy: The identifier of the actor that created the item. + public init( + _type: Components.Schemas.ToolSearchOutput._TypePayload, + id: Swift.String, + callId: Swift.String? = nil, + execution: Components.Schemas.ToolSearchExecutionType, + tools: [Components.Schemas.Tool], + status: Components.Schemas.FunctionCallOutputStatusEnum, + createdBy: Swift.String? = nil + ) { + self._type = _type + self.id = id + self.callId = callId + self.execution = execution + self.tools = tools + self.status = status + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case id + case callId = "call_id" + case execution + case tools + case status + case createdBy = "created_by" + } + } + /// A compaction item generated by the [`v1/responses/compact` API](/docs/api-reference/responses/compact). + /// + /// - Remark: Generated from `#/components/schemas/CompactionBody`. + public struct CompactionBody: Codable, Hashable, Sendable { + /// The type of the item. Always `compaction`. + /// + /// - Remark: Generated from `#/components/schemas/CompactionBody/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case compaction = "compaction" + } + /// The type of the item. Always `compaction`. + /// + /// - Remark: Generated from `#/components/schemas/CompactionBody/type`. + public var _type: Components.Schemas.CompactionBody._TypePayload + /// The unique ID of the compaction item. + /// + /// - Remark: Generated from `#/components/schemas/CompactionBody/id`. + public var id: Swift.String + /// The encrypted content that was produced by compaction. + /// + /// - Remark: Generated from `#/components/schemas/CompactionBody/encrypted_content`. + public var encryptedContent: Swift.String + /// The identifier of the actor that created the item. + /// + /// - Remark: Generated from `#/components/schemas/CompactionBody/created_by`. + public var createdBy: Swift.String? + /// Creates a new `CompactionBody`. + /// + /// - Parameters: + /// - _type: The type of the item. Always `compaction`. + /// - id: The unique ID of the compaction item. + /// - encryptedContent: The encrypted content that was produced by compaction. + /// - createdBy: The identifier of the actor that created the item. + public init( + _type: Components.Schemas.CompactionBody._TypePayload, + id: Swift.String, + encryptedContent: Swift.String, + createdBy: Swift.String? = nil + ) { + self._type = _type + self.id = id + self.encryptedContent = encryptedContent + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case id + case encryptedContent = "encrypted_content" + case createdBy = "created_by" + } + } + /// The logs output from the code interpreter. + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterOutputLogs`. + public struct CodeInterpreterOutputLogs: Codable, Hashable, Sendable { + /// The type of the output. Always `logs`. + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterOutputLogs/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case logs = "logs" + } + /// The type of the output. Always `logs`. + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterOutputLogs/type`. + public var _type: Components.Schemas.CodeInterpreterOutputLogs._TypePayload + /// The logs output from the code interpreter. + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterOutputLogs/logs`. + public var logs: Swift.String + /// Creates a new `CodeInterpreterOutputLogs`. + /// + /// - Parameters: + /// - _type: The type of the output. Always `logs`. + /// - logs: The logs output from the code interpreter. + public init( + _type: Components.Schemas.CodeInterpreterOutputLogs._TypePayload, + logs: Swift.String + ) { + self._type = _type + self.logs = logs + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case logs + } + } + /// The image output from the code interpreter. + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterOutputImage`. + public struct CodeInterpreterOutputImage: Codable, Hashable, Sendable { + /// The type of the output. Always `image`. + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterOutputImage/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case image = "image" + } + /// The type of the output. Always `image`. + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterOutputImage/type`. + public var _type: Components.Schemas.CodeInterpreterOutputImage._TypePayload + /// The URL of the image output from the code interpreter. + /// + /// - Remark: Generated from `#/components/schemas/CodeInterpreterOutputImage/url`. + public var url: Swift.String + /// Creates a new `CodeInterpreterOutputImage`. + /// + /// - Parameters: + /// - _type: The type of the output. Always `image`. + /// - url: The URL of the image output from the code interpreter. + public init( + _type: Components.Schemas.CodeInterpreterOutputImage._TypePayload, + url: Swift.String + ) { + self._type = _type + self.url = url + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case url + } + } + /// Execute a shell command on the server. + /// + /// - Remark: Generated from `#/components/schemas/LocalShellExecAction`. + public struct LocalShellExecAction: Codable, Hashable, Sendable { + /// The type of the local shell action. Always `exec`. + /// + /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case exec = "exec" + } + /// The type of the local shell action. Always `exec`. + /// + /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/type`. + public var _type: Components.Schemas.LocalShellExecAction._TypePayload + /// The command to run. + /// + /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/command`. + public var command: [Swift.String] + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/timeout_ms`. + public var timeoutMs: Swift.Int? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/working_directory`. + public var workingDirectory: Swift.String? + /// Environment variables to set for the command. + /// + /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/env`. + public struct EnvPayload: Codable, Hashable, Sendable { + /// A container of undocumented properties. + public var additionalProperties: [String: Swift.String] + /// Creates a new `EnvPayload`. /// /// - Parameters: - /// - value1: - /// - value2: - public init( - value1: Components.Schemas.Filters? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 + /// - additionalProperties: A container of undocumented properties. + public init(additionalProperties: [String: Swift.String] = .init()) { + self.additionalProperties = additionalProperties + } + public init(from decoder: any Swift.Decoder) throws { + additionalProperties = try decoder.decodeAdditionalProperties(knownKeys: []) + } + public func encode(to encoder: any Swift.Encoder) throws { + try encoder.encodeAdditionalProperties(additionalProperties) + } + } + /// Environment variables to set for the command. + /// + /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/env`. + public var env: Components.Schemas.LocalShellExecAction.EnvPayload + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/user`. + public var user: Swift.String? + /// Creates a new `LocalShellExecAction`. + /// + /// - Parameters: + /// - _type: The type of the local shell action. Always `exec`. + /// - command: The command to run. + /// - timeoutMs: + /// - workingDirectory: + /// - env: Environment variables to set for the command. + /// - user: + public init( + _type: Components.Schemas.LocalShellExecAction._TypePayload, + command: [Swift.String], + timeoutMs: Swift.Int? = nil, + workingDirectory: Swift.String? = nil, + env: Components.Schemas.LocalShellExecAction.EnvPayload, + user: Swift.String? = nil + ) { + self._type = _type + self.command = command + self.timeoutMs = timeoutMs + self.workingDirectory = workingDirectory + self.env = env + self.user = user + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case command + case timeoutMs = "timeout_ms" + case workingDirectory = "working_directory" + case env + case user + } + } + /// Execute a shell command. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellAction`. + public struct FunctionShellAction: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/FunctionShellAction/commands`. + public var commands: [Swift.String] + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/FunctionShellAction/timeout_ms`. + public var timeoutMs: Swift.Int? + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/FunctionShellAction/max_output_length`. + public var maxOutputLength: Swift.Int? + /// Creates a new `FunctionShellAction`. + /// + /// - Parameters: + /// - commands: + /// - timeoutMs: + /// - maxOutputLength: + public init( + commands: [Swift.String], + timeoutMs: Swift.Int? = nil, + maxOutputLength: Swift.Int? = nil + ) { + self.commands = commands + self.timeoutMs = timeoutMs + self.maxOutputLength = maxOutputLength + } + public enum CodingKeys: String, CodingKey { + case commands + case timeoutMs = "timeout_ms" + case maxOutputLength = "max_output_length" + } + } + /// - Remark: Generated from `#/components/schemas/LocalShellCallStatus`. + @frozen public enum LocalShellCallStatus: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + case incomplete = "incomplete" + } + /// Represents the use of a local environment to perform shell actions. + /// + /// - Remark: Generated from `#/components/schemas/LocalEnvironmentResource`. + public struct LocalEnvironmentResource: Codable, Hashable, Sendable { + /// The environment type. Always `local`. + /// + /// - Remark: Generated from `#/components/schemas/LocalEnvironmentResource/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case local = "local" + } + /// The environment type. Always `local`. + /// + /// - Remark: Generated from `#/components/schemas/LocalEnvironmentResource/type`. + public var _type: Components.Schemas.LocalEnvironmentResource._TypePayload + /// Creates a new `LocalEnvironmentResource`. + /// + /// - Parameters: + /// - _type: The environment type. Always `local`. + public init(_type: Components.Schemas.LocalEnvironmentResource._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// Represents a container created with /v1/containers. + /// + /// - Remark: Generated from `#/components/schemas/ContainerReferenceResource`. + public struct ContainerReferenceResource: Codable, Hashable, Sendable { + /// The environment type. Always `container_reference`. + /// + /// - Remark: Generated from `#/components/schemas/ContainerReferenceResource/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case containerReference = "container_reference" + } + /// The environment type. Always `container_reference`. + /// + /// - Remark: Generated from `#/components/schemas/ContainerReferenceResource/type`. + public var _type: Components.Schemas.ContainerReferenceResource._TypePayload + /// - Remark: Generated from `#/components/schemas/ContainerReferenceResource/container_id`. + public var containerId: Swift.String + /// Creates a new `ContainerReferenceResource`. + /// + /// - Parameters: + /// - _type: The environment type. Always `container_reference`. + /// - containerId: + public init( + _type: Components.Schemas.ContainerReferenceResource._TypePayload, + containerId: Swift.String + ) { + self._type = _type + self.containerId = containerId + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case containerId = "container_id" + } + } + /// A tool call that executes one or more shell commands in a managed environment. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCall`. + public struct FunctionShellCall: Codable, Hashable, Sendable { + /// The type of the item. Always `shell_call`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case shellCall = "shell_call" + } + /// The type of the item. Always `shell_call`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/type`. + public var _type: Components.Schemas.FunctionShellCall._TypePayload + /// The unique ID of the shell tool call. Populated when this item is returned via API. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/id`. + public var id: Swift.String + /// The unique ID of the shell tool call generated by the model. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/call_id`. + public var callId: Swift.String + /// The shell commands and limits that describe how to run the tool call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/action`. + public var action: Components.Schemas.FunctionShellAction + /// The status of the shell call. One of `in_progress`, `completed`, or `incomplete`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/status`. + public var status: Components.Schemas.LocalShellCallStatus + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/environment`. + @frozen public enum EnvironmentPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/environment/LocalEnvironmentResource`. + case localEnvironmentResource(Components.Schemas.LocalEnvironmentResource) + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/environment/ContainerReferenceResource`. + case containerReferenceResource(Components.Schemas.ContainerReferenceResource) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "LocalEnvironmentResource", "#/components/schemas/LocalEnvironmentResource": + self = .localEnvironmentResource(try .init(from: decoder)) + case "ContainerReferenceResource", "#/components/schemas/ContainerReferenceResource": + self = .containerReferenceResource(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .localEnvironmentResource(value): + try value.encode(to: encoder) + case let .containerReferenceResource(value): + try value.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/environment`. + public var environment: Components.Schemas.FunctionShellCall.EnvironmentPayload? + /// The ID of the entity that created this tool call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCall/created_by`. + public var createdBy: Swift.String? + /// Creates a new `FunctionShellCall`. + /// + /// - Parameters: + /// - _type: The type of the item. Always `shell_call`. + /// - 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. + /// - action: The shell commands and limits that describe how to run the tool call. + /// - status: The status of the shell call. One of `in_progress`, `completed`, or `incomplete`. + /// - environment: + /// - createdBy: The ID of the entity that created this tool call. + public init( + _type: Components.Schemas.FunctionShellCall._TypePayload, + id: Swift.String, + callId: Swift.String, + action: Components.Schemas.FunctionShellAction, + status: Components.Schemas.LocalShellCallStatus, + environment: Components.Schemas.FunctionShellCall.EnvironmentPayload? = nil, + createdBy: Swift.String? = nil + ) { + self._type = _type + self.id = id + self.callId = callId + self.action = action + self.status = status + self.environment = environment + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case id + case callId = "call_id" + case action + case status + case environment + case createdBy = "created_by" + } + } + /// - Remark: Generated from `#/components/schemas/LocalShellCallOutputStatusEnum`. + @frozen public enum LocalShellCallOutputStatusEnum: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + case incomplete = "incomplete" + } + /// Indicates that the shell call exceeded its configured time limit. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputTimeoutOutcome`. + public struct FunctionShellCallOutputTimeoutOutcome: Codable, Hashable, Sendable { + /// The outcome type. Always `timeout`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputTimeoutOutcome/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case timeout = "timeout" + } + /// The outcome type. Always `timeout`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputTimeoutOutcome/type`. + public var _type: Components.Schemas.FunctionShellCallOutputTimeoutOutcome._TypePayload + /// Creates a new `FunctionShellCallOutputTimeoutOutcome`. + /// + /// - Parameters: + /// - _type: The outcome type. Always `timeout`. + public init(_type: Components.Schemas.FunctionShellCallOutputTimeoutOutcome._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// Indicates that the shell commands finished and returned an exit code. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputExitOutcome`. + public struct FunctionShellCallOutputExitOutcome: Codable, Hashable, Sendable { + /// The outcome type. Always `exit`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputExitOutcome/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case exit = "exit" + } + /// The outcome type. Always `exit`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputExitOutcome/type`. + public var _type: Components.Schemas.FunctionShellCallOutputExitOutcome._TypePayload + /// Exit code from the shell process. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputExitOutcome/exit_code`. + public var exitCode: Swift.Int + /// Creates a new `FunctionShellCallOutputExitOutcome`. + /// + /// - Parameters: + /// - _type: The outcome type. Always `exit`. + /// - exitCode: Exit code from the shell process. + public init( + _type: Components.Schemas.FunctionShellCallOutputExitOutcome._TypePayload, + exitCode: Swift.Int + ) { + self._type = _type + self.exitCode = exitCode + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case exitCode = "exit_code" + } + } + /// The content of a shell tool call output that was emitted. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContent`. + public struct FunctionShellCallOutputContent: Codable, Hashable, Sendable { + /// The standard output that was captured. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContent/stdout`. + public var stdout: Swift.String + /// The standard error output that was captured. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContent/stderr`. + public var stderr: Swift.String + /// Represents either an exit outcome (with an exit code) or a timeout outcome for a shell call output chunk. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContent/outcome`. + @frozen public enum OutcomePayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContent/outcome/FunctionShellCallOutputTimeoutOutcome`. + case functionShellCallOutputTimeoutOutcome(Components.Schemas.FunctionShellCallOutputTimeoutOutcome) + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContent/outcome/FunctionShellCallOutputExitOutcome`. + case functionShellCallOutputExitOutcome(Components.Schemas.FunctionShellCallOutputExitOutcome) + public enum CodingKeys: String, CodingKey { + case _type = "type" } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try .init(from: decoder) - } catch { - errors.append(error) + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "FunctionShellCallOutputTimeoutOutcome", "#/components/schemas/FunctionShellCallOutputTimeoutOutcome": + self = .functionShellCallOutputTimeoutOutcome(try .init(from: decoder)) + case "FunctionShellCallOutputExitOutcome", "#/components/schemas/FunctionShellCallOutputExitOutcome": + self = .functionShellCallOutputExitOutcome(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .functionShellCallOutputTimeoutOutcome(value): + try value.encode(to: encoder) + case let .functionShellCallOutputExitOutcome(value): + try value.encode(to: encoder) } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors + } + } + /// Represents either an exit outcome (with an exit code) or a timeout outcome for a shell call output chunk. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContent/outcome`. + public var outcome: Components.Schemas.FunctionShellCallOutputContent.OutcomePayload + /// The identifier of the actor that created the item. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContent/created_by`. + public var createdBy: Swift.String? + /// Creates a new `FunctionShellCallOutputContent`. + /// + /// - Parameters: + /// - stdout: The standard output that was captured. + /// - stderr: The standard error output that was captured. + /// - outcome: Represents either an exit outcome (with an exit code) or a timeout outcome for a shell call output chunk. + /// - createdBy: The identifier of the actor that created the item. + public init( + stdout: Swift.String, + stderr: Swift.String, + outcome: Components.Schemas.FunctionShellCallOutputContent.OutcomePayload, + createdBy: Swift.String? = nil + ) { + self.stdout = stdout + self.stderr = stderr + self.outcome = outcome + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case stdout + case stderr + case outcome + case createdBy = "created_by" + } + } + /// The output of a shell tool call that was emitted. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput`. + public struct FunctionShellCallOutput: Codable, Hashable, Sendable { + /// The type of the shell call output. Always `shell_call_output`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case shellCallOutput = "shell_call_output" + } + /// The type of the shell call output. Always `shell_call_output`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/type`. + public var _type: Components.Schemas.FunctionShellCallOutput._TypePayload + /// The unique ID of the shell call output. Populated when this item is returned via API. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/id`. + public var id: Swift.String + /// The unique ID of the shell tool call generated by the model. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/call_id`. + public var callId: Swift.String + /// The status of the shell call output. One of `in_progress`, `completed`, or `incomplete`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/status`. + public var status: Components.Schemas.LocalShellCallOutputStatusEnum + /// An array of shell call output contents + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/output`. + public var output: [Components.Schemas.FunctionShellCallOutputContent] + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/max_output_length`. + public var maxOutputLength: Swift.Int? + /// The identifier of the actor that created the item. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/created_by`. + public var createdBy: Swift.String? + /// Creates a new `FunctionShellCallOutput`. + /// + /// - Parameters: + /// - _type: The type of the shell call output. Always `shell_call_output`. + /// - id: The unique ID of the shell call output. Populated when this item is returned via API. + /// - 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: + /// - createdBy: The identifier of the actor that created the item. + public init( + _type: Components.Schemas.FunctionShellCallOutput._TypePayload, + id: Swift.String, + callId: Swift.String, + status: Components.Schemas.LocalShellCallOutputStatusEnum, + output: [Components.Schemas.FunctionShellCallOutputContent], + maxOutputLength: Swift.Int? = nil, + createdBy: Swift.String? = nil + ) { + self._type = _type + self.id = id + self.callId = callId + self.status = status + self.output = output + self.maxOutputLength = maxOutputLength + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case id + case callId = "call_id" + case status + case output + case maxOutputLength = "max_output_length" + case createdBy = "created_by" + } + } + /// - Remark: Generated from `#/components/schemas/ApplyPatchCallStatus`. + @frozen public enum ApplyPatchCallStatus: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + } + /// Instruction describing how to create a file via the apply_patch tool. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperation`. + public struct ApplyPatchCreateFileOperation: Codable, Hashable, Sendable { + /// Create a new file with the provided diff. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperation/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case createFile = "create_file" + } + /// Create a new file with the provided diff. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperation/type`. + public var _type: Components.Schemas.ApplyPatchCreateFileOperation._TypePayload + /// Path of the file to create. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperation/path`. + public var path: Swift.String + /// Diff to apply. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperation/diff`. + public var diff: Swift.String + /// Creates a new `ApplyPatchCreateFileOperation`. + /// + /// - Parameters: + /// - _type: Create a new file with the provided diff. + /// - path: Path of the file to create. + /// - diff: Diff to apply. + public init( + _type: Components.Schemas.ApplyPatchCreateFileOperation._TypePayload, + path: Swift.String, + diff: Swift.String + ) { + self._type = _type + self.path = path + self.diff = diff + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case path + case diff + } + } + /// Instruction describing how to delete a file via the apply_patch tool. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchDeleteFileOperation`. + public struct ApplyPatchDeleteFileOperation: Codable, Hashable, Sendable { + /// Delete the specified file. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchDeleteFileOperation/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case deleteFile = "delete_file" + } + /// Delete the specified file. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchDeleteFileOperation/type`. + public var _type: Components.Schemas.ApplyPatchDeleteFileOperation._TypePayload + /// Path of the file to delete. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchDeleteFileOperation/path`. + public var path: Swift.String + /// Creates a new `ApplyPatchDeleteFileOperation`. + /// + /// - Parameters: + /// - _type: Delete the specified file. + /// - path: Path of the file to delete. + public init( + _type: Components.Schemas.ApplyPatchDeleteFileOperation._TypePayload, + path: Swift.String + ) { + self._type = _type + self.path = path + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case path + } + } + /// Instruction describing how to update a file via the apply_patch tool. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperation`. + public struct ApplyPatchUpdateFileOperation: Codable, Hashable, Sendable { + /// Update an existing file with the provided diff. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperation/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case updateFile = "update_file" + } + /// Update an existing file with the provided diff. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperation/type`. + public var _type: Components.Schemas.ApplyPatchUpdateFileOperation._TypePayload + /// Path of the file to update. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperation/path`. + public var path: Swift.String + /// Diff to apply. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperation/diff`. + public var diff: Swift.String + /// Creates a new `ApplyPatchUpdateFileOperation`. + /// + /// - Parameters: + /// - _type: Update an existing file with the provided diff. + /// - path: Path of the file to update. + /// - diff: Diff to apply. + public init( + _type: Components.Schemas.ApplyPatchUpdateFileOperation._TypePayload, + path: Swift.String, + diff: Swift.String + ) { + self._type = _type + self.path = path + self.diff = diff + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case path + case diff + } + } + /// A tool call that applies file diffs by creating, deleting, or updating files. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall`. + public struct ApplyPatchToolCall: Codable, Hashable, Sendable { + /// The type of the item. Always `apply_patch_call`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case applyPatchCall = "apply_patch_call" + } + /// The type of the item. Always `apply_patch_call`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/type`. + public var _type: Components.Schemas.ApplyPatchToolCall._TypePayload + /// The unique ID of the apply patch tool call. Populated when this item is returned via API. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/id`. + public var id: Swift.String + /// The unique ID of the apply patch tool call generated by the model. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/call_id`. + public var callId: Swift.String + /// The status of the apply patch tool call. One of `in_progress` or `completed`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/status`. + public var status: Components.Schemas.ApplyPatchCallStatus + /// One of the create_file, delete_file, or update_file operations applied via apply_patch. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/operation`. + @frozen public enum OperationPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/operation/ApplyPatchCreateFileOperation`. + case applyPatchCreateFileOperation(Components.Schemas.ApplyPatchCreateFileOperation) + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/operation/ApplyPatchDeleteFileOperation`. + case applyPatchDeleteFileOperation(Components.Schemas.ApplyPatchDeleteFileOperation) + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/operation/ApplyPatchUpdateFileOperation`. + case applyPatchUpdateFileOperation(Components.Schemas.ApplyPatchUpdateFileOperation) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type ) + switch discriminator { + case "ApplyPatchCreateFileOperation", "#/components/schemas/ApplyPatchCreateFileOperation": + self = .applyPatchCreateFileOperation(try .init(from: decoder)) + case "ApplyPatchDeleteFileOperation", "#/components/schemas/ApplyPatchDeleteFileOperation": + self = .applyPatchDeleteFileOperation(try .init(from: decoder)) + case "ApplyPatchUpdateFileOperation", "#/components/schemas/ApplyPatchUpdateFileOperation": + self = .applyPatchUpdateFileOperation(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } } - public func encode(to encoder: any Encoder) throws { - try self.value1?.encode(to: encoder) - try self.value2?.encode(to: encoder) + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .applyPatchCreateFileOperation(value): + try value.encode(to: encoder) + case let .applyPatchDeleteFileOperation(value): + try value.encode(to: encoder) + case let .applyPatchUpdateFileOperation(value): + try value.encode(to: encoder) + } } } - /// - Remark: Generated from `#/components/schemas/FileSearchTool/filters`. - public var filters: Components.Schemas.FileSearchTool.FiltersPayload? - /// Creates a new `FileSearchTool`. + /// One of the create_file, delete_file, or update_file operations applied via apply_patch. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/operation`. + public var operation: Components.Schemas.ApplyPatchToolCall.OperationPayload + /// The ID of the entity that created this tool call. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCall/created_by`. + public var createdBy: Swift.String? + /// Creates a new `ApplyPatchToolCall`. + /// + /// - Parameters: + /// - _type: The type of the item. Always `apply_patch_call`. + /// - 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: One of the create_file, delete_file, or update_file operations applied via apply_patch. + /// - createdBy: The ID of the entity that created this tool call. + public init( + _type: Components.Schemas.ApplyPatchToolCall._TypePayload, + id: Swift.String, + callId: Swift.String, + status: Components.Schemas.ApplyPatchCallStatus, + operation: Components.Schemas.ApplyPatchToolCall.OperationPayload, + createdBy: Swift.String? = nil + ) { + self._type = _type + self.id = id + self.callId = callId + self.status = status + self.operation = operation + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case id + case callId = "call_id" + case status + case operation + case createdBy = "created_by" + } + } + /// - Remark: Generated from `#/components/schemas/ApplyPatchCallOutputStatus`. + @frozen public enum ApplyPatchCallOutputStatus: String, Codable, Hashable, Sendable, CaseIterable { + case completed = "completed" + case failed = "failed" + } + /// The output emitted by an apply patch tool call. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput`. + public struct ApplyPatchToolCallOutput: Codable, Hashable, Sendable { + /// The type of the item. Always `apply_patch_call_output`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case applyPatchCallOutput = "apply_patch_call_output" + } + /// The type of the item. Always `apply_patch_call_output`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/type`. + public var _type: Components.Schemas.ApplyPatchToolCallOutput._TypePayload + /// The unique ID of the apply patch tool call output. Populated when this item is returned via API. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/id`. + public var id: Swift.String + /// The unique ID of the apply patch tool call generated by the model. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/call_id`. + public var callId: Swift.String + /// The status of the apply patch tool call output. One of `completed` or `failed`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/status`. + public var status: Components.Schemas.ApplyPatchCallOutputStatus + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/output`. + public var output: Swift.String? + /// The ID of the entity that created this tool call output. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/created_by`. + public var createdBy: Swift.String? + /// Creates a new `ApplyPatchToolCallOutput`. + /// + /// - Parameters: + /// - _type: The type of the item. Always `apply_patch_call_output`. + /// - 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: + /// - createdBy: The ID of the entity that created this tool call output. + public init( + _type: Components.Schemas.ApplyPatchToolCallOutput._TypePayload, + id: Swift.String, + callId: Swift.String, + status: Components.Schemas.ApplyPatchCallOutputStatus, + output: Swift.String? = nil, + createdBy: Swift.String? = nil + ) { + self._type = _type + self.id = id + self.callId = callId + self.status = status + self.output = output + self.createdBy = createdBy + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case id + case callId = "call_id" + case status + case output + case createdBy = "created_by" + } + } + /// - Remark: Generated from `#/components/schemas/MCPToolCallStatus`. + @frozen public enum MCPToolCallStatus: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + case incomplete = "incomplete" + case calling = "calling" + case failed = "failed" + } + /// - Remark: Generated from `#/components/schemas/DetailEnum`. + @frozen public enum DetailEnum: String, Codable, Hashable, Sendable, CaseIterable { + case low = "low" + case high = "high" + case auto = "auto" + case original = "original" + } + /// - Remark: Generated from `#/components/schemas/FunctionCallItemStatus`. + @frozen public enum FunctionCallItemStatus: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + case incomplete = "incomplete" + } + /// The output of a computer tool call. + /// + /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam`. + public struct ComputerCallOutputItemParam: Codable, Hashable, Sendable { + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/id`. + public var id: Swift.String? + /// The ID of the computer tool call that produced the output. + /// + /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/call_id`. + public var callId: Swift.String + /// The type of the computer tool call output. Always `computer_call_output`. + /// + /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case computerCallOutput = "computer_call_output" + } + /// The type of the computer tool call output. Always `computer_call_output`. + /// + /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/type`. + 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] + /// - 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: - /// - _type: The type of the file search tool. Always `file_search`. - /// - vectorStoreIds: The IDs of the vector stores to search. - /// - maxNumResults: The maximum number of results to return. This number should be between 1 and 50 inclusive. - /// - rankingOptions: - /// - filters: + /// - id: + /// - 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: + /// - status: public init( - _type: Components.Schemas.FileSearchTool._TypePayload, - vectorStoreIds: [Swift.String], - maxNumResults: Swift.Int? = nil, - rankingOptions: Components.Schemas.RankingOptions? = nil, - filters: Components.Schemas.FileSearchTool.FiltersPayload? = nil + id: Swift.String? = nil, + callId: Swift.String, + _type: Components.Schemas.ComputerCallOutputItemParam._TypePayload, + output: Components.Schemas.ComputerScreenshotImage, + acknowledgedSafetyChecks: [Components.Schemas.ComputerCallSafetyCheckParam]? = nil, + status: Components.Schemas.FunctionCallItemStatus? = nil ) { + self.id = id + self.callId = callId self._type = _type - self.vectorStoreIds = vectorStoreIds - self.maxNumResults = maxNumResults - self.rankingOptions = rankingOptions - self.filters = filters + self.output = output + self.acknowledgedSafetyChecks = acknowledgedSafetyChecks + self.status = status } public enum CodingKeys: String, CodingKey { + case id + case callId = "call_id" case _type = "type" - case vectorStoreIds = "vector_store_ids" - case maxNumResults = "max_num_results" - case rankingOptions = "ranking_options" - case filters + case output + case acknowledgedSafetyChecks = "acknowledged_safety_checks" + case status } } - /// - Remark: Generated from `#/components/schemas/ApproximateLocation`. - public struct ApproximateLocation: Codable, Hashable, Sendable { - /// The type of location approximation. Always `approximate`. + /// A text input to the model. + /// + /// - Remark: Generated from `#/components/schemas/InputTextContentParam`. + public struct InputTextContentParam: Codable, Hashable, Sendable { + /// The type of the input item. Always `input_text`. /// - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/type`. + /// - Remark: Generated from `#/components/schemas/InputTextContentParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case approximate = "approximate" + case inputText = "input_text" } - /// The type of location approximation. Always `approximate`. + /// The type of the input item. Always `input_text`. /// - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/type`. - public var _type: Components.Schemas.ApproximateLocation._TypePayload - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/country`. - public struct CountryPayload: Codable, Hashable, Sendable { - /// 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/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/country/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `CountryPayload`. - /// - /// - Parameters: - /// - value1: The two-letter [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, e.g. `US`. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + /// - Remark: Generated from `#/components/schemas/InputTextContentParam/type`. + public var _type: Components.Schemas.InputTextContentParam._TypePayload + /// The text input to the model. + /// + /// - Remark: Generated from `#/components/schemas/InputTextContentParam/text`. + public var text: Swift.String + /// Creates a new `InputTextContentParam`. + /// + /// - Parameters: + /// - _type: The type of the input item. Always `input_text`. + /// - text: The text input to the model. + public init( + _type: Components.Schemas.InputTextContentParam._TypePayload, + text: Swift.String + ) { + self._type = _type + self.text = text } - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/country`. - public var country: Components.Schemas.ApproximateLocation.CountryPayload? - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/region`. - public struct RegionPayload: Codable, Hashable, Sendable { - /// Free text input for the region of the user, e.g. `California`. - /// - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/region/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/region/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `RegionPayload`. - /// - /// - Parameters: - /// - value1: Free text input for the region of the user, e.g. `California`. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case text } - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/region`. - public var region: Components.Schemas.ApproximateLocation.RegionPayload? - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/city`. - public struct CityPayload: Codable, Hashable, Sendable { - /// Free text input for the city of the user, e.g. `San Francisco`. - /// - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/city/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/city/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `CityPayload`. - /// - /// - Parameters: - /// - value1: Free text input for the city of the user, e.g. `San Francisco`. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + } + /// An image input to the model. Learn about [image inputs](/docs/guides/vision) + /// + /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam`. + public struct InputImageContentParamAutoParam: Codable, Hashable, Sendable { + /// The type of the input item. Always `input_image`. + /// + /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case inputImage = "input_image" } - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/city`. - public var city: Components.Schemas.ApproximateLocation.CityPayload? - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/timezone`. - public struct TimezonePayload: Codable, Hashable, Sendable { - /// The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`. - /// - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/timezone/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/timezone/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `TimezonePayload`. - /// - /// - Parameters: - /// - value1: The [IANA timezone](https://timeapi.io/documentation/iana-timezones) of the user, e.g. `America/Los_Angeles`. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + /// The type of the input item. Always `input_image`. + /// + /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/type`. + public var _type: Components.Schemas.InputImageContentParamAutoParam._TypePayload + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/image_url`. + public var imageUrl: Swift.String? + public typealias String = Swift.String + /// - 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: + /// - detail: + public init( + _type: Components.Schemas.InputImageContentParamAutoParam._TypePayload, + imageUrl: Swift.String? = nil, + fileId: Swift.String? = nil, + detail: Components.Schemas.DetailEnum? = nil + ) { + self._type = _type + self.imageUrl = imageUrl + self.fileId = fileId + self.detail = detail + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case imageUrl = "image_url" + case fileId = "file_id" + case detail + } + } + /// - Remark: Generated from `#/components/schemas/FileDetailEnum`. + @frozen public enum FileDetailEnum: String, Codable, Hashable, Sendable, CaseIterable { + case low = "low" + case high = "high" + } + /// A file input to the model. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContentParam`. + public struct InputFileContentParam: Codable, Hashable, Sendable { + /// The type of the input item. Always `input_file`. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContentParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case inputFile = "input_file" } - /// - Remark: Generated from `#/components/schemas/ApproximateLocation/timezone`. - public var timezone: Components.Schemas.ApproximateLocation.TimezonePayload? - /// Creates a new `ApproximateLocation`. + /// The type of the input item. Always `input_file`. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContentParam/type`. + public var _type: Components.Schemas.InputFileContentParam._TypePayload + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/InputFileContentParam/file_id`. + public var fileId: Swift.String? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/InputFileContentParam/filename`. + public var filename: Swift.String? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/InputFileContentParam/file_data`. + public var fileData: Swift.String? + public typealias String = Swift.String + /// - 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`. + /// + /// - Remark: Generated from `#/components/schemas/InputFileContentParam/detail`. + public var detail: Components.Schemas.FileDetailEnum? + /// Creates a new `InputFileContentParam`. /// /// - Parameters: - /// - _type: The type of location approximation. Always `approximate`. - /// - country: - /// - region: - /// - city: - /// - timezone: + /// - _type: The type of the input item. Always `input_file`. + /// - fileId: + /// - filename: + /// - fileData: + /// - fileUrl: + /// - 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.ApproximateLocation._TypePayload, - country: Components.Schemas.ApproximateLocation.CountryPayload? = nil, - region: Components.Schemas.ApproximateLocation.RegionPayload? = nil, - city: Components.Schemas.ApproximateLocation.CityPayload? = nil, - timezone: Components.Schemas.ApproximateLocation.TimezonePayload? = nil + _type: Components.Schemas.InputFileContentParam._TypePayload, + fileId: Swift.String? = nil, + filename: Swift.String? = nil, + fileData: Swift.String? = nil, + fileUrl: Swift.String? = nil, + detail: Components.Schemas.FileDetailEnum? = nil ) { self._type = _type - self.country = country - self.region = region - self.city = city - self.timezone = timezone + self.fileId = fileId + self.filename = filename + self.fileData = fileData + self.fileUrl = fileUrl + self.detail = detail } public enum CodingKeys: String, CodingKey { case _type = "type" - case country - case region - case city - case timezone + case fileId = "file_id" + case filename + case fileData = "file_data" + case fileUrl = "file_url" + case detail } } - /// This tool searches the web for relevant results to use in a response. Learn more about the [web search tool](https://platform.openai.com/docs/guides/tools-web-search). + /// The output of a function tool call. /// - /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool`. - public struct WebSearchPreviewTool: Codable, Hashable, Sendable { - /// The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`. + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam`. + public struct FunctionCallOutputItemParam: Codable, Hashable, Sendable { + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/id`. + public var id: Swift.String? + /// The unique ID of the function tool call generated by the model. /// - /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/type`. + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/call_id`. + public var callId: Swift.String + /// The type of the function tool call output. Always `function_call_output`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case webSearchPreview = "web_search_preview" - case webSearchPreview20250311 = "web_search_preview_2025_03_11" + case functionCallOutput = "function_call_output" } - /// The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`. + /// The type of the function tool call output. Always `function_call_output`. /// - /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/type`. - public var _type: Components.Schemas.WebSearchPreviewTool._TypePayload - /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/user_location`. - public struct UserLocationPayload: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/user_location/value1`. - public var value1: Components.Schemas.ApproximateLocation? - /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/user_location/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `UserLocationPayload`. + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/type`. + public var _type: Components.Schemas.FunctionCallOutputItemParam._TypePayload + /// Text, image, or file output of the function tool call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output`. + @frozen public enum OutputPayload: Codable, Hashable, Sendable { + /// A JSON string of the output of the function tool call. /// - /// - Parameters: - /// - value1: - /// - value2: - public init( - value1: Components.Schemas.ApproximateLocation? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output/case1`. + case case1(Swift.String) + /// A piece of message content, such as text, an image, or a file. + /// + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output/Case2Payload`. + @frozen public enum Case2PayloadPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output/Case2Payload/InputTextContentParam`. + case inputTextContentParam(Components.Schemas.InputTextContentParam) + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output/Case2Payload/InputImageContentParamAutoParam`. + case inputImageContentParamAutoParam(Components.Schemas.InputImageContentParamAutoParam) + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output/Case2Payload/InputFileContentParam`. + case inputFileContentParam(Components.Schemas.InputFileContentParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "InputTextContentParam", "#/components/schemas/InputTextContentParam": + self = .inputTextContentParam(try .init(from: decoder)) + case "InputImageContentParamAutoParam", "#/components/schemas/InputImageContentParamAutoParam": + self = .inputImageContentParamAutoParam(try .init(from: decoder)) + case "InputFileContentParam", "#/components/schemas/InputFileContentParam": + self = .inputFileContentParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .inputTextContentParam(value): + try value.encode(to: encoder) + case let .inputImageContentParamAutoParam(value): + try value.encode(to: encoder) + case let .inputFileContentParam(value): + try value.encode(to: encoder) + } + } } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] + /// An array of content outputs (text, image, file) for the function tool call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output/case2`. + public typealias Case2Payload = [Components.Schemas.FunctionCallOutputItemParam.OutputPayload.Case2PayloadPayload] + /// An array of content outputs (text, image, file) for the function tool call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output/case2`. + case case2(Components.Schemas.FunctionCallOutputItemParam.OutputPayload.Case2Payload) + public init(from decoder: any Swift.Decoder) throws { + var errors: [any Swift.Error] = [] do { - self.value1 = try .init(from: decoder) + self = .case1(try decoder.decodeFromSingleValueContainer()) + return } catch { errors.append(error) } do { - self.value2 = try .init(from: decoder) + self = .case2(try decoder.decodeFromSingleValueContainer()) + return } catch { errors.append(error) } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], + throw Swift.DecodingError.failedToDecodeOneOfSchema( type: Self.self, codingPath: decoder.codingPath, errors: errors ) } - public func encode(to encoder: any Encoder) throws { - try self.value1?.encode(to: encoder) - try self.value2?.encode(to: encoder) + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .case1(value): + try encoder.encodeToSingleValueContainer(value) + case let .case2(value): + try encoder.encodeToSingleValueContainer(value) + } } } - /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/user_location`. - public var userLocation: Components.Schemas.WebSearchPreviewTool.UserLocationPayload? - /// 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. - /// - /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/search_context_size`. - @frozen public enum SearchContextSizePayload: String, Codable, Hashable, Sendable, CaseIterable { - case low = "low" - case medium = "medium" - case high = "high" - } - /// 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. + /// Text, image, or file output of the function tool call. /// - /// - Remark: Generated from `#/components/schemas/WebSearchPreviewTool/search_context_size`. - public var searchContextSize: Components.Schemas.WebSearchPreviewTool.SearchContextSizePayload? - /// Creates a new `WebSearchPreviewTool`. + /// - 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: - /// - _type: The type of the web search tool. One of `web_search_preview` or `web_search_preview_2025_03_11`. - /// - 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. + /// - id: + /// - 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. + /// - status: public init( - _type: Components.Schemas.WebSearchPreviewTool._TypePayload, - userLocation: Components.Schemas.WebSearchPreviewTool.UserLocationPayload? = nil, - searchContextSize: Components.Schemas.WebSearchPreviewTool.SearchContextSizePayload? = nil + id: Swift.String? = nil, + callId: Swift.String, + _type: Components.Schemas.FunctionCallOutputItemParam._TypePayload, + output: Components.Schemas.FunctionCallOutputItemParam.OutputPayload, + status: Components.Schemas.FunctionCallItemStatus? = nil ) { + self.id = id + self.callId = callId self._type = _type - self.userLocation = userLocation - self.searchContextSize = searchContextSize + self.output = output + self.status = status } public enum CodingKeys: String, CodingKey { + case id + case callId = "call_id" case _type = "type" - case userLocation = "user_location" - case searchContextSize = "search_context_size" + case output + case status } } - /// A tool that controls a virtual computer. Learn more about the [computer tool](https://platform.openai.com/docs/guides/tools-computer-use). - /// - /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool`. - public struct ComputerUsePreviewTool: Codable, Hashable, Sendable { - /// The type of the computer use tool. Always `computer_use_preview`. + /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam`. + public struct ToolSearchCallItemParam: Codable, Hashable, Sendable { + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/id`. + public var id: Swift.String? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/call_id`. + public var callId: Swift.String? + /// The item type. Always `tool_search_call`. /// - /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/type`. + /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case computerUsePreview = "computer_use_preview" + case toolSearchCall = "tool_search_call" } - /// The type of the computer use tool. Always `computer_use_preview`. + /// The item type. Always `tool_search_call`. /// - /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/type`. - public var _type: Components.Schemas.ComputerUsePreviewTool._TypePayload - /// The type of computer environment to control. + /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/type`. + public var _type: Components.Schemas.ToolSearchCallItemParam._TypePayload + /// Whether tool search was executed by the server or by the client. /// - /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/environment`. - @frozen public enum EnvironmentPayload: String, Codable, Hashable, Sendable, CaseIterable { - case windows = "windows" - case mac = "mac" - case linux = "linux" - case ubuntu = "ubuntu" - case browser = "browser" + /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/execution`. + public var execution: Components.Schemas.ToolSearchExecutionType? + /// The arguments supplied to the tool search call. + /// + /// - 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: + /// - _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. + /// - status: + public init( + id: Swift.String? = nil, + callId: Swift.String? = nil, + _type: Components.Schemas.ToolSearchCallItemParam._TypePayload, + execution: Components.Schemas.ToolSearchExecutionType? = nil, + arguments: Components.Schemas.EmptyModelParam, + status: Components.Schemas.FunctionCallItemStatus? = nil + ) { + self.id = id + self.callId = callId + self._type = _type + self.execution = execution + self.arguments = arguments + self.status = status } - /// The type of computer environment to control. + public enum CodingKeys: String, CodingKey { + case id + case callId = "call_id" + case _type = "type" + case execution + case arguments + case status + } + } + /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam`. + public struct ToolSearchOutputItemParam: Codable, Hashable, Sendable { + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/id`. + public var id: Swift.String? + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/call_id`. + public var callId: Swift.String? + /// The item type. Always `tool_search_output`. /// - /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/environment`. - public var environment: Components.Schemas.ComputerUsePreviewTool.EnvironmentPayload - /// The width of the computer display. + /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case toolSearchOutput = "tool_search_output" + } + /// The item type. Always `tool_search_output`. /// - /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/display_width`. - public var displayWidth: Swift.Int - /// The height of the computer display. + /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/type`. + public var _type: Components.Schemas.ToolSearchOutputItemParam._TypePayload + /// Whether tool search was executed by the server or by the client. /// - /// - Remark: Generated from `#/components/schemas/ComputerUsePreviewTool/display_height`. - public var displayHeight: Swift.Int - /// Creates a new `ComputerUsePreviewTool`. + /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/execution`. + public var execution: Components.Schemas.ToolSearchExecutionType? + /// The loaded tool definitions returned by the tool search output. + /// + /// - 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: - /// - _type: The type of the computer use tool. Always `computer_use_preview`. - /// - environment: The type of computer environment to control. - /// - displayWidth: The width of the computer display. - /// - displayHeight: The height of the computer display. + /// - id: + /// - callId: + /// - _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. + /// - status: public init( - _type: Components.Schemas.ComputerUsePreviewTool._TypePayload, - environment: Components.Schemas.ComputerUsePreviewTool.EnvironmentPayload, - displayWidth: Swift.Int, - displayHeight: Swift.Int + id: Swift.String? = nil, + callId: Swift.String? = nil, + _type: Components.Schemas.ToolSearchOutputItemParam._TypePayload, + execution: Components.Schemas.ToolSearchExecutionType? = nil, + tools: [Components.Schemas.Tool], + status: Components.Schemas.FunctionCallItemStatus? = nil ) { + self.id = id + self.callId = callId self._type = _type - self.environment = environment - self.displayWidth = displayWidth - self.displayHeight = displayHeight + self.execution = execution + self.tools = tools + self.status = status } public enum CodingKeys: String, CodingKey { + case id + case callId = "call_id" case _type = "type" - case environment - case displayWidth = "display_width" - case displayHeight = "display_height" + case execution + case tools + case status } } - /// A citation to a file. + /// A compaction item generated by the [`v1/responses/compact` API](/docs/api-reference/responses/compact). /// - /// - Remark: Generated from `#/components/schemas/FileCitationBody`. - public struct FileCitationBody: Codable, Hashable, Sendable { - /// The type of the file citation. Always `file_citation`. + /// - Remark: Generated from `#/components/schemas/CompactionSummaryItemParam`. + public struct CompactionSummaryItemParam: Codable, Hashable, Sendable { + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/CompactionSummaryItemParam/id`. + public var id: Swift.String? + /// The type of the item. Always `compaction`. /// - /// - Remark: Generated from `#/components/schemas/FileCitationBody/type`. + /// - Remark: Generated from `#/components/schemas/CompactionSummaryItemParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case fileCitation = "file_citation" + case compaction = "compaction" } - /// The type of the file citation. Always `file_citation`. + /// The type of the item. Always `compaction`. /// - /// - Remark: Generated from `#/components/schemas/FileCitationBody/type`. - public var _type: Components.Schemas.FileCitationBody._TypePayload - /// The ID of the file. + /// - Remark: Generated from `#/components/schemas/CompactionSummaryItemParam/type`. + public var _type: Components.Schemas.CompactionSummaryItemParam._TypePayload + /// The encrypted content of the compaction summary. + /// + /// - Remark: Generated from `#/components/schemas/CompactionSummaryItemParam/encrypted_content`. + public var encryptedContent: Swift.String + /// Creates a new `CompactionSummaryItemParam`. + /// + /// - Parameters: + /// - id: + /// - _type: The type of the item. Always `compaction`. + /// - encryptedContent: The encrypted content of the compaction summary. + public init( + id: Swift.String? = nil, + _type: Components.Schemas.CompactionSummaryItemParam._TypePayload, + encryptedContent: Swift.String + ) { + self.id = id + self._type = _type + self.encryptedContent = encryptedContent + } + public enum CodingKeys: String, CodingKey { + case id + case _type = "type" + case encryptedContent = "encrypted_content" + } + } + /// Commands and limits describing how to run the shell tool call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam`. + public struct FunctionShellActionParam: Codable, Hashable, Sendable { + /// Ordered shell commands for the execution environment to run. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/commands`. + public var commands: [Swift.String] + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/timeout_ms`. + public var timeoutMs: Swift.Int? + public typealias Int = Swift.Int + /// - 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: + public init( + commands: [Swift.String], + timeoutMs: Swift.Int? = nil, + maxOutputLength: Swift.Int? = nil + ) { + self.commands = commands + self.timeoutMs = timeoutMs + self.maxOutputLength = maxOutputLength + } + public enum CodingKeys: String, CodingKey { + case commands + case timeoutMs = "timeout_ms" + case maxOutputLength = "max_output_length" + } + } + /// Status values reported for shell tool calls. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemStatus`. + @frozen public enum FunctionShellCallItemStatus: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + case incomplete = "incomplete" + } + /// A tool representing a request to execute one or more shell commands. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam`. + public struct FunctionShellCallItemParam: Codable, Hashable, Sendable { + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/id`. + public var id: Swift.String? + /// The unique ID of the shell tool call generated by the model. /// - /// - Remark: Generated from `#/components/schemas/FileCitationBody/file_id`. - public var fileId: Swift.String - /// The index of the file in the list of files. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/call_id`. + public var callId: Swift.String + /// The type of the item. Always `shell_call`. /// - /// - Remark: Generated from `#/components/schemas/FileCitationBody/index`. - public var index: Swift.Int - /// Creates a new `FileCitationBody`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case shellCall = "shell_call" + } + /// The type of the item. Always `shell_call`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/type`. + public var _type: Components.Schemas.FunctionShellCallItemParam._TypePayload + /// The shell commands and limits that describe how to run the tool call. + /// + /// - 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. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/environment`. + @frozen public enum EnvironmentPayload: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/environment/LocalEnvironmentParam`. + case localEnvironmentParam(Components.Schemas.LocalEnvironmentParam) + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/environment/ContainerReferenceParam`. + case containerReferenceParam(Components.Schemas.ContainerReferenceParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "LocalEnvironmentParam", "#/components/schemas/LocalEnvironmentParam": + self = .localEnvironmentParam(try .init(from: decoder)) + case "ContainerReferenceParam", "#/components/schemas/ContainerReferenceParam": + self = .containerReferenceParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath + ) + } + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .localEnvironmentParam(value): + try value.encode(to: encoder) + case let .containerReferenceParam(value): + try value.encode(to: encoder) + } + } + } + /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/environment`. + public var environment: Components.Schemas.FunctionShellCallItemParam.EnvironmentPayload? + /// Creates a new `FunctionShellCallItemParam`. /// /// - Parameters: - /// - _type: The type of the file citation. Always `file_citation`. - /// - fileId: The ID of the file. - /// - index: The index of the file in the list of files. + /// - id: + /// - 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: public init( - _type: Components.Schemas.FileCitationBody._TypePayload, - fileId: Swift.String, - index: Swift.Int + id: Swift.String? = nil, + callId: Swift.String, + _type: Components.Schemas.FunctionShellCallItemParam._TypePayload, + action: Components.Schemas.FunctionShellActionParam, + status: Components.Schemas.FunctionShellCallItemStatus? = nil, + environment: Components.Schemas.FunctionShellCallItemParam.EnvironmentPayload? = nil ) { + self.id = id + self.callId = callId self._type = _type - self.fileId = fileId - self.index = index + self.action = action + self.status = status + self.environment = environment } public enum CodingKeys: String, CodingKey { + case id + case callId = "call_id" case _type = "type" - case fileId = "file_id" - case index + case action + case status + case environment } } - /// A citation for a web resource used to generate a model response. + /// Indicates that the shell call exceeded its configured time limit. /// - /// - Remark: Generated from `#/components/schemas/UrlCitationBody`. - public struct UrlCitationBody: Codable, Hashable, Sendable { - /// The type of the URL citation. Always `url_citation`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam`. + public struct FunctionShellCallOutputTimeoutOutcomeParam: Codable, Hashable, Sendable { + /// The outcome type. Always `timeout`. /// - /// - Remark: Generated from `#/components/schemas/UrlCitationBody/type`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case urlCitation = "url_citation" + case timeout = "timeout" } - /// The type of the URL citation. Always `url_citation`. + /// The outcome type. Always `timeout`. /// - /// - Remark: Generated from `#/components/schemas/UrlCitationBody/type`. - public var _type: Components.Schemas.UrlCitationBody._TypePayload - /// The URL of the web resource. - /// - /// - Remark: Generated from `#/components/schemas/UrlCitationBody/url`. - public var url: Swift.String - /// The index of the first character of the URL citation in the message. - /// - /// - Remark: Generated from `#/components/schemas/UrlCitationBody/start_index`. - public var startIndex: Swift.Int - /// The index of the last character of the URL citation in the message. - /// - /// - Remark: Generated from `#/components/schemas/UrlCitationBody/end_index`. - public var endIndex: Swift.Int - /// The title of the web resource. - /// - /// - Remark: Generated from `#/components/schemas/UrlCitationBody/title`. - public var title: Swift.String - /// Creates a new `UrlCitationBody`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam/type`. + public var _type: Components.Schemas.FunctionShellCallOutputTimeoutOutcomeParam._TypePayload + /// Creates a new `FunctionShellCallOutputTimeoutOutcomeParam`. /// /// - Parameters: - /// - _type: The type of the URL citation. Always `url_citation`. - /// - url: The URL of the web resource. - /// - startIndex: The index of the first character of the URL citation in the message. - /// - endIndex: The index of the last character of the URL citation in the message. - /// - title: The title of the web resource. - public init( - _type: Components.Schemas.UrlCitationBody._TypePayload, - url: Swift.String, - startIndex: Swift.Int, - endIndex: Swift.Int, - title: Swift.String - ) { + /// - _type: The outcome type. Always `timeout`. + public init(_type: Components.Schemas.FunctionShellCallOutputTimeoutOutcomeParam._TypePayload) { self._type = _type - self.url = url - self.startIndex = startIndex - self.endIndex = endIndex - self.title = title } public enum CodingKeys: String, CodingKey { case _type = "type" - case url - case startIndex = "start_index" - case endIndex = "end_index" - case title } } - /// A citation for a container file used to generate a model response. + /// Indicates that the shell commands finished and returned an exit code. /// - /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody`. - public struct ContainerFileCitationBody: Codable, Hashable, Sendable { - /// The type of the container file citation. Always `container_file_citation`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputExitOutcomeParam`. + public struct FunctionShellCallOutputExitOutcomeParam: Codable, Hashable, Sendable { + /// The outcome type. Always `exit`. /// - /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/type`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputExitOutcomeParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case containerFileCitation = "container_file_citation" + case exit = "exit" } - /// The type of the container file citation. Always `container_file_citation`. - /// - /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/type`. - public var _type: Components.Schemas.ContainerFileCitationBody._TypePayload - /// The ID of the container file. - /// - /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/container_id`. - public var containerId: Swift.String - /// The ID of the file. - /// - /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/file_id`. - public var fileId: Swift.String - /// The index of the first character of the container file citation in the message. + /// The outcome type. Always `exit`. /// - /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/start_index`. - public var startIndex: Swift.Int - /// The index of the last character of the container file citation in the message. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputExitOutcomeParam/type`. + public var _type: Components.Schemas.FunctionShellCallOutputExitOutcomeParam._TypePayload + /// The exit code returned by the shell process. /// - /// - Remark: Generated from `#/components/schemas/ContainerFileCitationBody/end_index`. - public var endIndex: Swift.Int - /// Creates a new `ContainerFileCitationBody`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputExitOutcomeParam/exit_code`. + public var exitCode: Swift.Int + /// Creates a new `FunctionShellCallOutputExitOutcomeParam`. /// /// - Parameters: - /// - _type: The type of the container file citation. Always `container_file_citation`. - /// - containerId: The ID of the container file. - /// - fileId: The ID of the file. - /// - startIndex: The index of the first character of the container file citation in the message. - /// - endIndex: The index of the last character of the container file citation in the message. + /// - _type: The outcome type. Always `exit`. + /// - exitCode: The exit code returned by the shell process. public init( - _type: Components.Schemas.ContainerFileCitationBody._TypePayload, - containerId: Swift.String, - fileId: Swift.String, - startIndex: Swift.Int, - endIndex: Swift.Int + _type: Components.Schemas.FunctionShellCallOutputExitOutcomeParam._TypePayload, + exitCode: Swift.Int ) { self._type = _type - self.containerId = containerId - self.fileId = fileId - self.startIndex = startIndex - self.endIndex = endIndex + self.exitCode = exitCode } public enum CodingKeys: String, CodingKey { case _type = "type" - case containerId = "container_id" - case fileId = "file_id" - case startIndex = "start_index" - case endIndex = "end_index" + case exitCode = "exit_code" } } - /// - Remark: Generated from `#/components/schemas/Annotation`. - @frozen public enum Annotation: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/Annotation/FileCitationBody`. - case fileCitationBody(Components.Schemas.FileCitationBody) - /// - Remark: Generated from `#/components/schemas/Annotation/UrlCitationBody`. - case urlCitationBody(Components.Schemas.UrlCitationBody) - /// - Remark: Generated from `#/components/schemas/Annotation/ContainerFileCitationBody`. - case containerFileCitationBody(Components.Schemas.ContainerFileCitationBody) - /// - Remark: Generated from `#/components/schemas/Annotation/FilePath`. - case filePath(Components.Schemas.FilePath) + /// The exit or timeout outcome associated with this shell call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputOutcomeParam`. + @frozen public enum FunctionShellCallOutputOutcomeParam: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputOutcomeParam/FunctionShellCallOutputTimeoutOutcomeParam`. + case functionShellCallOutputTimeoutOutcomeParam(Components.Schemas.FunctionShellCallOutputTimeoutOutcomeParam) + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputOutcomeParam/FunctionShellCallOutputExitOutcomeParam`. + case functionShellCallOutputExitOutcomeParam(Components.Schemas.FunctionShellCallOutputExitOutcomeParam) public enum CodingKeys: String, CodingKey { case _type = "type" } - public init(from decoder: any Decoder) throws { + public init(from decoder: any Swift.Decoder) throws { let container = try decoder.container(keyedBy: CodingKeys.self) let discriminator = try container.decode( Swift.String.self, forKey: ._type ) switch discriminator { - case "file_citation", "#/components/schemas/FileCitationBody": - self = .fileCitationBody(try .init(from: decoder)) - case "url_citation", "#/components/schemas/UrlCitationBody": - self = .urlCitationBody(try .init(from: decoder)) - case "container_file_citation", "#/components/schemas/ContainerFileCitationBody": - self = .containerFileCitationBody(try .init(from: decoder)) - case "file_path", "#/components/schemas/FilePath": - self = .filePath(try .init(from: decoder)) + case "FunctionShellCallOutputTimeoutOutcomeParam", "#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam": + self = .functionShellCallOutputTimeoutOutcomeParam(try .init(from: decoder)) + case "FunctionShellCallOutputExitOutcomeParam", "#/components/schemas/FunctionShellCallOutputExitOutcomeParam": + self = .functionShellCallOutputExitOutcomeParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( discriminatorKey: CodingKeys._type, @@ -11867,735 +16611,421 @@ public enum Components { ) } } - public func encode(to encoder: any Encoder) throws { + public func encode(to encoder: any Swift.Encoder) throws { switch self { - case let .fileCitationBody(value): - try value.encode(to: encoder) - case let .urlCitationBody(value): - try value.encode(to: encoder) - case let .containerFileCitationBody(value): + case let .functionShellCallOutputTimeoutOutcomeParam(value): try value.encode(to: encoder) - case let .filePath(value): + case let .functionShellCallOutputExitOutcomeParam(value): try value.encode(to: encoder) } } } - /// The top log probability of a token. + /// Captured stdout and stderr for a portion of a shell tool call output. /// - /// - Remark: Generated from `#/components/schemas/TopLogProb`. - public struct TopLogProb: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/TopLogProb/token`. - public var token: Swift.String - /// - Remark: Generated from `#/components/schemas/TopLogProb/logprob`. - public var logprob: Swift.Double - /// - Remark: Generated from `#/components/schemas/TopLogProb/bytes`. - public var bytes: [Swift.Int] - /// Creates a new `TopLogProb`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContentParam`. + public struct FunctionShellCallOutputContentParam: Codable, Hashable, Sendable { + /// Captured stdout output for the shell call. /// - /// - Parameters: - /// - token: - /// - logprob: - /// - bytes: - public init( - token: Swift.String, - logprob: Swift.Double, - bytes: [Swift.Int] - ) { - self.token = token - self.logprob = logprob - self.bytes = bytes - } - public enum CodingKeys: String, CodingKey { - case token - case logprob - case bytes - } - } - /// The log probability of a token. - /// - /// - Remark: Generated from `#/components/schemas/LogProb`. - public struct LogProb: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/LogProb/token`. - public var token: Swift.String - /// - Remark: Generated from `#/components/schemas/LogProb/logprob`. - public var logprob: Swift.Double - /// - Remark: Generated from `#/components/schemas/LogProb/bytes`. - public var bytes: [Swift.Int] - /// - Remark: Generated from `#/components/schemas/LogProb/top_logprobs`. - public var topLogprobs: [Components.Schemas.TopLogProb] - /// Creates a new `LogProb`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContentParam/stdout`. + public var stdout: Swift.String + /// Captured stderr output for the shell call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContentParam/stderr`. + public var stderr: Swift.String + /// The exit or timeout outcome associated with this shell call. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputContentParam/outcome`. + public var outcome: Components.Schemas.FunctionShellCallOutputOutcomeParam + /// Creates a new `FunctionShellCallOutputContentParam`. /// /// - Parameters: - /// - token: - /// - logprob: - /// - bytes: - /// - topLogprobs: + /// - stdout: Captured stdout output for the shell call. + /// - stderr: Captured stderr output for the shell call. + /// - outcome: The exit or timeout outcome associated with this shell call. public init( - token: Swift.String, - logprob: Swift.Double, - bytes: [Swift.Int], - topLogprobs: [Components.Schemas.TopLogProb] + stdout: Swift.String, + stderr: Swift.String, + outcome: Components.Schemas.FunctionShellCallOutputOutcomeParam ) { - self.token = token - self.logprob = logprob - self.bytes = bytes - self.topLogprobs = topLogprobs + self.stdout = stdout + self.stderr = stderr + self.outcome = outcome } public enum CodingKeys: String, CodingKey { - case token - case logprob - case bytes - case topLogprobs = "top_logprobs" + case stdout + case stderr + case outcome } } - /// A text output from the model. + /// The streamed output items emitted by a shell tool call. /// - /// - Remark: Generated from `#/components/schemas/OutputTextContent`. - public struct OutputTextContent: Codable, Hashable, Sendable { - /// The type of the output text. Always `output_text`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam`. + public struct FunctionShellCallOutputItemParam: Codable, Hashable, Sendable { + public typealias String = Swift.String + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/id`. + public var id: Swift.String? + /// The unique ID of the shell tool call generated by the model. /// - /// - Remark: Generated from `#/components/schemas/OutputTextContent/type`. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/call_id`. + public var callId: Swift.String + /// The type of the item. Always `shell_call_output`. + /// + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case outputText = "output_text" + case shellCallOutput = "shell_call_output" } - /// The type of the output text. Always `output_text`. - /// - /// - Remark: Generated from `#/components/schemas/OutputTextContent/type`. - public var _type: Components.Schemas.OutputTextContent._TypePayload - /// The text output from the model. + /// The type of the item. Always `shell_call_output`. /// - /// - Remark: Generated from `#/components/schemas/OutputTextContent/text`. - public var text: Swift.String - /// The annotations of the text output. + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/type`. + public var _type: Components.Schemas.FunctionShellCallOutputItemParam._TypePayload + /// Captured chunks of stdout and stderr output, along with their associated outcomes. /// - /// - Remark: Generated from `#/components/schemas/OutputTextContent/annotations`. - public var annotations: [Components.Schemas.Annotation] - /// - Remark: Generated from `#/components/schemas/OutputTextContent/logprobs`. - public var logprobs: [Components.Schemas.LogProb]? - /// Creates a new `OutputTextContent`. + /// - 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? + public typealias Int = Swift.Int + /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/max_output_length`. + public var maxOutputLength: Swift.Int? + /// Creates a new `FunctionShellCallOutputItemParam`. /// /// - Parameters: - /// - _type: The type of the output text. Always `output_text`. - /// - text: The text output from the model. - /// - annotations: The annotations of the text output. - /// - logprobs: + /// - id: + /// - 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: public init( - _type: Components.Schemas.OutputTextContent._TypePayload, - text: Swift.String, - annotations: [Components.Schemas.Annotation], - logprobs: [Components.Schemas.LogProb]? = nil + id: Swift.String? = nil, + callId: Swift.String, + _type: Components.Schemas.FunctionShellCallOutputItemParam._TypePayload, + output: [Components.Schemas.FunctionShellCallOutputContentParam], + status: Components.Schemas.FunctionShellCallItemStatus? = nil, + maxOutputLength: Swift.Int? = nil ) { + self.id = id + self.callId = callId self._type = _type - self.text = text - self.annotations = annotations - self.logprobs = logprobs + self.output = output + self.status = status + self.maxOutputLength = maxOutputLength } public enum CodingKeys: String, CodingKey { + case id + case callId = "call_id" case _type = "type" - case text - case annotations - case logprobs + case output + case status + case maxOutputLength = "max_output_length" } } - /// A refusal from the model. + /// Status values reported for apply_patch tool calls. /// - /// - Remark: Generated from `#/components/schemas/RefusalContent`. - public struct RefusalContent: Codable, Hashable, Sendable { - /// The type of the refusal. Always `refusal`. + /// - Remark: Generated from `#/components/schemas/ApplyPatchCallStatusParam`. + @frozen public enum ApplyPatchCallStatusParam: String, Codable, Hashable, Sendable, CaseIterable { + case inProgress = "in_progress" + case completed = "completed" + } + /// Instruction for creating a new file via the apply_patch tool. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperationParam`. + public struct ApplyPatchCreateFileOperationParam: Codable, Hashable, Sendable { + /// The operation type. Always `create_file`. /// - /// - Remark: Generated from `#/components/schemas/RefusalContent/type`. + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperationParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case refusal = "refusal" + case createFile = "create_file" } - /// The type of the refusal. Always `refusal`. + /// The operation type. Always `create_file`. /// - /// - Remark: Generated from `#/components/schemas/RefusalContent/type`. - public var _type: Components.Schemas.RefusalContent._TypePayload - /// The refusal explanationfrom the model. + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperationParam/type`. + public var _type: Components.Schemas.ApplyPatchCreateFileOperationParam._TypePayload + /// Path of the file to create relative to the workspace root. /// - /// - Remark: Generated from `#/components/schemas/RefusalContent/refusal`. - public var refusal: Swift.String - /// Creates a new `RefusalContent`. + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperationParam/path`. + public var path: Swift.String + /// Unified diff content to apply when creating the file. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchCreateFileOperationParam/diff`. + public var diff: Swift.String + /// Creates a new `ApplyPatchCreateFileOperationParam`. /// /// - Parameters: - /// - _type: The type of the refusal. Always `refusal`. - /// - refusal: The refusal explanationfrom the model. + /// - _type: The operation type. Always `create_file`. + /// - path: Path of the file to create relative to the workspace root. + /// - diff: Unified diff content to apply when creating the file. public init( - _type: Components.Schemas.RefusalContent._TypePayload, - refusal: Swift.String + _type: Components.Schemas.ApplyPatchCreateFileOperationParam._TypePayload, + path: Swift.String, + diff: Swift.String ) { self._type = _type - self.refusal = refusal + self.path = path + self.diff = diff } public enum CodingKeys: String, CodingKey { case _type = "type" - case refusal + case path + case diff } } - /// A pending safety check for the computer call. + /// Instruction for deleting an existing file via the apply_patch tool. /// - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam`. - public struct ComputerCallSafetyCheckParam: Codable, Hashable, Sendable { - /// The ID of the pending safety check. + /// - Remark: Generated from `#/components/schemas/ApplyPatchDeleteFileOperationParam`. + public struct ApplyPatchDeleteFileOperationParam: Codable, Hashable, Sendable { + /// The operation type. Always `delete_file`. /// - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/id`. - public var id: Swift.String - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/code`. - public struct CodePayload: Codable, Hashable, Sendable { - /// The type of the pending safety check. - /// - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/code/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/code/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `CodePayload`. - /// - /// - Parameters: - /// - value1: The type of the pending safety check. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/code`. - public var code: Components.Schemas.ComputerCallSafetyCheckParam.CodePayload? - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/message`. - public struct MessagePayload: Codable, Hashable, Sendable { - /// Details about the pending safety check. - /// - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/message/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/message/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `MessagePayload`. - /// - /// - Parameters: - /// - value1: Details about the pending safety check. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + /// - Remark: Generated from `#/components/schemas/ApplyPatchDeleteFileOperationParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case deleteFile = "delete_file" } - /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/message`. - public var message: Components.Schemas.ComputerCallSafetyCheckParam.MessagePayload? - /// Creates a new `ComputerCallSafetyCheckParam`. + /// The operation type. Always `delete_file`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchDeleteFileOperationParam/type`. + public var _type: Components.Schemas.ApplyPatchDeleteFileOperationParam._TypePayload + /// Path of the file to delete relative to the workspace root. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchDeleteFileOperationParam/path`. + public var path: Swift.String + /// Creates a new `ApplyPatchDeleteFileOperationParam`. /// /// - Parameters: - /// - id: The ID of the pending safety check. - /// - code: - /// - message: + /// - _type: The operation type. Always `delete_file`. + /// - path: Path of the file to delete relative to the workspace root. public init( - id: Swift.String, - code: Components.Schemas.ComputerCallSafetyCheckParam.CodePayload? = nil, - message: Components.Schemas.ComputerCallSafetyCheckParam.MessagePayload? = nil + _type: Components.Schemas.ApplyPatchDeleteFileOperationParam._TypePayload, + path: Swift.String ) { - self.id = id - self.code = code - self.message = message + self._type = _type + self.path = path } public enum CodingKeys: String, CodingKey { - case id - case code - case message + case _type = "type" + case path } } - /// The output of a computer tool call. + /// Instruction for updating an existing file via the apply_patch tool. /// - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam`. - public struct ComputerCallOutputItemParam: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/id`. - public struct IdPayload: Codable, Hashable, Sendable { - /// The ID of the computer tool call output. - /// - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/id/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/id/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `IdPayload`. - /// - /// - Parameters: - /// - value1: The ID of the computer tool call output. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/id`. - public var id: Components.Schemas.ComputerCallOutputItemParam.IdPayload? - /// The ID of the computer tool call that produced the output. - /// - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/call_id`. - public var callId: Swift.String - /// The type of the computer tool call output. Always `computer_call_output`. + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperationParam`. + public struct ApplyPatchUpdateFileOperationParam: Codable, Hashable, Sendable { + /// The operation type. Always `update_file`. /// - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/type`. + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperationParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case computerCallOutput = "computer_call_output" + case updateFile = "update_file" } - /// The type of the computer tool call output. Always `computer_call_output`. + /// The operation type. Always `update_file`. /// - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/type`. - 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/ComputerCallOutputItemParam/acknowledged_safety_checks`. - public struct AcknowledgedSafetyChecksPayload: Codable, Hashable, Sendable { - /// The safety checks reported by the API that have been acknowledged by the developer. - /// - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/acknowledged_safety_checks/value1`. - public var value1: [Components.Schemas.ComputerCallSafetyCheckParam]? - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/acknowledged_safety_checks/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `AcknowledgedSafetyChecksPayload`. - /// - /// - Parameters: - /// - value1: The safety checks reported by the API that have been acknowledged by the developer. - /// - value2: - public init( - value1: [Components.Schemas.ComputerCallSafetyCheckParam]? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperationParam/type`. + public var _type: Components.Schemas.ApplyPatchUpdateFileOperationParam._TypePayload + /// Path of the file to update relative to the workspace root. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperationParam/path`. + public var path: Swift.String + /// Unified diff content to apply to the existing file. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchUpdateFileOperationParam/diff`. + public var diff: Swift.String + /// Creates a new `ApplyPatchUpdateFileOperationParam`. + /// + /// - Parameters: + /// - _type: The operation type. Always `update_file`. + /// - path: Path of the file to update relative to the workspace root. + /// - diff: Unified diff content to apply to the existing file. + public init( + _type: Components.Schemas.ApplyPatchUpdateFileOperationParam._TypePayload, + path: Swift.String, + diff: Swift.String + ) { + self._type = _type + self.path = path + self.diff = diff } - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/acknowledged_safety_checks`. - public var acknowledgedSafetyChecks: Components.Schemas.ComputerCallOutputItemParam.AcknowledgedSafetyChecksPayload? - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/status`. - public struct StatusPayload: Codable, Hashable, Sendable { - /// The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API. - /// - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/status/value1`. - @frozen public enum Value1Payload: String, Codable, Hashable, Sendable, CaseIterable { - case inProgress = "in_progress" - case completed = "completed" - case incomplete = "incomplete" - } - /// The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API. - /// - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/status/value1`. - public var value1: Components.Schemas.ComputerCallOutputItemParam.StatusPayload.Value1Payload? - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/status/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `StatusPayload`. - /// - /// - Parameters: - /// - value1: The status of the message input. One of `in_progress`, `completed`, or `incomplete`. Populated when input items are returned via API. - /// - value2: - public init( - value1: Components.Schemas.ComputerCallOutputItemParam.StatusPayload.Value1Payload? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors + public enum CodingKeys: String, CodingKey { + case _type = "type" + case path + case diff + } + } + /// One of the create_file, delete_file, or update_file operations supplied to the apply_patch tool. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchOperationParam`. + @frozen public enum ApplyPatchOperationParam: Codable, Hashable, Sendable { + /// - Remark: Generated from `#/components/schemas/ApplyPatchOperationParam/ApplyPatchCreateFileOperationParam`. + case applyPatchCreateFileOperationParam(Components.Schemas.ApplyPatchCreateFileOperationParam) + /// - Remark: Generated from `#/components/schemas/ApplyPatchOperationParam/ApplyPatchDeleteFileOperationParam`. + case applyPatchDeleteFileOperationParam(Components.Schemas.ApplyPatchDeleteFileOperationParam) + /// - Remark: Generated from `#/components/schemas/ApplyPatchOperationParam/ApplyPatchUpdateFileOperationParam`. + case applyPatchUpdateFileOperationParam(Components.Schemas.ApplyPatchUpdateFileOperationParam) + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + public init(from decoder: any Swift.Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + let discriminator = try container.decode( + Swift.String.self, + forKey: ._type + ) + switch discriminator { + case "ApplyPatchCreateFileOperationParam", "#/components/schemas/ApplyPatchCreateFileOperationParam": + self = .applyPatchCreateFileOperationParam(try .init(from: decoder)) + case "ApplyPatchDeleteFileOperationParam", "#/components/schemas/ApplyPatchDeleteFileOperationParam": + self = .applyPatchDeleteFileOperationParam(try .init(from: decoder)) + case "ApplyPatchUpdateFileOperationParam", "#/components/schemas/ApplyPatchUpdateFileOperationParam": + self = .applyPatchUpdateFileOperationParam(try .init(from: decoder)) + default: + throw Swift.DecodingError.unknownOneOfDiscriminator( + discriminatorKey: CodingKeys._type, + discriminatorValue: discriminator, + codingPath: decoder.codingPath ) } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) + } + public func encode(to encoder: any Swift.Encoder) throws { + switch self { + case let .applyPatchCreateFileOperationParam(value): + try value.encode(to: encoder) + case let .applyPatchDeleteFileOperationParam(value): + try value.encode(to: encoder) + case let .applyPatchUpdateFileOperationParam(value): + try value.encode(to: encoder) } } - /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/status`. - public var status: Components.Schemas.ComputerCallOutputItemParam.StatusPayload? - /// Creates a new `ComputerCallOutputItemParam`. + } + /// A tool call representing a request to create, delete, or update files using diff patches. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallItemParam`. + public struct ApplyPatchToolCallItemParam: Codable, Hashable, Sendable { + /// The type of the item. Always `apply_patch_call`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallItemParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case applyPatchCall = "apply_patch_call" + } + /// The type of the item. Always `apply_patch_call`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallItemParam/type`. + public var _type: Components.Schemas.ApplyPatchToolCallItemParam._TypePayload + public typealias String = Swift.String + /// - 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. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallItemParam/call_id`. + public var callId: Swift.String + /// The status of the apply patch tool call. One of `in_progress` or `completed`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallItemParam/status`. + public var status: Components.Schemas.ApplyPatchCallStatusParam + /// The specific create, delete, or update instruction for the apply_patch tool call. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallItemParam/operation`. + public var operation: Components.Schemas.ApplyPatchOperationParam + /// Creates a new `ApplyPatchToolCallItemParam`. /// /// - Parameters: + /// - _type: The type of the item. Always `apply_patch_call`. /// - id: - /// - 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: - /// - status: + /// - 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. public init( - id: Components.Schemas.ComputerCallOutputItemParam.IdPayload? = nil, + _type: Components.Schemas.ApplyPatchToolCallItemParam._TypePayload, + id: Swift.String? = nil, callId: Swift.String, - _type: Components.Schemas.ComputerCallOutputItemParam._TypePayload, - output: Components.Schemas.ComputerScreenshotImage, - acknowledgedSafetyChecks: Components.Schemas.ComputerCallOutputItemParam.AcknowledgedSafetyChecksPayload? = nil, - status: Components.Schemas.ComputerCallOutputItemParam.StatusPayload? = nil + status: Components.Schemas.ApplyPatchCallStatusParam, + operation: Components.Schemas.ApplyPatchOperationParam ) { + self._type = _type self.id = id self.callId = callId - self._type = _type - self.output = output - self.acknowledgedSafetyChecks = acknowledgedSafetyChecks self.status = status + self.operation = operation } public enum CodingKeys: String, CodingKey { + case _type = "type" case id case callId = "call_id" - case _type = "type" - case output - case acknowledgedSafetyChecks = "acknowledged_safety_checks" case status + case operation } } - /// The output of a function tool call. + /// Outcome values reported for apply_patch tool call outputs. /// - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam`. - public struct FunctionCallOutputItemParam: Codable, Hashable, Sendable { - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/id`. - public struct IdPayload: 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/value1`. - public var value1: Swift.String? - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/id/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `IdPayload`. - /// - /// - Parameters: - /// - value1: The unique ID of the function tool call output. Populated when this item is returned via API. - /// - value2: - public init( - value1: Swift.String? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/id`. - public var id: Components.Schemas.FunctionCallOutputItemParam.IdPayload? - /// The unique ID of the function tool call generated by the model. - /// - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/call_id`. - public var callId: Swift.String - /// The type of the function tool call output. Always `function_call_output`. + /// - Remark: Generated from `#/components/schemas/ApplyPatchCallOutputStatusParam`. + @frozen public enum ApplyPatchCallOutputStatusParam: String, Codable, Hashable, Sendable, CaseIterable { + case completed = "completed" + case failed = "failed" + } + /// The streamed output emitted by an apply patch tool call. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam`. + public struct ApplyPatchToolCallOutputItemParam: Codable, Hashable, Sendable { + /// The type of the item. Always `apply_patch_call_output`. /// - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/type`. + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/type`. @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { - case functionCallOutput = "function_call_output" + case applyPatchCallOutput = "apply_patch_call_output" } - /// The type of the function tool call output. Always `function_call_output`. + /// The type of the item. Always `apply_patch_call_output`. /// - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/type`. - public var _type: Components.Schemas.FunctionCallOutputItemParam._TypePayload - /// A JSON string of the output of the function tool call. + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/type`. + public var _type: Components.Schemas.ApplyPatchToolCallOutputItemParam._TypePayload + public typealias String = Swift.String + /// - 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. /// - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/output`. - public var output: Swift.String - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/status`. - public struct StatusPayload: Codable, Hashable, Sendable { - /// The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. - /// - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/status/value1`. - @frozen public enum Value1Payload: String, Codable, Hashable, Sendable, CaseIterable { - case inProgress = "in_progress" - case completed = "completed" - case incomplete = "incomplete" - } - /// The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. - /// - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/status/value1`. - public var value1: Components.Schemas.FunctionCallOutputItemParam.StatusPayload.Value1Payload? - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/status/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `StatusPayload`. - /// - /// - Parameters: - /// - value1: The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated when items are returned via API. - /// - value2: - public init( - value1: Components.Schemas.FunctionCallOutputItemParam.StatusPayload.Value1Payload? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } - } - /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/status`. - public var status: Components.Schemas.FunctionCallOutputItemParam.StatusPayload? - /// Creates a new `FunctionCallOutputItemParam`. + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/call_id`. + public var callId: Swift.String + /// The status of the apply patch tool call output. One of `completed` or `failed`. + /// + /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/status`. + public var status: Components.Schemas.ApplyPatchCallOutputStatusParam + public typealias String = Swift.String + /// - 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: - /// - 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: A JSON string of the output of the function tool call. - /// - status: + /// - 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: public init( - id: Components.Schemas.FunctionCallOutputItemParam.IdPayload? = nil, + _type: Components.Schemas.ApplyPatchToolCallOutputItemParam._TypePayload, + id: Swift.String? = nil, callId: Swift.String, - _type: Components.Schemas.FunctionCallOutputItemParam._TypePayload, - output: Swift.String, - status: Components.Schemas.FunctionCallOutputItemParam.StatusPayload? = nil + status: Components.Schemas.ApplyPatchCallOutputStatusParam, + output: Swift.String? = nil ) { + self._type = _type self.id = id self.callId = callId - self._type = _type - self.output = output self.status = status + self.output = output } public enum CodingKeys: String, CodingKey { + case _type = "type" case id case callId = "call_id" - case _type = "type" - case output case status + case output } } /// An internal identifier for an item to reference. /// /// - Remark: Generated from `#/components/schemas/ItemReferenceParam`. public struct ItemReferenceParam: Codable, Hashable, Sendable { + /// The type of item to reference. Always `item_reference`. + /// /// - Remark: Generated from `#/components/schemas/ItemReferenceParam/type`. - public struct _TypePayload: Codable, Hashable, Sendable { - /// The type of item to reference. Always `item_reference`. - /// - /// - Remark: Generated from `#/components/schemas/ItemReferenceParam/type/value1`. - @frozen public enum Value1Payload: 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/value1`. - public var value1: Components.Schemas.ItemReferenceParam._TypePayload.Value1Payload? - /// - Remark: Generated from `#/components/schemas/ItemReferenceParam/type/value2`. - public var value2: OpenAPIRuntime.OpenAPIValueContainer? - /// Creates a new `_TypePayload`. - /// - /// - Parameters: - /// - value1: The type of item to reference. Always `item_reference`. - /// - value2: - public init( - value1: Components.Schemas.ItemReferenceParam._TypePayload.Value1Payload? = nil, - value2: OpenAPIRuntime.OpenAPIValueContainer? = nil - ) { - self.value1 = value1 - self.value2 = value2 - } - public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { - self.value1 = try decoder.decodeFromSingleValueContainer() - } catch { - errors.append(error) - } - do { - self.value2 = try .init(from: decoder) - } catch { - errors.append(error) - } - try Swift.DecodingError.verifyAtLeastOneSchemaIsNotNil( - [ - self.value1, - self.value2 - ], - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) - } - public func encode(to encoder: any Encoder) throws { - try encoder.encodeFirstNonNilValueToSingleValueContainer([ - self.value1 - ]) - try self.value2?.encode(to: encoder) - } + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case itemReference = "item_reference" } /// - Remark: Generated from `#/components/schemas/ItemReferenceParam/type`. public var _type: Components.Schemas.ItemReferenceParam._TypePayload? @@ -12620,6 +17050,120 @@ public enum Components { case id } } + /// Forces the model to call the apply_patch tool when executing a tool call. + /// + /// - Remark: Generated from `#/components/schemas/SpecificApplyPatchParam`. + public struct SpecificApplyPatchParam: Codable, Hashable, Sendable { + /// The tool to call. Always `apply_patch`. + /// + /// - Remark: Generated from `#/components/schemas/SpecificApplyPatchParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case applyPatch = "apply_patch" + } + /// The tool to call. Always `apply_patch`. + /// + /// - Remark: Generated from `#/components/schemas/SpecificApplyPatchParam/type`. + public var _type: Components.Schemas.SpecificApplyPatchParam._TypePayload + /// Creates a new `SpecificApplyPatchParam`. + /// + /// - Parameters: + /// - _type: The tool to call. Always `apply_patch`. + public init(_type: Components.Schemas.SpecificApplyPatchParam._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// Forces the model to call the shell tool when a tool call is required. + /// + /// - Remark: Generated from `#/components/schemas/SpecificFunctionShellParam`. + public struct SpecificFunctionShellParam: Codable, Hashable, Sendable { + /// The tool to call. Always `shell`. + /// + /// - Remark: Generated from `#/components/schemas/SpecificFunctionShellParam/type`. + @frozen public enum _TypePayload: String, Codable, Hashable, Sendable, CaseIterable { + case shell = "shell" + } + /// The tool to call. Always `shell`. + /// + /// - Remark: Generated from `#/components/schemas/SpecificFunctionShellParam/type`. + public var _type: Components.Schemas.SpecificFunctionShellParam._TypePayload + /// Creates a new `SpecificFunctionShellParam`. + /// + /// - Parameters: + /// - _type: The tool to call. Always `shell`. + public init(_type: Components.Schemas.SpecificFunctionShellParam._TypePayload) { + self._type = _type + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + } + } + /// The conversation that this response belongs to. + /// + /// - Remark: Generated from `#/components/schemas/ConversationParam-2`. + public struct ConversationParam2: Codable, Hashable, Sendable { + /// The unique ID of the conversation. + /// + /// - Remark: Generated from `#/components/schemas/ConversationParam-2/id`. + public var id: Swift.String + /// Creates a new `ConversationParam2`. + /// + /// - Parameters: + /// - id: The unique ID of the conversation. + public init(id: Swift.String) { + self.id = id + } + public enum CodingKeys: String, CodingKey { + case id + } + } + /// - Remark: Generated from `#/components/schemas/ContextManagementParam`. + public struct ContextManagementParam: Codable, Hashable, Sendable { + /// The context management entry type. Currently only 'compaction' is supported. + /// + /// - Remark: Generated from `#/components/schemas/ContextManagementParam/type`. + public var _type: Swift.String + public typealias Int = Swift.Int + /// - 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: + public init( + _type: Swift.String, + compactThreshold: Swift.Int? = nil + ) { + self._type = _type + self.compactThreshold = compactThreshold + } + public enum CodingKeys: String, CodingKey { + case _type = "type" + case compactThreshold = "compact_threshold" + } + } + /// The conversation that this response belonged to. Input items and output items from this response were automatically added to this conversation. + /// + /// - Remark: Generated from `#/components/schemas/Conversation-2`. + public struct Conversation2: Codable, Hashable, Sendable { + /// The unique ID of the conversation that this response was associated with. + /// + /// - Remark: Generated from `#/components/schemas/Conversation-2/id`. + public var id: Swift.String + /// Creates a new `Conversation2`. + /// + /// - Parameters: + /// - id: The unique ID of the conversation that this response was associated with. + public init(id: Swift.String) { + self.id = id + } + public enum CodingKeys: String, CodingKey { + case id + } + } } /// Types generated from the `#/components/parameters` section of the OpenAPI document. public enum Parameters {} From 31c62b4bf3c93d73d109b86ddebc459bfbad9e82 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 15 May 2026 20:29:25 +0300 Subject: [PATCH 02/31] Fix duplicate typealias declarations in generated Components.swift Remove 32 invalid redeclarations: duplicate primitive typealiases (Bool/String/Int/Double = Swift.X) within the same struct scope, and six `typealias String = [Swift.String]` entries that shadowed Swift.String in CodingKeys raw type position, breaking compilation. Co-Authored-By: Claude Sonnet 4.6 --- .../Public/Schemas/Generated/Components.swift | 32 ------------------- 1 file changed, 32 deletions(-) diff --git a/Sources/OpenAI/Public/Schemas/Generated/Components.swift b/Sources/OpenAI/Public/Schemas/Generated/Components.swift index 5b8c1e39..334ecaf5 100644 --- a/Sources/OpenAI/Public/Schemas/Generated/Components.swift +++ b/Sources/OpenAI/Public/Schemas/Generated/Components.swift @@ -1045,13 +1045,11 @@ public enum Components { public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/parallel_tool_calls`. public var parallelToolCalls: Swift.Bool? - public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/store`. public var store: Swift.Bool? public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/instructions`. public var instructions: Swift.String? - public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/stream`. public var stream: Swift.Bool? /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/stream_options`. @@ -2100,7 +2098,6 @@ public enum Components { public var code: Swift.String? /// - Remark: Generated from `#/components/schemas/Error/message`. public var message: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/Error/param`. public var param: Swift.String? /// - Remark: Generated from `#/components/schemas/Error/type`. @@ -3925,7 +3922,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/approve`. public var approve: Swift.Bool - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/reason`. public var reason: Swift.String? /// Creates a new `MCPApprovalResponse`. @@ -4477,7 +4473,6 @@ public enum Components { public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPToolCall/output`. public var output: Swift.String? - public typealias String = Swift.String /// - 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`. @@ -4485,7 +4480,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPToolCall/status`. public var status: Components.Schemas.MCPToolCallStatus? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPToolCall/approval_request_id`. public var approvalRequestId: Swift.String? /// Creates a new `MCPToolCall`. @@ -4819,7 +4813,6 @@ public enum Components { public typealias Double = Swift.Double /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/temperature`. public var temperature: Swift.Double? - public typealias Double = Swift.Double /// - 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. @@ -6609,7 +6602,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/message`. public var message: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/param`. public var param: Swift.String? /// The sequence number of this event. @@ -11782,13 +11774,10 @@ public enum Components { public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/country`. public var country: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/region`. public var region: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/city`. public var city: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/timezone`. public var timezone: Swift.String? /// Creates a new `WebSearchApproximateLocation`. @@ -11904,7 +11893,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/WebSearchTool/filters`. public struct FiltersPayload: Codable, Hashable, Sendable { - public typealias String = [Swift.String] /// - Remark: Generated from `#/components/schemas/WebSearchTool/filters/allowed_domains`. public var allowedDomains: [Swift.String]? /// Creates a new `FiltersPayload`. @@ -12842,7 +12830,6 @@ public enum Components { public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputImageContent/image_url`. public var imageUrl: Swift.String? - public typealias String = Swift.String /// - 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`. @@ -12992,7 +12979,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ClickParam/y`. public var y: Swift.Int - public typealias String = [Swift.String] /// - Remark: Generated from `#/components/schemas/ClickParam/keys`. public var keys: [Swift.String]? /// Creates a new `ClickParam`. @@ -13046,7 +13032,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/DoubleClickAction/y`. public var y: Swift.Int - public typealias String = [Swift.String] /// - Remark: Generated from `#/components/schemas/DoubleClickAction/keys`. public var keys: [Swift.String]? /// Creates a new `DoubleClickAction`. @@ -13127,7 +13112,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/DragParam/path`. public var path: [Components.Schemas.CoordParam] - public typealias String = [Swift.String] /// - Remark: Generated from `#/components/schemas/DragParam/keys`. public var keys: [Swift.String]? /// Creates a new `DragParam`. @@ -13208,7 +13192,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MoveParam/y`. public var y: Swift.Int - public typealias String = [Swift.String] /// - Remark: Generated from `#/components/schemas/MoveParam/keys`. public var keys: [Swift.String]? /// Creates a new `MoveParam`. @@ -13291,7 +13274,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ScrollParam/scroll_y`. public var scrollY: Swift.Int - public typealias String = [Swift.String] /// - Remark: Generated from `#/components/schemas/ScrollParam/keys`. public var keys: [Swift.String]? /// Creates a new `ScrollParam`. @@ -13398,7 +13380,6 @@ public enum Components { public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/code`. public var code: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/message`. public var message: Swift.String? /// Creates a new `ComputerCallSafetyCheckParam`. @@ -14681,13 +14662,10 @@ public enum Components { public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ApproximateLocation/country`. public var country: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ApproximateLocation/region`. public var region: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ApproximateLocation/city`. public var city: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ApproximateLocation/timezone`. public var timezone: Swift.String? /// Creates a new `ApproximateLocation`. @@ -15046,7 +15024,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/env`. public var env: Components.Schemas.LocalShellExecAction.EnvPayload - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/user`. public var user: Swift.String? /// Creates a new `LocalShellExecAction`. @@ -15091,7 +15068,6 @@ public enum Components { public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/FunctionShellAction/timeout_ms`. public var timeoutMs: Swift.Int? - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/FunctionShellAction/max_output_length`. public var maxOutputLength: Swift.Int? /// Creates a new `FunctionShellAction`. @@ -15959,7 +15935,6 @@ public enum Components { public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/image_url`. public var imageUrl: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/file_id`. public var fileId: Swift.String? /// - Remark: Generated from `#/components/schemas/DetailEnum`. @@ -16013,13 +15988,10 @@ public enum Components { public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputFileContentParam/file_id`. public var fileId: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputFileContentParam/filename`. public var filename: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputFileContentParam/file_data`. public var fileData: Swift.String? - public typealias String = Swift.String /// - 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`. @@ -16212,7 +16184,6 @@ public enum Components { public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/id`. public var id: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/call_id`. public var callId: Swift.String? /// The item type. Always `tool_search_call`. @@ -16275,7 +16246,6 @@ public enum Components { public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/id`. public var id: Swift.String? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/call_id`. public var callId: Swift.String? /// The item type. Always `tool_search_output`. @@ -16386,7 +16356,6 @@ public enum Components { public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/timeout_ms`. public var timeoutMs: Swift.Int? - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/max_output_length`. public var maxOutputLength: Swift.Int? /// Creates a new `FunctionShellActionParam`. @@ -16985,7 +16954,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/status`. public var status: Components.Schemas.ApplyPatchCallOutputStatusParam - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/output`. public var output: Swift.String? /// Creates a new `ApplyPatchToolCallOutputItemParam`. From 114c61384318cb2fa79f5eac9ffa7b61a0169458 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 15 May 2026 20:37:11 +0300 Subject: [PATCH 03/31] Update ResponseStreamEvent for new OpenAPI spec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Rename reasoning event types: ResponseReasoningDelta/DoneEvent → ResponseReasoningTextDelta/DoneEvent; ResponseReasoningSummaryDelta/DoneEvent → ResponseReasoningSummaryTextDelta/DoneEvent - Reorder decoder chain to match new value indices (value29–50): new ReasoningText events inserted at 29/30 pushed Refusal, OutputText, WebSearch, ImageGen, MCP events down by 2; MCP call-arguments events moved from value40/41 to value42/43, freeing 40/41 for the two previously-missing ImageGen events - Add decoder entries for value40/41 (ImageGenCallInProgress/PartialImage) and value49 (MCPListToolsInProgress), which were absent in the old mapping - Update guard indices to match: value40/41 → value42/43, value49 → value51 - Update case comments to match spec wording Co-Authored-By: Claude Sonnet 4.6 --- .../Schemas/Facade/ResponseStreamEvent.swift | 66 +++++++++---------- 1 file changed, 31 insertions(+), 35 deletions(-) diff --git a/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift b/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift index 9c156edf..94253719 100644 --- a/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift +++ b/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift @@ -133,17 +133,17 @@ public enum ResponseStreamEvent: Codable, Equatable, Sendable { } public enum ReasoningEvent: Codable, Equatable, Sendable { - /// Emitted when there is a delta (partial update) to the reasoning content. - case delta(Schemas.ResponseReasoningDeltaEvent) - /// Emitted when the reasoning content is finalized for an item. - case done(Schemas.ResponseReasoningDoneEvent) + /// Emitted when a delta is added to a reasoning text. + case delta(Schemas.ResponseReasoningTextDeltaEvent) + /// Emitted when a reasoning text is completed. + case done(Schemas.ResponseReasoningTextDoneEvent) } - + public enum ReasoningSummaryEvent: Codable, Equatable, Sendable { - /// Emitted when there is a delta (partial update) to the reasoning summary content. - case delta(Schemas.ResponseReasoningSummaryDeltaEvent) - /// Emitted when the reasoning summary content is finalized for an item. - case done(Schemas.ResponseReasoningSummaryDoneEvent) + /// Emitted when a delta is added to a reasoning summary text. + case delta(Schemas.ResponseReasoningSummaryTextDeltaEvent) + /// Emitted when a reasoning summary text is completed. + case done(Schemas.ResponseReasoningSummaryTextDoneEvent) } public enum AudioEvent: Codable, Equatable, Sendable { @@ -276,7 +276,7 @@ public enum ResponseStreamEvent: Codable, Equatable, Sendable { } let rawEvent = try Components.Schemas.ResponseStreamEvent(from: decoder) - if rawEvent.value10 != nil || rawEvent.value13 != nil || rawEvent.value20 != nil || rawEvent.value21 != nil, rawEvent.value22 != nil, rawEvent.value40 != nil, rawEvent.value41 != nil, rawEvent.value49 != nil { + if rawEvent.value10 != nil || rawEvent.value13 != nil || rawEvent.value20 != nil || rawEvent.value21 != nil, rawEvent.value22 != nil, rawEvent.value42 != nil, rawEvent.value43 != nil, rawEvent.value51 != nil { // The following events are handled elsewhere by non-generated types // (search "Decoding Response Event") // @@ -339,49 +339,45 @@ public enum ResponseStreamEvent: Codable, Equatable, Sendable { } else if let value = rawEvent.value28 { self = .reasoningSummaryText(.done(value)) } else if let value = rawEvent.value29 { - self = .refusal(.delta(value)) + self = .reasoning(.delta(value)) } else if let value = rawEvent.value30 { - self = .refusal(.done(value)) + self = .reasoning(.done(value)) } else if let value = rawEvent.value31 { - self = .outputText(.delta(value)) + self = .refusal(.delta(value)) } else if let value = rawEvent.value32 { - self = .outputText(.done(value)) + self = .refusal(.done(value)) } else if let value = rawEvent.value33 { - self = .webSearchCall(.completed(value)) + self = .outputText(.delta(value)) } else if let value = rawEvent.value34 { - self = .webSearchCall(.inProgress(value)) + self = .outputText(.done(value)) } else if let value = rawEvent.value35 { - self = .webSearchCall(.searching(value)) + self = .webSearchCall(.completed(value)) } else if let value = rawEvent.value36 { - self = .imageGenerationCall(.completed(value)) + self = .webSearchCall(.inProgress(value)) } else if let value = rawEvent.value37 { - self = .imageGenerationCall(.generating(value)) + self = .webSearchCall(.searching(value)) } else if let value = rawEvent.value38 { - self = .imageGenerationCall(.inProgress(value)) + self = .imageGenerationCall(.completed(value)) } else if let value = rawEvent.value39 { + self = .imageGenerationCall(.generating(value)) + } else if let value = rawEvent.value40 { + self = .imageGenerationCall(.inProgress(value)) + } else if let value = rawEvent.value41 { self = .imageGenerationCall(.partialImage(value)) - } else if let value = rawEvent.value42 { + } else if let value = rawEvent.value44 { self = .mcpCall(.completed(value)) - } else if let value = rawEvent.value43 { + } else if let value = rawEvent.value45 { self = .mcpCall(.failed(value)) - } else if let value = rawEvent.value44 { + } else if let value = rawEvent.value46 { self = .mcpCall(.inProgress(value)) - } else if let value = rawEvent.value45 { + } else if let value = rawEvent.value47 { self = .mcpListTools(.completed(value)) - } else if let value = rawEvent.value46 { + } else if let value = rawEvent.value48 { self = .mcpListTools(.failed(value)) - } else if let value = rawEvent.value47 { + } else if let value = rawEvent.value49 { self = .mcpListTools(.inProgress(value)) - } else if let value = rawEvent.value48 { - self = .outputTextAnnotation(.added(value)) } else if let value = rawEvent.value50 { - self = .reasoning(.delta(value)) - } else if let value = rawEvent.value51 { - self = .reasoning(.done(value)) - } else if let value = rawEvent.value52 { - self = .reasoningSummary(.delta(value)) - } else if let value = rawEvent.value53 { - self = .reasoningSummary(.done(value)) + self = .outputTextAnnotation(.added(value)) } else { throw ResponseStreamEventDecodingError.unknownEvent(rawEvent) } From d09a8cb65f7ebc9c5db9ea0ba735831829af6221 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 15 May 2026 20:43:49 +0300 Subject: [PATCH 04/31] Update OutputItem facade for new OpenAPI spec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Generated OutputItem changed from a OneOf struct (value1…value12) to a discriminated enum with named cases. Rewrite init(from:) to decode the generated enum and switch on its cases. Also adds the 13 new cases introduced in the spec: functionToolCallOutputResource, computerToolCallOutputResource, toolSearchCall, toolSearchOutput, compactionBody, localShellToolCallOutput, functionShellCall, functionShellCallOutput, applyPatchToolCall, applyPatchToolCallOutput, mcpApprovalResponseResource, customToolCall, customToolCallOutputResource. Updates existing comments to use absolute URLs and aligns wording with the spec descriptions. Co-Authored-By: Claude Sonnet 4.6 --- .../Public/Schemas/Facade/OutputItem.swift | 104 +++++++++++++----- 1 file changed, 75 insertions(+), 29 deletions(-) diff --git a/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift b/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift index 7e7b6f2a..7f772c63 100644 --- a/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift +++ b/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift @@ -11,69 +11,115 @@ import Foundation /// When editing the list of tool calls - also check Tool type if the list of tools should be updated public enum OutputItem: Codable, Hashable, Sendable { public typealias Schemas = Components.Schemas - + /// An output message from the model. case outputMessage(Schemas.OutputMessage) - /// The results of a file search tool call. See the `file search guide` for more information: - /// https://platform.openai.com/docs/guides/tools-file-search + /// The results of a file search tool call. See the + /// [file search guide](https://platform.openai.com/docs/guides/tools-file-search) for more information. case fileSearchToolCall(Schemas.FileSearchToolCall) - /// A tool call to run a function. See the `function calling guide` for more information: - /// https://platform.openai.com/docs/guides/function-calling + /// A tool call to run a function. See the + /// [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more information. case functionToolCall(Schemas.FunctionToolCall) - /// The results of a web search tool call. See the `web search guide` for more information. - /// https://platform.openai.com/docs/guides/tools-web-search + /// The output resource of a function tool call. + case functionToolCallOutputResource(Schemas.FunctionToolCallOutputResource) + /// The results of a web search tool call. See the + /// [web search guide](https://platform.openai.com/docs/guides/tools-web-search) for more information. case webSearchToolCall(Schemas.WebSearchToolCall) - /// A tool call to a computer use tool. See the `computer use guide` for more information. - /// https://platform.openai.com/docs/guides/tools-computer-use + /// A tool call to a computer use tool. See the + /// [computer use guide](https://platform.openai.com/docs/guides/tools-computer-use) for more information. case computerToolCall(Schemas.ComputerToolCall) + /// The output resource of a computer use tool call. + case computerToolCallOutputResource(Schemas.ComputerToolCallOutputResource) /// A description of the chain of thought used by a reasoning model while generating a response. case reasoning(Schemas.ReasoningItem) + /// A tool search call. + case toolSearchCall(Schemas.ToolSearchCall) + /// The output of a tool search call. + case toolSearchOutput(Schemas.ToolSearchOutput) + /// A compaction item generated by the `v1/responses/compact` API. + case compactionBody(Schemas.CompactionBody) /// An image generation request made by the model. case imageGenerationCall(Schemas.ImageGenToolCall) /// A tool call to run code. case codeInterpreterToolCall(Schemas.CodeInterpreterToolCall) /// A tool call to run a command on the local shell. case localShellCall(Schemas.LocalShellToolCall) + /// The output of a local shell tool call. + case localShellToolCallOutput(Schemas.LocalShellToolCallOutput) + /// A tool call that executes one or more shell commands in a managed environment. + case functionShellCall(Schemas.FunctionShellCall) + /// The output of a shell tool call that was emitted. + case functionShellCallOutput(Schemas.FunctionShellCallOutput) + /// A tool call that applies file diffs by creating, deleting, or updating files. + case applyPatchToolCall(Schemas.ApplyPatchToolCall) + /// The output emitted by an apply patch tool call. + case applyPatchToolCallOutput(Schemas.ApplyPatchToolCallOutput) /// An invocation of a tool on an MCP server. case mcpToolCall(Schemas.MCPToolCall) /// A list of tools available on an MCP server. case mcpListTools(Schemas.MCPListTools) /// A request for human approval of a tool invocation. case mcpApprovalRequest(Schemas.MCPApprovalRequest) - + /// A response to an MCP approval request. + case mcpApprovalResponseResource(Schemas.MCPApprovalResponseResource) + /// A call to a custom tool created by the model. + case customToolCall(Schemas.CustomToolCall) + /// The output resource of a custom tool call. + case customToolCallOutputResource(Schemas.CustomToolCallOutputResource) + public init(from decoder: any Decoder) throws { let generated = try Schemas.OutputItem(from: decoder) - if let value = generated.value1 { + switch generated { + case .outputMessage(let value): self = .outputMessage(value) - } else if let value = generated.value2 { + case .fileSearchToolCall(let value): self = .fileSearchToolCall(value) - } else if let value = generated.value3 { + case .functionToolCall(let value): self = .functionToolCall(value) - } else if let value = generated.value4 { + case .functionToolCallOutputResource(let value): + self = .functionToolCallOutputResource(value) + case .webSearchToolCall(let value): self = .webSearchToolCall(value) - } else if let value = generated.value5 { + case .computerToolCall(let value): self = .computerToolCall(value) - } else if let value = generated.value6 { + case .computerToolCallOutputResource(let value): + self = .computerToolCallOutputResource(value) + case .reasoningItem(let value): self = .reasoning(value) - } else if let value = generated.value7 { + case .toolSearchCall(let value): + self = .toolSearchCall(value) + case .toolSearchOutput(let value): + self = .toolSearchOutput(value) + case .compactionBody(let value): + self = .compactionBody(value) + case .imageGenToolCall(let value): self = .imageGenerationCall(value) - } else if let value = generated.value8 { + case .codeInterpreterToolCall(let value): self = .codeInterpreterToolCall(value) - } else if let value = generated.value9 { + case .localShellToolCall(let value): self = .localShellCall(value) - } else if let value = generated.value10 { + case .localShellToolCallOutput(let value): + self = .localShellToolCallOutput(value) + case .functionShellCall(let value): + self = .functionShellCall(value) + case .functionShellCallOutput(let value): + self = .functionShellCallOutput(value) + case .applyPatchToolCall(let value): + self = .applyPatchToolCall(value) + case .applyPatchToolCallOutput(let value): + self = .applyPatchToolCallOutput(value) + case .mcpToolCall(let value): self = .mcpToolCall(value) - } else if let value = generated.value11 { + case .mcpListTools(let value): self = .mcpListTools(value) - } else if let value = generated.value12 { + case .mcpApprovalRequest(let value): self = .mcpApprovalRequest(value) - } else { - throw DecodingError.dataCorrupted( - DecodingError.Context( - codingPath: decoder.codingPath, - debugDescription: "None of the known OutputItem cases could be decoded." - ) - ) + case .mcpApprovalResponseResource(let value): + self = .mcpApprovalResponseResource(value) + case .customToolCall(let value): + self = .customToolCall(value) + case .customToolCallOutputResource(let value): + self = .customToolCallOutputResource(value) } } } From 1ee424116713ad0dd2f431d0c0668d2671e09109 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 15 May 2026 20:53:28 +0300 Subject: [PATCH 05/31] Remove OutputItem facade, use Components.Schemas.OutputItem directly The generated type now has readable case names, making the facade unnecessary. Co-Authored-By: Claude Sonnet 4.6 --- .../Models/Responses API/ResponseObject.swift | 2 +- .../Edited/ResponseOutputItemAddedEvent.swift | 4 +- .../Edited/ResponseOutputItemDoneEvent.swift | 4 +- .../Public/Schemas/Facade/OutputItem.swift | 125 ------------------ .../OpenAITests/ResponsesEndpointTests.swift | 2 +- 5 files changed, 6 insertions(+), 131 deletions(-) delete mode 100644 Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift diff --git a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift index 7e2bb9cc..6fb7278a 100644 --- a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift +++ b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift @@ -48,7 +48,7 @@ public struct ResponseObject: Codable, Equatable, Sendable { /// An array of content items generated by the model. /// * The length and order of items in the `output` array is dependent on the model's response. /// * Rather than accessing the first item in the `output` array and assuming it's an `assistant` message with the content generated by the model, you might consider using the `output_text` property where supported in SDKs. - public let output: [OutputItem] + public let output: [Schemas.OutputItem] /// Whether to allow the model to run tool calls in parallel. public let parallelToolCalls: Bool diff --git a/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemAddedEvent.swift b/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemAddedEvent.swift index 82f6e1e8..d1624ba1 100644 --- a/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemAddedEvent.swift +++ b/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemAddedEvent.swift @@ -12,7 +12,7 @@ public struct ResponseOutputItemAddedEvent: Codable, Hashable, Sendable { /// The index of the output item that was added. public let outputIndex: Int /// The output item that was added. - public let item: OutputItem + public let item: Components.Schemas.OutputItem /// Creates a new `ResponseOutputItemAddedEvent`. /// /// - Parameters: @@ -22,7 +22,7 @@ public struct ResponseOutputItemAddedEvent: Codable, Hashable, Sendable { public init( type: String = "response.output_item.added", outputIndex: Int, - item: OutputItem + item: Components.Schemas.OutputItem ) { self.type = type self.outputIndex = outputIndex diff --git a/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemDoneEvent.swift b/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemDoneEvent.swift index b1a6a70c..c98363d3 100644 --- a/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemDoneEvent.swift +++ b/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemDoneEvent.swift @@ -12,7 +12,7 @@ public struct ResponseOutputItemDoneEvent: Codable, Hashable, Sendable { /// The index of the output item that was marked done. public let outputIndex: Int /// The output item that was marked done. - public let item: OutputItem + public let item: Components.Schemas.OutputItem /// Creates a new `ResponseOutputItemDoneEvent`. /// /// - Parameters: @@ -22,7 +22,7 @@ public struct ResponseOutputItemDoneEvent: Codable, Hashable, Sendable { public init( type: String = "response.output_item.done", outputIndex: Int, - item: OutputItem + item: Components.Schemas.OutputItem ) { self.type = type self.outputIndex = outputIndex diff --git a/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift b/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift deleted file mode 100644 index 7f772c63..00000000 --- a/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift +++ /dev/null @@ -1,125 +0,0 @@ -// -// OutputItem.swift -// OpenAI -// -// Created by Oleksii Nezhyborets on 15.04.2025. -// - -import Foundation - -/// Improved interface to use instead of generated `Components.Schemas.OutputItem` -/// When editing the list of tool calls - also check Tool type if the list of tools should be updated -public enum OutputItem: Codable, Hashable, Sendable { - public typealias Schemas = Components.Schemas - - /// An output message from the model. - case outputMessage(Schemas.OutputMessage) - /// The results of a file search tool call. See the - /// [file search guide](https://platform.openai.com/docs/guides/tools-file-search) for more information. - case fileSearchToolCall(Schemas.FileSearchToolCall) - /// A tool call to run a function. See the - /// [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more information. - case functionToolCall(Schemas.FunctionToolCall) - /// The output resource of a function tool call. - case functionToolCallOutputResource(Schemas.FunctionToolCallOutputResource) - /// The results of a web search tool call. See the - /// [web search guide](https://platform.openai.com/docs/guides/tools-web-search) for more information. - case webSearchToolCall(Schemas.WebSearchToolCall) - /// A tool call to a computer use tool. See the - /// [computer use guide](https://platform.openai.com/docs/guides/tools-computer-use) for more information. - case computerToolCall(Schemas.ComputerToolCall) - /// The output resource of a computer use tool call. - case computerToolCallOutputResource(Schemas.ComputerToolCallOutputResource) - /// A description of the chain of thought used by a reasoning model while generating a response. - case reasoning(Schemas.ReasoningItem) - /// A tool search call. - case toolSearchCall(Schemas.ToolSearchCall) - /// The output of a tool search call. - case toolSearchOutput(Schemas.ToolSearchOutput) - /// A compaction item generated by the `v1/responses/compact` API. - case compactionBody(Schemas.CompactionBody) - /// An image generation request made by the model. - case imageGenerationCall(Schemas.ImageGenToolCall) - /// A tool call to run code. - case codeInterpreterToolCall(Schemas.CodeInterpreterToolCall) - /// A tool call to run a command on the local shell. - case localShellCall(Schemas.LocalShellToolCall) - /// The output of a local shell tool call. - case localShellToolCallOutput(Schemas.LocalShellToolCallOutput) - /// A tool call that executes one or more shell commands in a managed environment. - case functionShellCall(Schemas.FunctionShellCall) - /// The output of a shell tool call that was emitted. - case functionShellCallOutput(Schemas.FunctionShellCallOutput) - /// A tool call that applies file diffs by creating, deleting, or updating files. - case applyPatchToolCall(Schemas.ApplyPatchToolCall) - /// The output emitted by an apply patch tool call. - case applyPatchToolCallOutput(Schemas.ApplyPatchToolCallOutput) - /// An invocation of a tool on an MCP server. - case mcpToolCall(Schemas.MCPToolCall) - /// A list of tools available on an MCP server. - case mcpListTools(Schemas.MCPListTools) - /// A request for human approval of a tool invocation. - case mcpApprovalRequest(Schemas.MCPApprovalRequest) - /// A response to an MCP approval request. - case mcpApprovalResponseResource(Schemas.MCPApprovalResponseResource) - /// A call to a custom tool created by the model. - case customToolCall(Schemas.CustomToolCall) - /// The output resource of a custom tool call. - case customToolCallOutputResource(Schemas.CustomToolCallOutputResource) - - public init(from decoder: any Decoder) throws { - let generated = try Schemas.OutputItem(from: decoder) - switch generated { - case .outputMessage(let value): - self = .outputMessage(value) - case .fileSearchToolCall(let value): - self = .fileSearchToolCall(value) - case .functionToolCall(let value): - self = .functionToolCall(value) - case .functionToolCallOutputResource(let value): - self = .functionToolCallOutputResource(value) - case .webSearchToolCall(let value): - self = .webSearchToolCall(value) - case .computerToolCall(let value): - self = .computerToolCall(value) - case .computerToolCallOutputResource(let value): - self = .computerToolCallOutputResource(value) - case .reasoningItem(let value): - self = .reasoning(value) - case .toolSearchCall(let value): - self = .toolSearchCall(value) - case .toolSearchOutput(let value): - self = .toolSearchOutput(value) - case .compactionBody(let value): - self = .compactionBody(value) - case .imageGenToolCall(let value): - self = .imageGenerationCall(value) - case .codeInterpreterToolCall(let value): - self = .codeInterpreterToolCall(value) - case .localShellToolCall(let value): - self = .localShellCall(value) - case .localShellToolCallOutput(let value): - self = .localShellToolCallOutput(value) - case .functionShellCall(let value): - self = .functionShellCall(value) - case .functionShellCallOutput(let value): - self = .functionShellCallOutput(value) - case .applyPatchToolCall(let value): - self = .applyPatchToolCall(value) - case .applyPatchToolCallOutput(let value): - self = .applyPatchToolCallOutput(value) - case .mcpToolCall(let value): - self = .mcpToolCall(value) - case .mcpListTools(let value): - self = .mcpListTools(value) - case .mcpApprovalRequest(let value): - self = .mcpApprovalRequest(value) - case .mcpApprovalResponseResource(let value): - self = .mcpApprovalResponseResource(value) - case .customToolCall(let value): - self = .customToolCall(value) - case .customToolCallOutputResource(let value): - self = .customToolCallOutputResource(value) - } - } -} diff --git a/Tests/OpenAITests/ResponsesEndpointTests.swift b/Tests/OpenAITests/ResponsesEndpointTests.swift index 6ca04ae3..cdcff55e 100644 --- a/Tests/OpenAITests/ResponsesEndpointTests.swift +++ b/Tests/OpenAITests/ResponsesEndpointTests.swift @@ -119,7 +119,7 @@ class ResponsesEndpointTests: XCTestCase { XCTFail("Expected tool in response to be a function") } } - private func makeResponse(output: [OutputItem] = [], tools: [Tool] = []) -> ResponseObject { + private func makeResponse(output: [Components.Schemas.OutputItem] = [], tools: [Tool] = []) -> ResponseObject { .init( createdAt: 123, error: nil, From 3bd250eda6ca5f710776931fb1d5f61fa7631dfc Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 15 May 2026 23:08:57 +0300 Subject: [PATCH 06/31] Update manual types for new OpenAPI spec MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Rename Includable → IncludeEnum, TextPayload → ResponseTextParam, ToolChoicePayload → ToolChoiceParam - Replace LocalShellTool → LocalShellToolParam in Tool enum - Add new Tool cases: computer, computerUsePreview, webSearch, webSearchPreview, functionShell, custom, namespace, toolSearch, applyPatch - Drop Tool suffix from all enum case names Co-Authored-By: Claude Sonnet 4.6 --- .../CreateModelResponseQuery.swift | 8 +- .../Responses API/GetModelResponseQuery.swift | 2 +- .../Models/Responses API/ResponseObject.swift | 6 +- .../OpenAI/Public/Schemas/Edited/Tool.swift | 117 ++++++++++++++---- 4 files changed, 101 insertions(+), 32 deletions(-) diff --git a/Sources/OpenAI/Public/Models/Responses API/CreateModelResponseQuery.swift b/Sources/OpenAI/Public/Models/Responses API/CreateModelResponseQuery.swift index 227b9d15..8e54c737 100644 --- a/Sources/OpenAI/Public/Models/Responses API/CreateModelResponseQuery.swift +++ b/Sources/OpenAI/Public/Models/Responses API/CreateModelResponseQuery.swift @@ -33,7 +33,7 @@ public struct CreateModelResponseQuery: Codable, Equatable, Sendable { /// - `computer_call_output.output.image_url`: Include image urls from the computer call output. /// - `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). /// - `code_interpreter_call.outputs`: Includes the outputs of python code execution in code interpreter tool call items. - public let include: [Schemas.Includable]? + public let include: [Schemas.IncludeEnum]? /// Whether to run the model response in the background. [Learn more](https://platform.openai.com/docs/guides/background). public let background: Bool? @@ -105,7 +105,7 @@ public struct CreateModelResponseQuery: Codable, Equatable, Sendable { /// How the model should select which tool (or tools) to use when generating a response. /// See the `tools` parameter to see how to specify which tools the model can call. - public let toolChoice: ResponseProperties.ToolChoicePayload? + public let toolChoice: Schemas.ToolChoiceParam? /// An array of tools the model may call while generating a response. You can specify which tool to use by setting the `toolChoice` parameter. /// @@ -133,7 +133,7 @@ public struct CreateModelResponseQuery: Codable, Equatable, Sendable { public init( input: Input, model: String, - include: [Schemas.Includable]? = nil, + include: [Schemas.IncludeEnum]? = nil, background: Bool? = nil, instructions: String? = nil, maxOutputTokens: Int? = nil, @@ -148,7 +148,7 @@ public struct CreateModelResponseQuery: Codable, Equatable, Sendable { stream: Bool? = nil, temperature: Double? = nil, text: TextResponseConfigurationOptions? = nil, - toolChoice: ResponseProperties.ToolChoicePayload? = nil, + toolChoice: Schemas.ToolChoiceParam? = nil, tools: [Tool]? = nil, topP: Double? = nil, truncation: String? = nil, diff --git a/Sources/OpenAI/Public/Models/Responses API/GetModelResponseQuery.swift b/Sources/OpenAI/Public/Models/Responses API/GetModelResponseQuery.swift index 29fea2ba..57cffbf0 100644 --- a/Sources/OpenAI/Public/Models/Responses API/GetModelResponseQuery.swift +++ b/Sources/OpenAI/Public/Models/Responses API/GetModelResponseQuery.swift @@ -15,7 +15,7 @@ public struct GetModelResponseQuery: Codable, Equatable, Sendable { /// * `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. /// * `computer_call_output.output.image_url`: Include image urls from the computer call output. - public let include: [Components.Schemas.Includable]? + public let include: [Components.Schemas.IncludeEnum]? private enum CodingKeys: String, CodingKey { case responseId = "response_id" diff --git a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift index 6fb7278a..bc2c217a 100644 --- a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift +++ b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift @@ -70,10 +70,10 @@ public struct ResponseObject: Codable, Equatable, Sendable { /// Configuration options for a text response from the model. Can be plain text or structured JSON data. Learn more: /// - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) /// - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - public let text: ResponseProperties.TextPayload - + public let text: Schemas.ResponseTextParam + /// How the model should select which tool (or tools) to use when generating a response. See the `tools` parameter to see how to specify which tools the model can call. - public let toolChoice: ResponseProperties.ToolChoicePayload + public let toolChoice: Schemas.ToolChoiceParam /// An array of tools the model may call while generating a response. You can specify which tool to use by setting the `tool_choice` parameter. /// diff --git a/Sources/OpenAI/Public/Schemas/Edited/Tool.swift b/Sources/OpenAI/Public/Schemas/Edited/Tool.swift index 7e8b1d27..7d32d916 100644 --- a/Sources/OpenAI/Public/Schemas/Edited/Tool.swift +++ b/Sources/OpenAI/Public/Schemas/Edited/Tool.swift @@ -8,60 +8,85 @@ @_spi(Generated) import OpenAPIRuntime /// Reason for editing: Generated FunctionTool type is not user friendly. -/// When editing the list of tool - also check OutputItem type if the list of tool calls should be updated @frozen public enum Tool: Codable, Hashable, Sendable { public typealias Schemas = Components.Schemas - + /// A tool that searches for relevant content from uploaded files. /// Learn more about the [file search tool](/docs/guides/tools-file-search). - case fileSearchTool(Schemas.FileSearchTool) + case fileSearch(Schemas.FileSearchTool) /// Defines a function in your own code the model can choose to call. Learn more /// about [function calling](/docs/guides/function-calling). - case functionTool(FunctionTool) + case function(FunctionTool) /// A tool that controls a virtual computer. Learn more about the /// [computer tool](/docs/guides/tools-computer-use). - case computerTool(Schemas.ComputerUsePreviewTool) + case computer(Schemas.ComputerTool) + /// A tool that controls a virtual computer (preview version). + case computerUsePreview(Schemas.ComputerUsePreviewTool) /// This tool searches the web for relevant results to use in a response. /// Learn more about the [web search tool](/docs/guides/tools-web-search). - case webSearchTool(Schemas.WebSearchPreviewTool) + case webSearch(Schemas.WebSearchTool) + /// This tool searches the web for relevant results to use in a response (preview version). + case webSearchPreview(Schemas.WebSearchPreviewTool) /// Give the model access to additional tools via remote Model Context Protocol (MCP) servers. /// [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp) - case mcpTool(Schemas.MCPTool) + case mcp(Schemas.MCPTool) /// A tool that runs Python code to help generate a response to a prompt. case codeInterpreter(Schemas.CodeInterpreterTool) /// A tool that generates images using a model like `gpt-image-1`. - case imageGenerationTool(Schemas.ImageGenTool) + case imageGeneration(Schemas.ImageGenTool) /// A tool that allows the model to execute shell commands in a local environment. - case localShellTool(Schemas.LocalShellTool) - + case localShell(Schemas.LocalShellToolParam) + /// A tool that allows the model to execute shell commands via a function. + case functionShell(Schemas.FunctionShellToolParam) + /// A custom tool defined by the user. + case custom(Schemas.CustomToolParam) + /// A namespace-scoped tool. + case namespace(Schemas.NamespaceToolParam) + /// A tool that performs tool searches. + case toolSearch(Schemas.ToolSearchToolParam) + /// A tool that applies patches. + case applyPatch(Schemas.ApplyPatchToolParam) + public init(from decoder: any Decoder) throws { var errors: [any Error] = [] do { - self = .fileSearchTool(try .init(from: decoder)) + self = .fileSearch(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .function(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .computer(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .functionTool(try .init(from: decoder)) + self = .computerUsePreview(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .computerTool(try .init(from: decoder)) + self = .webSearch(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .webSearchTool(try .init(from: decoder)) + self = .webSearchPreview(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .mcpTool(try .init(from: decoder)) + self = .mcp(try .init(from: decoder)) return } catch { errors.append(error) @@ -73,13 +98,43 @@ errors.append(error) } do { - self = .imageGenerationTool(try .init(from: decoder)) + self = .imageGeneration(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .localShell(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .functionShell(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .localShellTool(try .init(from: decoder)) + self = .custom(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .namespace(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .toolSearch(try .init(from: decoder)) + return + } catch { + errors.append(error) + } + do { + self = .applyPatch(try .init(from: decoder)) return } catch { errors.append(error) @@ -92,21 +147,35 @@ } public func encode(to encoder: any Encoder) throws { switch self { - case let .fileSearchTool(value): + case let .fileSearch(value): + try value.encode(to: encoder) + case let .function(value): + try value.encode(to: encoder) + case let .computer(value): try value.encode(to: encoder) - case let .functionTool(value): + case let .computerUsePreview(value): try value.encode(to: encoder) - case let .computerTool(value): + case let .webSearch(value): try value.encode(to: encoder) - case let .webSearchTool(value): + case let .webSearchPreview(value): try value.encode(to: encoder) - case let .mcpTool(value): + case let .mcp(value): try value.encode(to: encoder) case let .codeInterpreter(value): try value.encode(to: encoder) - case let .imageGenerationTool(value): + case let .imageGeneration(value): + try value.encode(to: encoder) + case let .localShell(value): + try value.encode(to: encoder) + case let .functionShell(value): + try value.encode(to: encoder) + case let .custom(value): + try value.encode(to: encoder) + case let .namespace(value): + try value.encode(to: encoder) + case let .toolSearch(value): try value.encode(to: encoder) - case let .localShellTool(value): + case let .applyPatch(value): try value.encode(to: encoder) } } From 6a31fbbdbe112b940bc9195c67d18d43fb8c92df Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 15 May 2026 23:18:50 +0300 Subject: [PATCH 07/31] Fix test failures and normalize Tool case naming MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Restore Tool suffix on all enum cases; rename codeInterpreter → codeInterpreterTool - Add required responseId param to ResponseAudioDoneEvent in test - Add logprobs:[] to mock SSE JSON for ResponseTextDeltaEvent (now required by spec) Co-Authored-By: Claude Sonnet 4.6 --- .../OpenAI/Public/Schemas/Edited/Tool.swift | 90 +++++++++---------- Tests/OpenAITests/MockServerSentEvent.swift | 2 +- Tests/OpenAITests/StreamingClientTests.swift | 2 +- 3 files changed, 47 insertions(+), 47 deletions(-) diff --git a/Sources/OpenAI/Public/Schemas/Edited/Tool.swift b/Sources/OpenAI/Public/Schemas/Edited/Tool.swift index 7d32d916..3eed40c4 100644 --- a/Sources/OpenAI/Public/Schemas/Edited/Tool.swift +++ b/Sources/OpenAI/Public/Schemas/Edited/Tool.swift @@ -13,128 +13,128 @@ /// A tool that searches for relevant content from uploaded files. /// Learn more about the [file search tool](/docs/guides/tools-file-search). - case fileSearch(Schemas.FileSearchTool) + case fileSearchTool(Schemas.FileSearchTool) /// Defines a function in your own code the model can choose to call. Learn more /// about [function calling](/docs/guides/function-calling). - case function(FunctionTool) + case functionTool(FunctionTool) /// A tool that controls a virtual computer. Learn more about the /// [computer tool](/docs/guides/tools-computer-use). - case computer(Schemas.ComputerTool) + case computerTool(Schemas.ComputerTool) /// A tool that controls a virtual computer (preview version). - case computerUsePreview(Schemas.ComputerUsePreviewTool) + case computerUsePreviewTool(Schemas.ComputerUsePreviewTool) /// This tool searches the web for relevant results to use in a response. /// Learn more about the [web search tool](/docs/guides/tools-web-search). - case webSearch(Schemas.WebSearchTool) + case webSearchTool(Schemas.WebSearchTool) /// This tool searches the web for relevant results to use in a response (preview version). - case webSearchPreview(Schemas.WebSearchPreviewTool) + case webSearchPreviewTool(Schemas.WebSearchPreviewTool) /// Give the model access to additional tools via remote Model Context Protocol (MCP) servers. /// [Learn more about MCP](https://platform.openai.com/docs/guides/tools-remote-mcp) - case mcp(Schemas.MCPTool) + case mcpTool(Schemas.MCPTool) /// A tool that runs Python code to help generate a response to a prompt. - case codeInterpreter(Schemas.CodeInterpreterTool) + case codeInterpreterTool(Schemas.CodeInterpreterTool) /// A tool that generates images using a model like `gpt-image-1`. - case imageGeneration(Schemas.ImageGenTool) + case imageGenerationTool(Schemas.ImageGenTool) /// A tool that allows the model to execute shell commands in a local environment. - case localShell(Schemas.LocalShellToolParam) + case localShellTool(Schemas.LocalShellToolParam) /// A tool that allows the model to execute shell commands via a function. - case functionShell(Schemas.FunctionShellToolParam) + case functionShellTool(Schemas.FunctionShellToolParam) /// A custom tool defined by the user. - case custom(Schemas.CustomToolParam) + case customTool(Schemas.CustomToolParam) /// A namespace-scoped tool. - case namespace(Schemas.NamespaceToolParam) + case namespaceTool(Schemas.NamespaceToolParam) /// A tool that performs tool searches. - case toolSearch(Schemas.ToolSearchToolParam) + case toolSearchTool(Schemas.ToolSearchToolParam) /// A tool that applies patches. - case applyPatch(Schemas.ApplyPatchToolParam) + case applyPatchTool(Schemas.ApplyPatchToolParam) public init(from decoder: any Decoder) throws { var errors: [any Error] = [] do { - self = .fileSearch(try .init(from: decoder)) + self = .fileSearchTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .function(try .init(from: decoder)) + self = .functionTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .computer(try .init(from: decoder)) + self = .computerTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .computerUsePreview(try .init(from: decoder)) + self = .computerUsePreviewTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .webSearch(try .init(from: decoder)) + self = .webSearchTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .webSearchPreview(try .init(from: decoder)) + self = .webSearchPreviewTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .mcp(try .init(from: decoder)) + self = .mcpTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .codeInterpreter(try .init(from: decoder)) + self = .codeInterpreterTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .imageGeneration(try .init(from: decoder)) + self = .imageGenerationTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .localShell(try .init(from: decoder)) + self = .localShellTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .functionShell(try .init(from: decoder)) + self = .functionShellTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .custom(try .init(from: decoder)) + self = .customTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .namespace(try .init(from: decoder)) + self = .namespaceTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .toolSearch(try .init(from: decoder)) + self = .toolSearchTool(try .init(from: decoder)) return } catch { errors.append(error) } do { - self = .applyPatch(try .init(from: decoder)) + self = .applyPatchTool(try .init(from: decoder)) return } catch { errors.append(error) @@ -147,35 +147,35 @@ } public func encode(to encoder: any Encoder) throws { switch self { - case let .fileSearch(value): + case let .fileSearchTool(value): try value.encode(to: encoder) - case let .function(value): + case let .functionTool(value): try value.encode(to: encoder) - case let .computer(value): + case let .computerTool(value): try value.encode(to: encoder) - case let .computerUsePreview(value): + case let .computerUsePreviewTool(value): try value.encode(to: encoder) - case let .webSearch(value): + case let .webSearchTool(value): try value.encode(to: encoder) - case let .webSearchPreview(value): + case let .webSearchPreviewTool(value): try value.encode(to: encoder) - case let .mcp(value): + case let .mcpTool(value): try value.encode(to: encoder) - case let .codeInterpreter(value): + case let .codeInterpreterTool(value): try value.encode(to: encoder) - case let .imageGeneration(value): + case let .imageGenerationTool(value): try value.encode(to: encoder) - case let .localShell(value): + case let .localShellTool(value): try value.encode(to: encoder) - case let .functionShell(value): + case let .functionShellTool(value): try value.encode(to: encoder) - case let .custom(value): + case let .customTool(value): try value.encode(to: encoder) - case let .namespace(value): + case let .namespaceTool(value): try value.encode(to: encoder) - case let .toolSearch(value): + case let .toolSearchTool(value): try value.encode(to: encoder) - case let .applyPatch(value): + case let .applyPatchTool(value): try value.encode(to: encoder) } } diff --git a/Tests/OpenAITests/MockServerSentEvent.swift b/Tests/OpenAITests/MockServerSentEvent.swift index f09a183e..67f3a7fd 100644 --- a/Tests/OpenAITests/MockServerSentEvent.swift +++ b/Tests/OpenAITests/MockServerSentEvent.swift @@ -30,7 +30,7 @@ struct MockServerSentEvent { sequenceNumber: Int = 1 ) -> Data { let json = """ - {"type":"\(payloadType)","output_index":\(outputIndex),"item_id":"\(itemId)","content_index":\(contentIndex),"delta":"\(delta)","sequence_number":\(sequenceNumber)} + {"type":"\(payloadType)","output_index":\(outputIndex),"item_id":"\(itemId)","content_index":\(contentIndex),"delta":"\(delta)","sequence_number":\(sequenceNumber),"logprobs":[]} """ return "data: \(json)\n\n".data(using: .utf8)! } diff --git a/Tests/OpenAITests/StreamingClientTests.swift b/Tests/OpenAITests/StreamingClientTests.swift index 6f8c3557..273f0977 100644 --- a/Tests/OpenAITests/StreamingClientTests.swift +++ b/Tests/OpenAITests/StreamingClientTests.swift @@ -57,7 +57,7 @@ struct StreamingClientTests { } @Test func interceptResponsesRequest() async throws { - mockSession.dataTask = try DataTaskMock.successfulJson(with: ResponseStreamEvent.audio(.done(.init(_type: .response_audio_done, sequenceNumber: 0)))) + mockSession.dataTask = try DataTaskMock.successfulJson(with: ResponseStreamEvent.audio(.done(.init(_type: .response_audio_done, responseId: "", sequenceNumber: 0)))) mockMiddleware.interceptRequestReturnValue = .init(url: interceptedURL) _ = client.performResponsesStreamingRequest( request: JSONRequest(url: originalURL), From e79fa23a58f0dc2bde876077d9cea0da48eec201 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 15 May 2026 23:23:38 +0300 Subject: [PATCH 08/31] Fix warnings --- .../Extensions for generated code/Schemas+Description.swift | 3 +-- .../Public/JSONSchemaConvertible/JSONSchemaConvertible.swift | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Sources/OpenAI/Private/Extensions for generated code/Schemas+Description.swift b/Sources/OpenAI/Private/Extensions for generated code/Schemas+Description.swift index 971d22aa..a6805835 100644 --- a/Sources/OpenAI/Private/Extensions for generated code/Schemas+Description.swift +++ b/Sources/OpenAI/Private/Extensions for generated code/Schemas+Description.swift @@ -24,8 +24,7 @@ extension Components.Schemas.ModelResponseProperties: CustomStringConvertible { let parts: [String] = [ "metadata: \(metadata.map(String.init(describing:)) ?? "nil")", "temperature: \(temperature.map(String.init(describing:)) ?? "nil")", - "topP: \(topP.map(String.init(describing:)) ?? "nil")", - "user: \(user.map { "\"\($0)\"" } ?? "nil")" + "topP: \(topP.map(String.init(describing:)) ?? "nil")" ] return "ModelResponseProperties(\(parts.joined(separator: ", ")))" diff --git a/Sources/OpenAI/Public/JSONSchemaConvertible/JSONSchemaConvertible.swift b/Sources/OpenAI/Public/JSONSchemaConvertible/JSONSchemaConvertible.swift index 83123e20..46dc196e 100644 --- a/Sources/OpenAI/Public/JSONSchemaConvertible/JSONSchemaConvertible.swift +++ b/Sources/OpenAI/Public/JSONSchemaConvertible/JSONSchemaConvertible.swift @@ -7,6 +7,6 @@ import Foundation -public protocol JSONSchemaConvertible: Codable { +public protocol JSONSchemaConvertible: Codable, Sendable { static var example: Self { get } } From a0ff99be4cff6453e897e4bd84a3868ad939055c Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Sat, 16 May 2026 20:24:00 +0300 Subject: [PATCH 09/31] Restore OutputItem facade, keeping public API stable Re-adds the OutputItem facade removed in the previous commit so that public call sites don't need to switch on Components.Schemas.OutputItem directly. The facade mirrors all 25 cases of the generated type and preserves the user-friendly names (reasoning, imageGenerationCall, localShellCall). Also removes the now-redundant ResponseStreamEvent.OutputItem typealias that pointed at the generated type. Co-Authored-By: Claude Sonnet 4.6 --- .../Models/Responses API/ResponseObject.swift | 2 +- .../Edited/ResponseOutputItemAddedEvent.swift | 4 +- .../Edited/ResponseOutputItemDoneEvent.swift | 4 +- .../Public/Schemas/Facade/OutputItem.swift | 125 ++++++++++++++++++ .../Schemas/Facade/ResponseStreamEvent.swift | 1 - .../OpenAITests/ResponsesEndpointTests.swift | 2 +- 6 files changed, 131 insertions(+), 7 deletions(-) create mode 100644 Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift diff --git a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift index bc2c217a..98fda867 100644 --- a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift +++ b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift @@ -48,7 +48,7 @@ public struct ResponseObject: Codable, Equatable, Sendable { /// An array of content items generated by the model. /// * The length and order of items in the `output` array is dependent on the model's response. /// * Rather than accessing the first item in the `output` array and assuming it's an `assistant` message with the content generated by the model, you might consider using the `output_text` property where supported in SDKs. - public let output: [Schemas.OutputItem] + public let output: [OutputItem] /// Whether to allow the model to run tool calls in parallel. public let parallelToolCalls: Bool diff --git a/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemAddedEvent.swift b/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemAddedEvent.swift index d1624ba1..82f6e1e8 100644 --- a/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemAddedEvent.swift +++ b/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemAddedEvent.swift @@ -12,7 +12,7 @@ public struct ResponseOutputItemAddedEvent: Codable, Hashable, Sendable { /// The index of the output item that was added. public let outputIndex: Int /// The output item that was added. - public let item: Components.Schemas.OutputItem + public let item: OutputItem /// Creates a new `ResponseOutputItemAddedEvent`. /// /// - Parameters: @@ -22,7 +22,7 @@ public struct ResponseOutputItemAddedEvent: Codable, Hashable, Sendable { public init( type: String = "response.output_item.added", outputIndex: Int, - item: Components.Schemas.OutputItem + item: OutputItem ) { self.type = type self.outputIndex = outputIndex diff --git a/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemDoneEvent.swift b/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemDoneEvent.swift index c98363d3..b1a6a70c 100644 --- a/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemDoneEvent.swift +++ b/Sources/OpenAI/Public/Schemas/Edited/ResponseOutputItemDoneEvent.swift @@ -12,7 +12,7 @@ public struct ResponseOutputItemDoneEvent: Codable, Hashable, Sendable { /// The index of the output item that was marked done. public let outputIndex: Int /// The output item that was marked done. - public let item: Components.Schemas.OutputItem + public let item: OutputItem /// Creates a new `ResponseOutputItemDoneEvent`. /// /// - Parameters: @@ -22,7 +22,7 @@ public struct ResponseOutputItemDoneEvent: Codable, Hashable, Sendable { public init( type: String = "response.output_item.done", outputIndex: Int, - item: Components.Schemas.OutputItem + item: OutputItem ) { self.type = type self.outputIndex = outputIndex diff --git a/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift b/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift new file mode 100644 index 00000000..7f772c63 --- /dev/null +++ b/Sources/OpenAI/Public/Schemas/Facade/OutputItem.swift @@ -0,0 +1,125 @@ +// +// OutputItem.swift +// OpenAI +// +// Created by Oleksii Nezhyborets on 15.04.2025. +// + +import Foundation + +/// Improved interface to use instead of generated `Components.Schemas.OutputItem` +/// When editing the list of tool calls - also check Tool type if the list of tools should be updated +public enum OutputItem: Codable, Hashable, Sendable { + public typealias Schemas = Components.Schemas + + /// An output message from the model. + case outputMessage(Schemas.OutputMessage) + /// The results of a file search tool call. See the + /// [file search guide](https://platform.openai.com/docs/guides/tools-file-search) for more information. + case fileSearchToolCall(Schemas.FileSearchToolCall) + /// A tool call to run a function. See the + /// [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more information. + case functionToolCall(Schemas.FunctionToolCall) + /// The output resource of a function tool call. + case functionToolCallOutputResource(Schemas.FunctionToolCallOutputResource) + /// The results of a web search tool call. See the + /// [web search guide](https://platform.openai.com/docs/guides/tools-web-search) for more information. + case webSearchToolCall(Schemas.WebSearchToolCall) + /// A tool call to a computer use tool. See the + /// [computer use guide](https://platform.openai.com/docs/guides/tools-computer-use) for more information. + case computerToolCall(Schemas.ComputerToolCall) + /// The output resource of a computer use tool call. + case computerToolCallOutputResource(Schemas.ComputerToolCallOutputResource) + /// A description of the chain of thought used by a reasoning model while generating a response. + case reasoning(Schemas.ReasoningItem) + /// A tool search call. + case toolSearchCall(Schemas.ToolSearchCall) + /// The output of a tool search call. + case toolSearchOutput(Schemas.ToolSearchOutput) + /// A compaction item generated by the `v1/responses/compact` API. + case compactionBody(Schemas.CompactionBody) + /// An image generation request made by the model. + case imageGenerationCall(Schemas.ImageGenToolCall) + /// A tool call to run code. + case codeInterpreterToolCall(Schemas.CodeInterpreterToolCall) + /// A tool call to run a command on the local shell. + case localShellCall(Schemas.LocalShellToolCall) + /// The output of a local shell tool call. + case localShellToolCallOutput(Schemas.LocalShellToolCallOutput) + /// A tool call that executes one or more shell commands in a managed environment. + case functionShellCall(Schemas.FunctionShellCall) + /// The output of a shell tool call that was emitted. + case functionShellCallOutput(Schemas.FunctionShellCallOutput) + /// A tool call that applies file diffs by creating, deleting, or updating files. + case applyPatchToolCall(Schemas.ApplyPatchToolCall) + /// The output emitted by an apply patch tool call. + case applyPatchToolCallOutput(Schemas.ApplyPatchToolCallOutput) + /// An invocation of a tool on an MCP server. + case mcpToolCall(Schemas.MCPToolCall) + /// A list of tools available on an MCP server. + case mcpListTools(Schemas.MCPListTools) + /// A request for human approval of a tool invocation. + case mcpApprovalRequest(Schemas.MCPApprovalRequest) + /// A response to an MCP approval request. + case mcpApprovalResponseResource(Schemas.MCPApprovalResponseResource) + /// A call to a custom tool created by the model. + case customToolCall(Schemas.CustomToolCall) + /// The output resource of a custom tool call. + case customToolCallOutputResource(Schemas.CustomToolCallOutputResource) + + public init(from decoder: any Decoder) throws { + let generated = try Schemas.OutputItem(from: decoder) + switch generated { + case .outputMessage(let value): + self = .outputMessage(value) + case .fileSearchToolCall(let value): + self = .fileSearchToolCall(value) + case .functionToolCall(let value): + self = .functionToolCall(value) + case .functionToolCallOutputResource(let value): + self = .functionToolCallOutputResource(value) + case .webSearchToolCall(let value): + self = .webSearchToolCall(value) + case .computerToolCall(let value): + self = .computerToolCall(value) + case .computerToolCallOutputResource(let value): + self = .computerToolCallOutputResource(value) + case .reasoningItem(let value): + self = .reasoning(value) + case .toolSearchCall(let value): + self = .toolSearchCall(value) + case .toolSearchOutput(let value): + self = .toolSearchOutput(value) + case .compactionBody(let value): + self = .compactionBody(value) + case .imageGenToolCall(let value): + self = .imageGenerationCall(value) + case .codeInterpreterToolCall(let value): + self = .codeInterpreterToolCall(value) + case .localShellToolCall(let value): + self = .localShellCall(value) + case .localShellToolCallOutput(let value): + self = .localShellToolCallOutput(value) + case .functionShellCall(let value): + self = .functionShellCall(value) + case .functionShellCallOutput(let value): + self = .functionShellCallOutput(value) + case .applyPatchToolCall(let value): + self = .applyPatchToolCall(value) + case .applyPatchToolCallOutput(let value): + self = .applyPatchToolCallOutput(value) + case .mcpToolCall(let value): + self = .mcpToolCall(value) + case .mcpListTools(let value): + self = .mcpListTools(value) + case .mcpApprovalRequest(let value): + self = .mcpApprovalRequest(value) + case .mcpApprovalResponseResource(let value): + self = .mcpApprovalResponseResource(value) + case .customToolCall(let value): + self = .customToolCall(value) + case .customToolCallOutputResource(let value): + self = .customToolCallOutputResource(value) + } + } +} diff --git a/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift b/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift index 94253719..38ace8c5 100644 --- a/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift +++ b/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift @@ -10,7 +10,6 @@ import Foundation /// Improved interface to use instead of generated `Components.Schemas.ResponseStreamEvent` public enum ResponseStreamEvent: Codable, Equatable, Sendable { public typealias Schemas = Components.Schemas - public typealias OutputItem = Components.Schemas.OutputItem public typealias OutputContent = Components.Schemas.OutputContent public typealias OutputText = Components.Schemas.OutputTextContent public typealias Annotation = Components.Schemas.Annotation diff --git a/Tests/OpenAITests/ResponsesEndpointTests.swift b/Tests/OpenAITests/ResponsesEndpointTests.swift index cdcff55e..6ca04ae3 100644 --- a/Tests/OpenAITests/ResponsesEndpointTests.swift +++ b/Tests/OpenAITests/ResponsesEndpointTests.swift @@ -119,7 +119,7 @@ class ResponsesEndpointTests: XCTestCase { XCTFail("Expected tool in response to be a function") } } - private func makeResponse(output: [Components.Schemas.OutputItem] = [], tools: [Tool] = []) -> ResponseObject { + private func makeResponse(output: [OutputItem] = [], tools: [Tool] = []) -> ResponseObject { .init( createdAt: 123, error: nil, From 626c71298acd087de08231741f64a48acf829a22 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Sat, 16 May 2026 20:45:54 +0300 Subject: [PATCH 10/31] Fix Demo app build errors after OpenAPI spec update Co-Authored-By: Claude Sonnet 4.6 --- .../xcshareddata/swiftpm/Package.resolved | 80 ++++++++++++++----- Demo/DemoChat/Package.resolved | 67 +++++++++++----- Demo/DemoChat/Sources/MCPToolsStore.swift | 2 +- Demo/DemoChat/Sources/ResponsesStore.swift | 57 ++++++------- 4 files changed, 132 insertions(+), 74 deletions(-) diff --git a/Demo/Demo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Demo/Demo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved index 526c1e9c..7b68eb0e 100644 --- a/Demo/Demo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved +++ b/Demo/Demo.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved @@ -1,5 +1,5 @@ { - "originHash" : "04b998cb575c58f627f05521d8d4107ab4f5a6d6d9a1d5720849f5fca454dce9", + "originHash" : "bcd79666ae410601a4f1ded1094921cb30aa100078efb734690a128ae00006a7", "pins" : [ { "identity" : "activityindicatorview", @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/exyte/AnchoredPopup.git", "state" : { - "revision" : "29fd1404c093cda93d949763ee711d1a892069ea", - "version" : "1.0.5" + "revision" : "2fb9d1ac101b86cbcc12a3f8e571648ce4469d18", + "version" : "1.1.3" } }, { @@ -24,17 +24,17 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/exyte/Chat.git", "state" : { - "revision" : "83c304be3992ad67c546be00d5437f841241afb8", - "version" : "2.5.7" + "revision" : "056ee35312811844a5d257bad076423f69f4b707", + "version" : "2.7.10" } }, { "identity" : "eventsource", "kind" : "remoteSourceControl", - "location" : "https://github.com/loopwork-ai/eventsource.git", + "location" : "https://github.com/mattt/eventsource.git", "state" : { - "revision" : "07957602bb99a5355c810187e66e6ce378a1057d", - "version" : "1.1.1" + "revision" : "a3a85a85214caf642abaa96ae664e4c772a59f6e", + "version" : "1.4.1" } }, { @@ -42,8 +42,17 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/Giphy/giphy-ios-sdk", "state" : { - "revision" : "9a3970c258ef5cc005f9359ba4c6a344fe062abe", - "version" : "2.2.15" + "revision" : "3ba672878445c53c8cb87d57c3ae5cc1f3166b5b", + "version" : "2.3.2" + } + }, + { + "identity" : "kingfisher", + "kind" : "remoteSourceControl", + "location" : "https://github.com/onevcat/Kingfisher", + "state" : { + "revision" : "cf8be20d07654570554c8a8a4952bc8a5766a8b0", + "version" : "8.9.0" } }, { @@ -60,8 +69,26 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/exyte/MediaPicker.git", "state" : { - "revision" : "7067c34b6460890bdeb43ba1ab01faf901860b3e", - "version" : "3.1.2" + "revision" : "ce2eda6300337d1478a78fc033bce8dd9bf4bb2c", + "version" : "3.3.2" + } + }, + { + "identity" : "swift-atomics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-atomics.git", + "state" : { + "revision" : "b601256eab081c0f92f059e12818ac1d4f178ff7", + "version" : "1.3.0" + } + }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections.git", + "state" : { + "revision" : "fea17c02d767f46b23070fdfdacc28a03a39232a", + "version" : "1.5.1" } }, { @@ -69,8 +96,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-http-types", "state" : { - "revision" : "ef18d829e8b92d731ad27bb81583edd2094d1ce3", - "version" : "1.3.1" + "revision" : "45eb0224913ea070ec4fba17291b9e7ecf4749ca", + "version" : "1.5.1" } }, { @@ -78,8 +105,17 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-log.git", "state" : { - "revision" : "3d8596ed08bd13520157f0355e35caed215ffbfa", - "version" : "1.6.3" + "revision" : "5073617dac96330a486245e4c0179cb0a6fd2256", + "version" : "1.12.0" + } + }, + { + "identity" : "swift-nio", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio.git", + "state" : { + "revision" : "f71c8d2a5e74a2c6d11a0fbe324774b5d6084237", + "version" : "2.99.0" } }, { @@ -87,8 +123,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-openapi-runtime", "state" : { - "revision" : "8f33cc5dfe81169fb167da73584b9c72c3e8bc23", - "version" : "1.8.2" + "revision" : "f039fa6d6338aab5164f3d1be16281524c9a8f89", + "version" : "1.11.0" } }, { @@ -96,8 +132,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/modelcontextprotocol/swift-sdk.git", "state" : { - "revision" : "9742933d2ff250212a04aed39b123bcc63a21e9c", - "version" : "0.9.0" + "revision" : "a0ae212ebf6eab5f754c3129608bc5557637e605", + "version" : "0.12.1" } }, { @@ -105,8 +141,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-system.git", "state" : { - "revision" : "61e4ca4b81b9e09e2ec863b00c340eb13497dac6", - "version" : "1.5.0" + "revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df", + "version" : "1.6.4" } } ], diff --git a/Demo/DemoChat/Package.resolved b/Demo/DemoChat/Package.resolved index 72554206..7b68eb0e 100644 --- a/Demo/DemoChat/Package.resolved +++ b/Demo/DemoChat/Package.resolved @@ -15,8 +15,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/exyte/AnchoredPopup.git", "state" : { - "revision" : "d7478c34e761725ff06ad74e44e675d0d56a4150", - "version" : "1.0.7" + "revision" : "2fb9d1ac101b86cbcc12a3f8e571648ce4469d18", + "version" : "1.1.3" } }, { @@ -24,8 +24,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/exyte/Chat.git", "state" : { - "revision" : "f5d93619556fbb988985c3a5fe2444ce96190f39", - "version" : "2.7.4" + "revision" : "056ee35312811844a5d257bad076423f69f4b707", + "version" : "2.7.10" } }, { @@ -33,8 +33,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/mattt/eventsource.git", "state" : { - "revision" : "ca2a9d90cbe49e09b92f4b6ebd922c03ebea51d0", - "version" : "1.3.0" + "revision" : "a3a85a85214caf642abaa96ae664e4c772a59f6e", + "version" : "1.4.1" } }, { @@ -42,8 +42,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/Giphy/giphy-ios-sdk", "state" : { - "revision" : "37f5b1ff6cf8bc4a78c0bc5eb1b814381bac9580", - "version" : "2.2.16" + "revision" : "3ba672878445c53c8cb87d57c3ae5cc1f3166b5b", + "version" : "2.3.2" } }, { @@ -51,8 +51,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/onevcat/Kingfisher", "state" : { - "revision" : "d30a5fad881137e2267f96a8e3fc35c58999bb94", - "version" : "8.6.2" + "revision" : "cf8be20d07654570554c8a8a4952bc8a5766a8b0", + "version" : "8.9.0" } }, { @@ -69,8 +69,26 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/exyte/MediaPicker.git", "state" : { - "revision" : "fd71c0b560aa79eee1b87f73ce93fac5576a01df", - "version" : "3.2.4" + "revision" : "ce2eda6300337d1478a78fc033bce8dd9bf4bb2c", + "version" : "3.3.2" + } + }, + { + "identity" : "swift-atomics", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-atomics.git", + "state" : { + "revision" : "b601256eab081c0f92f059e12818ac1d4f178ff7", + "version" : "1.3.0" + } + }, + { + "identity" : "swift-collections", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-collections.git", + "state" : { + "revision" : "fea17c02d767f46b23070fdfdacc28a03a39232a", + "version" : "1.5.1" } }, { @@ -87,8 +105,17 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-log.git", "state" : { - "revision" : "ce592ae52f982c847a4efc0dd881cc9eb32d29f2", - "version" : "1.6.4" + "revision" : "5073617dac96330a486245e4c0179cb0a6fd2256", + "version" : "1.12.0" + } + }, + { + "identity" : "swift-nio", + "kind" : "remoteSourceControl", + "location" : "https://github.com/apple/swift-nio.git", + "state" : { + "revision" : "f71c8d2a5e74a2c6d11a0fbe324774b5d6084237", + "version" : "2.99.0" } }, { @@ -96,8 +123,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-openapi-runtime", "state" : { - "revision" : "7722cf8eac05c1f1b5b05895b04cfcc29576d9be", - "version" : "1.8.3" + "revision" : "f039fa6d6338aab5164f3d1be16281524c9a8f89", + "version" : "1.11.0" } }, { @@ -105,8 +132,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/modelcontextprotocol/swift-sdk.git", "state" : { - "revision" : "c0407a0b52677cb395d824cac2879b963075ba8c", - "version" : "0.10.2" + "revision" : "a0ae212ebf6eab5f754c3129608bc5557637e605", + "version" : "0.12.1" } }, { @@ -114,8 +141,8 @@ "kind" : "remoteSourceControl", "location" : "https://github.com/apple/swift-system.git", "state" : { - "revision" : "395a77f0aa927f0ff73941d7ac35f2b46d47c9db", - "version" : "1.6.3" + "revision" : "7c6ad0fc39d0763e0b699210e4124afd5041c5df", + "version" : "1.6.4" } } ], diff --git a/Demo/DemoChat/Sources/MCPToolsStore.swift b/Demo/DemoChat/Sources/MCPToolsStore.swift index f6a86d10..943a37b6 100644 --- a/Demo/DemoChat/Sources/MCPToolsStore.swift +++ b/Demo/DemoChat/Sources/MCPToolsStore.swift @@ -35,7 +35,7 @@ public final class MCPToolsStore: ObservableObject { public init(from tool: MCP.Tool) { self.id = tool.name self.name = tool.name - self.description = tool.description + self.description = tool.description ?? "" self.inputSchema = tool.inputSchema } } diff --git a/Demo/DemoChat/Sources/ResponsesStore.swift b/Demo/DemoChat/Sources/ResponsesStore.swift index 2f980274..9ea475b9 100644 --- a/Demo/DemoChat/Sources/ResponsesStore.swift +++ b/Demo/DemoChat/Sources/ResponsesStore.swift @@ -239,7 +239,7 @@ public final class ResponsesStore: ObservableObject { .item(.functionCallOutputItemParam(.init( callId: toolCall.callId, _type: .functionCallOutput, - output: result + output: .case1(result) ))) ]), model: model, @@ -328,7 +328,7 @@ public final class ResponsesStore: ObservableObject { var tools: [Tool] = [] if webSearchEnabled { - tools.append(.webSearchTool(.init(_type: .webSearchPreview))) + tools.append(.webSearchPreviewTool(.init(_type: .webSearchPreview))) } if functionCallingEnabled { @@ -776,10 +776,27 @@ public final class ResponsesStore: ObservableObject { ) throws { try updateMessageBeingStreamed(messageId: messageId) { message in switch outputContent { - case .OutputTextContent(let outputText): + case .outputTextContent(let outputText): message.text = outputText.text message.annotations = outputText.annotations - case .RefusalContent(let refusal): + case .refusalContent(let refusal): + message.refusalText = refusal.refusal + case .reasoningTextContent: + break + } + } + } + + private func updateMessageBeingStreamed( + messageId: String, + outputContent: Components.Schemas.OutputMessageContent + ) throws { + try updateMessageBeingStreamed(messageId: messageId) { message in + switch outputContent { + case .outputTextContent(let outputText): + message.text = outputText.text + message.annotations = outputText.annotations + case .refusalContent(let refusal): message.refusalText = refusal.refusal } } @@ -889,50 +906,28 @@ public final class ResponsesStore: ObservableObject { return nil } } - - private func conversationTurn( - fromOutputContent outputContent: ResponseStreamEvent.Schemas.OutputContent, - messageId: String, - userId: String, - username: String - ) throws -> ConversationTurn { - guard let responseBeingStreamed else { - throw StoreError.noResponseToUpdate - } - - return .init( - id: responseBeingStreamed.id, - type: .response, - chatMessage: chatMessage( - fromOutputContent: outputContent, - messageId: messageId, - userId: userId, - username: username - ) - ) - } - + private func chatMessage( - fromOutputContent outputContent: ResponseStreamEvent.Schemas.OutputContent, + fromOutputContent outputContent: Components.Schemas.OutputMessageContent, messageId: String, userId: String, username: String ) -> ExyteChat.Message { switch outputContent { - case .OutputTextContent(let outputText): + case .outputTextContent(let outputText): return makeChatMessage( withText: outputText.text, annotations: outputText.annotations, messageId: messageId, user: systemUser(withId: userId, username: username) ) - case .RefusalContent(let refusal): + case .refusalContent(let refusal): let message = ExyteChat.Message( id: messageId, user: systemUser(withId: userId, username: username), text: refusal.refusal ) - + return message } } From 1036e646ee2941a8a83c7d3805c174fd65c9f4a8 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Mon, 18 May 2026 15:45:40 +0300 Subject: [PATCH 11/31] Prefix the print, may be too long when Base64 --- Demo/DemoChat/Sources/ResponsesStore.swift | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Demo/DemoChat/Sources/ResponsesStore.swift b/Demo/DemoChat/Sources/ResponsesStore.swift index 9ea475b9..ad68db39 100644 --- a/Demo/DemoChat/Sources/ResponsesStore.swift +++ b/Demo/DemoChat/Sources/ResponsesStore.swift @@ -408,8 +408,8 @@ public final class ResponsesStore: ObservableObject { encoder.outputFormatting = .prettyPrinted let jsonData = try encoder.encode(query) if let jsonString = String(data: jsonData, encoding: .utf8) { - print("Request JSON:") - print(jsonString) + print("Request JSON, prefixed to 10000:") + print(jsonString.prefix(10000)) } } catch { print("Failed to serialize request to JSON: \(error)") From d3ff1524f5a6dc1b4d7f0ec5180148a12ba9613c Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Mon, 18 May 2026 15:47:27 +0300 Subject: [PATCH 12/31] Print error --- Demo/DemoChat/Sources/ChatStore.swift | 1 + 1 file changed, 1 insertion(+) diff --git a/Demo/DemoChat/Sources/ChatStore.swift b/Demo/DemoChat/Sources/ChatStore.swift index 994f03ca..43658cb8 100644 --- a/Demo/DemoChat/Sources/ChatStore.swift +++ b/Demo/DemoChat/Sources/ChatStore.swift @@ -231,6 +231,7 @@ public final class ChatStore: ObservableObject { try await completeConversation(conversationIndex: conversationIndex, query: chatQuery) } } catch { + print("error in func completeChat(conversationId:model:stream:):\n\(error)") conversationErrors[conversationId] = error } } From ddfd805992e43440da9c0b85034218a572c03af7 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Mon, 18 May 2026 15:50:23 +0300 Subject: [PATCH 13/31] Add spec and config --- openapi-generator-config.yaml | 13 + openapi.with-code-samples.yml | 73597 ++++++++++++++++++++++++++++++++ 2 files changed, 73610 insertions(+) create mode 100644 openapi-generator-config.yaml create mode 100644 openapi.with-code-samples.yml diff --git a/openapi-generator-config.yaml b/openapi-generator-config.yaml new file mode 100644 index 00000000..fdd5dfbf --- /dev/null +++ b/openapi-generator-config.yaml @@ -0,0 +1,13 @@ + generate: + - types + namingStrategy: idiomatic + accessModifier: public + filter: + paths: + - /audio/transcriptions + - /responses + - /responses/{response_id} + - /responses/{response_id}/input_items + schemas: + - WebSearchLocation + - WebSearchContextSize diff --git a/openapi.with-code-samples.yml b/openapi.with-code-samples.yml new file mode 100644 index 00000000..b494033d --- /dev/null +++ b/openapi.with-code-samples.yml @@ -0,0 +1,73597 @@ +openapi: 3.1.0 +info: + title: OpenAI API + description: >- + The OpenAI REST API. Please see + https://platform.openai.com/docs/api-reference for more details. + version: 2.3.0 + termsOfService: https://openai.com/policies/terms-of-use + contact: + name: OpenAI Support + url: https://help.openai.com/ + license: + name: MIT + url: https://github.com/openai/openai-openapi/blob/master/LICENSE +servers: + - url: https://api.openai.com/v1 +security: + - ApiKeyAuth: [] +tags: + - name: Assistants + description: Build Assistants that can call models and use tools. + - name: Audio + description: Turn audio into text or text into audio. + - name: Chat + description: >- + Given a list of messages comprising a conversation, the model will return + a response. + - name: Conversations + description: Manage conversations and conversation items. + - name: Completions + description: >- + Given a prompt, the model will return one or more predicted completions, + and can also return the probabilities of alternative tokens at each + position. + - name: Embeddings + description: >- + Get a vector representation of a given input that can be easily consumed + by machine learning models and algorithms. + - name: Evals + description: Manage and run evals in the OpenAI platform. + - name: Fine-tuning + description: Manage fine-tuning jobs to tailor a model to your specific training data. + - name: Graders + description: Manage and run graders in the OpenAI platform. + - name: Batch + description: Create large batches of API requests to run asynchronously. + - name: Files + description: >- + Files are used to upload documents that can be used with features like + Assistants and Fine-tuning. + - name: Uploads + description: Use Uploads to upload large files in multiple parts. + - name: Images + description: Given a prompt and/or an input image, the model will generate a new image. + - name: Models + description: List and describe the various models available in the API. + - name: Moderations + description: >- + Given text and/or image inputs, classifies if those inputs are potentially + harmful. + - name: Audit Logs + description: List user actions and configuration changes within this organization. +paths: + /assistants: + get: + operationId: listAssistants + tags: + - Assistants + summary: Returns a list of assistants. + deprecated: true + parameters: + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: before + in: query + description: > + A cursor for use in pagination. `before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the + previous page of the list. + schema: + type: string + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListAssistantsResponse' + x-oaiMeta: + name: List assistants + group: assistants + examples: + request: + curl: | + curl "https://api.openai.com/v1/assistants?order=desc&limit=20" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.beta.assistants.list() + page = page.data[0] + print(page.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myAssistants = await openai.beta.assistants.list({ + order: "desc", + limit: "20", + }); + + console.log(myAssistants.data); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + // Automatically fetches more pages as needed. + for await (const assistant of client.beta.assistants.list()) { + console.log(assistant.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Beta.Assistants.List(context.TODO(), openai.BetaAssistantListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.assistants.AssistantListPage; + import com.openai.models.beta.assistants.AssistantListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + AssistantListPage page = client.beta().assistants().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.beta.assistants.list + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1698982736, + "name": "Coding Tutor", + "description": null, + "model": "gpt-4o", + "instructions": "You are a helpful assistant designed to make me better at coding!", + "tools": [], + "tool_resources": {}, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + }, + { + "id": "asst_abc456", + "object": "assistant", + "created_at": 1698982718, + "name": "My Assistant", + "description": null, + "model": "gpt-4o", + "instructions": "You are a helpful assistant designed to make me better at coding!", + "tools": [], + "tool_resources": {}, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + }, + { + "id": "asst_abc789", + "object": "assistant", + "created_at": 1698982643, + "name": null, + "description": null, + "model": "gpt-4o", + "instructions": null, + "tools": [], + "tool_resources": {}, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + } + ], + "first_id": "asst_abc123", + "last_id": "asst_abc789", + "has_more": false + } + post: + operationId: createAssistant + tags: + - Assistants + summary: Create an assistant with a model and instructions. + deprecated: true + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateAssistantRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/AssistantObject' + x-oaiMeta: + name: Create assistant + group: assistants + examples: + - title: Code Interpreter + request: + curl: | + curl "https://api.openai.com/v1/assistants" \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", + "name": "Math Tutor", + "tools": [{"type": "code_interpreter"}], + "model": "gpt-4o" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + assistant = client.beta.assistants.create( + model="gpt-4o", + ) + print(assistant.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myAssistant = await openai.beta.assistants.create({ + instructions: + "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", + name: "Math Tutor", + tools: [{ type: "code_interpreter" }], + model: "gpt-4o", + }); + + console.log(myAssistant); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const assistant = await client.beta.assistants.create({ model: + 'gpt-4o' }); + + + console.log(assistant.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tassistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{\n\t\tModel: shared.ChatModelGPT4o,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", assistant.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.ChatModel; + import com.openai.models.beta.assistants.Assistant; + import com.openai.models.beta.assistants.AssistantCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + AssistantCreateParams params = AssistantCreateParams.builder() + .model(ChatModel.GPT_4O) + .build(); + Assistant assistant = client.beta().assistants().create(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + assistant = openai.beta.assistants.create(model: :"gpt-4o") + + puts(assistant) + response: | + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1698984975, + "name": "Math Tutor", + "description": null, + "model": "gpt-4o", + "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", + "tools": [ + { + "type": "code_interpreter" + } + ], + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + } + - title: Files + request: + curl: | + curl https://api.openai.com/v1/assistants \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", + "tools": [{"type": "file_search"}], + "tool_resources": {"file_search": {"vector_store_ids": ["vs_123"]}}, + "model": "gpt-4o" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + assistant = client.beta.assistants.create( + model="gpt-4o", + ) + print(assistant.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myAssistant = await openai.beta.assistants.create({ + instructions: + "You are an HR bot, and you have access to files to answer employee questions about company policies.", + name: "HR Helper", + tools: [{ type: "file_search" }], + tool_resources: { + file_search: { + vector_store_ids: ["vs_123"] + } + }, + model: "gpt-4o" + }); + + console.log(myAssistant); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const assistant = await client.beta.assistants.create({ model: + 'gpt-4o' }); + + + console.log(assistant.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tassistant, err := client.Beta.Assistants.New(context.TODO(), openai.BetaAssistantNewParams{\n\t\tModel: shared.ChatModelGPT4o,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", assistant.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.ChatModel; + import com.openai.models.beta.assistants.Assistant; + import com.openai.models.beta.assistants.AssistantCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + AssistantCreateParams params = AssistantCreateParams.builder() + .model(ChatModel.GPT_4O) + .build(); + Assistant assistant = client.beta().assistants().create(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + assistant = openai.beta.assistants.create(model: :"gpt-4o") + + puts(assistant) + response: | + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1699009403, + "name": "HR Helper", + "description": null, + "model": "gpt-4o", + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", + "tools": [ + { + "type": "file_search" + } + ], + "tool_resources": { + "file_search": { + "vector_store_ids": ["vs_123"] + } + }, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + } + /assistants/{assistant_id}: + get: + operationId: getAssistant + tags: + - Assistants + summary: Retrieves an assistant. + deprecated: true + parameters: + - in: path + name: assistant_id + required: true + schema: + type: string + description: The ID of the assistant to retrieve. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/AssistantObject' + x-oaiMeta: + name: Retrieve assistant + group: assistants + examples: + request: + curl: | + curl https://api.openai.com/v1/assistants/asst_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + assistant = client.beta.assistants.retrieve( + "assistant_id", + ) + print(assistant.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myAssistant = await openai.beta.assistants.retrieve( + "asst_abc123" + ); + + console.log(myAssistant); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const assistant = await + client.beta.assistants.retrieve('assistant_id'); + + + console.log(assistant.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tassistant, err := client.Beta.Assistants.Get(context.TODO(), \"assistant_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", assistant.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.assistants.Assistant; + import com.openai.models.beta.assistants.AssistantRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Assistant assistant = client.beta().assistants().retrieve("assistant_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + assistant = openai.beta.assistants.retrieve("assistant_id") + + puts(assistant) + response: | + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1699009709, + "name": "HR Helper", + "description": null, + "model": "gpt-4o", + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies.", + "tools": [ + { + "type": "file_search" + } + ], + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + } + post: + operationId: modifyAssistant + tags: + - Assistants + summary: Modifies an assistant. + deprecated: true + parameters: + - in: path + name: assistant_id + required: true + schema: + type: string + description: The ID of the assistant to modify. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ModifyAssistantRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/AssistantObject' + x-oaiMeta: + name: Modify assistant + group: assistants + examples: + request: + curl: | + curl https://api.openai.com/v1/assistants/asst_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", + "tools": [{"type": "file_search"}], + "model": "gpt-4o" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + assistant = client.beta.assistants.update( + assistant_id="assistant_id", + ) + print(assistant.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myUpdatedAssistant = await openai.beta.assistants.update( + "asst_abc123", + { + instructions: + "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", + name: "HR Helper", + tools: [{ type: "file_search" }], + model: "gpt-4o" + } + ); + + console.log(myUpdatedAssistant); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const assistant = await + client.beta.assistants.update('assistant_id'); + + + console.log(assistant.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tassistant, err := client.Beta.Assistants.Update(\n\t\tcontext.TODO(),\n\t\t\"assistant_id\",\n\t\topenai.BetaAssistantUpdateParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", assistant.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.assistants.Assistant; + import com.openai.models.beta.assistants.AssistantUpdateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Assistant assistant = client.beta().assistants().update("assistant_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + assistant = openai.beta.assistants.update("assistant_id") + + puts(assistant) + response: | + { + "id": "asst_123", + "object": "assistant", + "created_at": 1699009709, + "name": "HR Helper", + "description": null, + "model": "gpt-4o", + "instructions": "You are an HR bot, and you have access to files to answer employee questions about company policies. Always response with info from either of the files.", + "tools": [ + { + "type": "file_search" + } + ], + "tool_resources": { + "file_search": { + "vector_store_ids": [] + } + }, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + } + delete: + operationId: deleteAssistant + tags: + - Assistants + summary: Delete an assistant. + deprecated: true + parameters: + - in: path + name: assistant_id + required: true + schema: + type: string + description: The ID of the assistant to delete. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteAssistantResponse' + x-oaiMeta: + name: Delete assistant + group: assistants + examples: + request: + curl: | + curl https://api.openai.com/v1/assistants/asst_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -X DELETE + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + assistant_deleted = client.beta.assistants.delete( + "assistant_id", + ) + print(assistant_deleted.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const response = await openai.beta.assistants.delete("asst_abc123"); + + console.log(response); + } + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const assistantDeleted = await + client.beta.assistants.delete('assistant_id'); + + + console.log(assistantDeleted.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tassistantDeleted, err := client.Beta.Assistants.Delete(context.TODO(), \"assistant_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", assistantDeleted.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.assistants.AssistantDeleteParams; + import com.openai.models.beta.assistants.AssistantDeleted; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + AssistantDeleted assistantDeleted = client.beta().assistants().delete("assistant_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + assistant_deleted = openai.beta.assistants.delete("assistant_id") + + puts(assistant_deleted) + response: | + { + "id": "asst_abc123", + "object": "assistant.deleted", + "deleted": true + } + /audio/speech: + post: + operationId: createSpeech + tags: + - Audio + summary: | + Generates audio from the input text. + + Returns the audio file content, or a stream of audio events. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateSpeechRequest' + responses: + '200': + description: OK + headers: + Transfer-Encoding: + schema: + type: string + description: chunked + content: + application/octet-stream: + schema: + type: string + format: binary + text/event-stream: + schema: + $ref: '#/components/schemas/CreateSpeechResponseStreamEvent' + x-oaiMeta: + name: Create speech + group: audio + examples: + - title: Default + request: + curl: | + curl https://api.openai.com/v1/audio/speech \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gpt-4o-mini-tts", + "input": "The quick brown fox jumped over the lazy dog.", + "voice": "alloy" + }' \ + --output speech.mp3 + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + speech = client.audio.speech.create( + input="input", + model="tts-1", + voice="alloy", + ) + print(speech) + content = speech.read() + print(content) + javascript: | + import fs from "fs"; + import path from "path"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const speechFile = path.resolve("./speech.mp3"); + + async function main() { + const mp3 = await openai.audio.speech.create({ + model: "gpt-4o-mini-tts", + voice: "alloy", + input: "Today is a wonderful day to build something people love!", + }); + console.log(speechFile); + const buffer = Buffer.from(await mp3.arrayBuffer()); + await fs.promises.writeFile(speechFile, buffer); + } + main(); + csharp: | + using System; + using System.IO; + + using OpenAI.Audio; + + AudioClient client = new( + model: "gpt-4o-mini-tts", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + BinaryData speech = client.GenerateSpeech( + text: "The quick brown fox jumped over the lazy dog.", + voice: GeneratedSpeechVoice.Alloy + ); + + using FileStream stream = File.OpenWrite("speech.mp3"); + speech.ToStream().CopyTo(stream); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const speech = await client.audio.speech.create({ + input: 'input', + model: 'tts-1', + voice: 'alloy', + }); + + console.log(speech); + + const content = await speech.blob(); + console.log(content); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tspeech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{\n\t\tInput: \"input\",\n\t\tModel: openai.SpeechModelTTS1,\n\t\tVoice: openai.AudioSpeechNewParamsVoiceUnion{\n\t\t\tOfAudioSpeechNewsVoiceString2: openai.String(\"alloy\"),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", speech)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.core.http.HttpResponse; + import com.openai.models.audio.speech.SpeechCreateParams; + import com.openai.models.audio.speech.SpeechModel; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + SpeechCreateParams params = SpeechCreateParams.builder() + .input("input") + .model(SpeechModel.TTS_1) + .voice(SpeechCreateParams.Voice.UnionMember1.ALLOY) + .build(); + HttpResponse speech = client.audio().speech().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + speech = openai.audio.speech.create(input: "input", model: + :"tts-1", voice: :alloy) + + + puts(speech) + - title: SSE Stream Format + request: + curl: | + curl https://api.openai.com/v1/audio/speech \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gpt-4o-mini-tts", + "input": "The quick brown fox jumped over the lazy dog.", + "voice": "alloy", + "stream_format": "sse" + }' + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const speech = await client.audio.speech.create({ + input: 'input', + model: 'tts-1', + voice: 'alloy', + }); + + console.log(speech); + + const content = await speech.blob(); + console.log(content); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + speech = client.audio.speech.create( + input="input", + model="tts-1", + voice="alloy", + ) + print(speech) + content = speech.read() + print(content) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tspeech, err := client.Audio.Speech.New(context.TODO(), openai.AudioSpeechNewParams{\n\t\tInput: \"input\",\n\t\tModel: openai.SpeechModelTTS1,\n\t\tVoice: openai.AudioSpeechNewParamsVoiceUnion{\n\t\t\tOfAudioSpeechNewsVoiceString2: openai.String(\"alloy\"),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", speech)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.core.http.HttpResponse; + import com.openai.models.audio.speech.SpeechCreateParams; + import com.openai.models.audio.speech.SpeechModel; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + SpeechCreateParams params = SpeechCreateParams.builder() + .input("input") + .model(SpeechModel.TTS_1) + .voice(SpeechCreateParams.Voice.UnionMember1.ALLOY) + .build(); + HttpResponse speech = client.audio().speech().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + speech = openai.audio.speech.create(input: "input", model: + :"tts-1", voice: :alloy) + + + puts(speech) + /audio/transcriptions: + post: + operationId: createTranscription + tags: + - Audio + summary: > + Transcribes audio into the input language. + + + Returns a transcription object in `json`, `diarized_json`, or + `verbose_json` + + format, or a stream of transcript events. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateTranscriptionRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + oneOf: + - $ref: '#/components/schemas/CreateTranscriptionResponseJson' + - $ref: >- + #/components/schemas/CreateTranscriptionResponseDiarizedJson + - $ref: >- + #/components/schemas/CreateTranscriptionResponseVerboseJson + text/event-stream: + schema: + $ref: '#/components/schemas/CreateTranscriptionResponseStreamEvent' + x-oaiMeta: + name: Create transcription + group: audio + examples: + - title: Default + request: + curl: | + curl https://api.openai.com/v1/audio/transcriptions \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: multipart/form-data" \ + -F file="@/path/to/file/audio.mp3" \ + -F model="gpt-4o-transcribe" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for transcription in client.audio.transcriptions.create( + file=b"Example data", + model="gpt-4o-transcribe", + ): + print(transcription) + javascript: | + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const transcription = await openai.audio.transcriptions.create({ + file: fs.createReadStream("audio.mp3"), + model: "gpt-4o-transcribe", + }); + + console.log(transcription.text); + } + main(); + csharp: > + using System; + + + using OpenAI.Audio; + + string audioFilePath = "audio.mp3"; + + + AudioClient client = new( + model: "gpt-4o-transcribe", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + AudioTranscription transcription = + client.TranscribeAudio(audioFilePath); + + + Console.WriteLine($"{transcription.Text}"); + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const transcription = await client.audio.transcriptions.create({ + file: fs.createReadStream('speech.mp3'), + model: 'gpt-4o-transcribe', + }); + + console.log(transcription); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\ttranscription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\tModel: openai.AudioModelGPT4oTranscribe,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", transcription)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.audio.AudioModel; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateParams; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateResponse; + + import java.io.ByteArrayInputStream; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + TranscriptionCreateParams params = TranscriptionCreateParams.builder() + .file(new ByteArrayInputStream("Example data".getBytes())) + .model(AudioModel.GPT_4O_TRANSCRIBE) + .build(); + TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + transcription = openai.audio.transcriptions.create(file: + StringIO.new("Example data"), model: :"gpt-4o-transcribe") + + + puts(transcription) + response: | + { + "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that.", + "usage": { + "type": "tokens", + "input_tokens": 14, + "input_token_details": { + "text_tokens": 0, + "audio_tokens": 14 + }, + "output_tokens": 45, + "total_tokens": 59 + } + } + - title: Diarization + request: + curl: | + curl https://api.openai.com/v1/audio/transcriptions \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: multipart/form-data" \ + -F file="@/path/to/file/meeting.wav" \ + -F model="gpt-4o-transcribe-diarize" \ + -F response_format="diarized_json" \ + -F chunking_strategy=auto \ + -F 'known_speaker_names[]=agent' \ + -F 'known_speaker_references[]=data:audio/wav;base64,AAA...' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for transcription in client.audio.transcriptions.create( + file=b"Example data", + model="gpt-4o-transcribe", + ): + print(transcription) + javascript: > + import fs from "fs"; + + import OpenAI from "openai"; + + + const openai = new OpenAI(); + + + const speakerRef = + fs.readFileSync("agent.wav").toString("base64"); + + + const transcript = await openai.audio.transcriptions.create({ + file: fs.createReadStream("meeting.wav"), + model: "gpt-4o-transcribe-diarize", + response_format: "diarized_json", + chunking_strategy: "auto", + extra_body: { + known_speaker_names: ["agent"], + known_speaker_references: [`data:audio/wav;base64,${speakerRef}`], + }, + }); + + + console.log(transcript.segments); + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const transcription = await client.audio.transcriptions.create({ + file: fs.createReadStream('speech.mp3'), + model: 'gpt-4o-transcribe', + }); + + console.log(transcription); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\ttranscription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\tModel: openai.AudioModelGPT4oTranscribe,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", transcription)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.audio.AudioModel; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateParams; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateResponse; + + import java.io.ByteArrayInputStream; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + TranscriptionCreateParams params = TranscriptionCreateParams.builder() + .file(new ByteArrayInputStream("Example data".getBytes())) + .model(AudioModel.GPT_4O_TRANSCRIBE) + .build(); + TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + transcription = openai.audio.transcriptions.create(file: + StringIO.new("Example data"), model: :"gpt-4o-transcribe") + + + puts(transcription) + response: | + { + "task": "transcribe", + "duration": 27.4, + "text": "Agent: Thanks for calling OpenAI support.\nA: Hi, I'm trying to enable diarization.\nAgent: Happy to walk you through the steps.", + "segments": [ + { + "type": "transcript.text.segment", + "id": "seg_001", + "start": 0.0, + "end": 4.7, + "text": "Thanks for calling OpenAI support.", + "speaker": "agent" + }, + { + "type": "transcript.text.segment", + "id": "seg_002", + "start": 4.7, + "end": 11.8, + "text": "Hi, I'm trying to enable diarization.", + "speaker": "A" + }, + { + "type": "transcript.text.segment", + "id": "seg_003", + "start": 12.1, + "end": 18.5, + "text": "Happy to walk you through the steps.", + "speaker": "agent" + } + ], + "usage": { + "type": "duration", + "seconds": 27 + } + } + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/audio/transcriptions \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: multipart/form-data" \ + -F file="@/path/to/file/audio.mp3" \ + -F model="gpt-4o-mini-transcribe" \ + -F stream=true + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for transcription in client.audio.transcriptions.create( + file=b"Example data", + model="gpt-4o-transcribe", + ): + print(transcription) + javascript: | + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const stream = await openai.audio.transcriptions.create({ + file: fs.createReadStream("audio.mp3"), + model: "gpt-4o-mini-transcribe", + stream: true, + }); + + for await (const event of stream) { + console.log(event); + } + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const transcription = await client.audio.transcriptions.create({ + file: fs.createReadStream('speech.mp3'), + model: 'gpt-4o-transcribe', + }); + + console.log(transcription); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\ttranscription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\tModel: openai.AudioModelGPT4oTranscribe,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", transcription)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.audio.AudioModel; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateParams; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateResponse; + + import java.io.ByteArrayInputStream; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + TranscriptionCreateParams params = TranscriptionCreateParams.builder() + .file(new ByteArrayInputStream("Example data".getBytes())) + .model(AudioModel.GPT_4O_TRANSCRIBE) + .build(); + TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + transcription = openai.audio.transcriptions.create(file: + StringIO.new("Example data"), model: :"gpt-4o-transcribe") + + + puts(transcription) + response: > + data: + {"type":"transcript.text.delta","delta":"I","logprobs":[{"token":"I","logprob":-0.00007588794,"bytes":[73]}]} + + + data: {"type":"transcript.text.delta","delta":" + see","logprobs":[{"token":" + see","logprob":-3.1281633e-7,"bytes":[32,115,101,101]}]} + + + data: {"type":"transcript.text.delta","delta":" + skies","logprobs":[{"token":" + skies","logprob":-2.3392786e-6,"bytes":[32,115,107,105,101,115]}]} + + + data: {"type":"transcript.text.delta","delta":" + of","logprobs":[{"token":" + of","logprob":-3.1281633e-7,"bytes":[32,111,102]}]} + + + data: {"type":"transcript.text.delta","delta":" + blue","logprobs":[{"token":" + blue","logprob":-1.0280384e-6,"bytes":[32,98,108,117,101]}]} + + + data: {"type":"transcript.text.delta","delta":" + and","logprobs":[{"token":" + and","logprob":-0.0005108566,"bytes":[32,97,110,100]}]} + + + data: {"type":"transcript.text.delta","delta":" + clouds","logprobs":[{"token":" + clouds","logprob":-1.9361265e-7,"bytes":[32,99,108,111,117,100,115]}]} + + + data: {"type":"transcript.text.delta","delta":" + of","logprobs":[{"token":" + of","logprob":-1.9361265e-7,"bytes":[32,111,102]}]} + + + data: {"type":"transcript.text.delta","delta":" + white","logprobs":[{"token":" + white","logprob":-7.89631e-7,"bytes":[32,119,104,105,116,101]}]} + + + data: + {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.0014890312,"bytes":[44]}]} + + + data: {"type":"transcript.text.delta","delta":" + the","logprobs":[{"token":" + the","logprob":-0.0110956915,"bytes":[32,116,104,101]}]} + + + data: {"type":"transcript.text.delta","delta":" + bright","logprobs":[{"token":" + bright","logprob":0.0,"bytes":[32,98,114,105,103,104,116]}]} + + + data: {"type":"transcript.text.delta","delta":" + blessed","logprobs":[{"token":" + blessed","logprob":-0.000045848617,"bytes":[32,98,108,101,115,115,101,100]}]} + + + data: {"type":"transcript.text.delta","delta":" + days","logprobs":[{"token":" + days","logprob":-0.000010802739,"bytes":[32,100,97,121,115]}]} + + + data: + {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.00001700133,"bytes":[44]}]} + + + data: {"type":"transcript.text.delta","delta":" + the","logprobs":[{"token":" + the","logprob":-0.0000118755715,"bytes":[32,116,104,101]}]} + + + data: {"type":"transcript.text.delta","delta":" + dark","logprobs":[{"token":" + dark","logprob":-5.5122365e-7,"bytes":[32,100,97,114,107]}]} + + + data: {"type":"transcript.text.delta","delta":" + sacred","logprobs":[{"token":" + sacred","logprob":-5.4385737e-6,"bytes":[32,115,97,99,114,101,100]}]} + + + data: {"type":"transcript.text.delta","delta":" + nights","logprobs":[{"token":" + nights","logprob":-4.00813e-6,"bytes":[32,110,105,103,104,116,115]}]} + + + data: + {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.0036910512,"bytes":[44]}]} + + + data: {"type":"transcript.text.delta","delta":" + and","logprobs":[{"token":" + and","logprob":-0.0031903093,"bytes":[32,97,110,100]}]} + + + data: {"type":"transcript.text.delta","delta":" + I","logprobs":[{"token":" + I","logprob":-1.504853e-6,"bytes":[32,73]}]} + + + data: {"type":"transcript.text.delta","delta":" + think","logprobs":[{"token":" + think","logprob":-4.3202e-7,"bytes":[32,116,104,105,110,107]}]} + + + data: {"type":"transcript.text.delta","delta":" + to","logprobs":[{"token":" + to","logprob":-1.9361265e-7,"bytes":[32,116,111]}]} + + + data: {"type":"transcript.text.delta","delta":" + myself","logprobs":[{"token":" + myself","logprob":-1.7432603e-6,"bytes":[32,109,121,115,101,108,102]}]} + + + data: + {"type":"transcript.text.delta","delta":",","logprobs":[{"token":",","logprob":-0.29254505,"bytes":[44]}]} + + + data: {"type":"transcript.text.delta","delta":" + what","logprobs":[{"token":" + what","logprob":-0.016815351,"bytes":[32,119,104,97,116]}]} + + + data: {"type":"transcript.text.delta","delta":" + a","logprobs":[{"token":" + a","logprob":-3.1281633e-7,"bytes":[32,97]}]} + + + data: {"type":"transcript.text.delta","delta":" + wonderful","logprobs":[{"token":" + wonderful","logprob":-2.1008714e-6,"bytes":[32,119,111,110,100,101,114,102,117,108]}]} + + + data: {"type":"transcript.text.delta","delta":" + world","logprobs":[{"token":" + world","logprob":-8.180258e-6,"bytes":[32,119,111,114,108,100]}]} + + + data: + {"type":"transcript.text.delta","delta":".","logprobs":[{"token":".","logprob":-0.014231676,"bytes":[46]}]} + + + data: {"type":"transcript.text.done","text":"I see skies of blue + and clouds of white, the bright blessed days, the dark sacred + nights, and I think to myself, what a wonderful + world.","logprobs":[{"token":"I","logprob":-0.00007588794,"bytes":[73]},{"token":" + see","logprob":-3.1281633e-7,"bytes":[32,115,101,101]},{"token":" + skies","logprob":-2.3392786e-6,"bytes":[32,115,107,105,101,115]},{"token":" + of","logprob":-3.1281633e-7,"bytes":[32,111,102]},{"token":" + blue","logprob":-1.0280384e-6,"bytes":[32,98,108,117,101]},{"token":" + and","logprob":-0.0005108566,"bytes":[32,97,110,100]},{"token":" + clouds","logprob":-1.9361265e-7,"bytes":[32,99,108,111,117,100,115]},{"token":" + of","logprob":-1.9361265e-7,"bytes":[32,111,102]},{"token":" + white","logprob":-7.89631e-7,"bytes":[32,119,104,105,116,101]},{"token":",","logprob":-0.0014890312,"bytes":[44]},{"token":" + the","logprob":-0.0110956915,"bytes":[32,116,104,101]},{"token":" + bright","logprob":0.0,"bytes":[32,98,114,105,103,104,116]},{"token":" + blessed","logprob":-0.000045848617,"bytes":[32,98,108,101,115,115,101,100]},{"token":" + days","logprob":-0.000010802739,"bytes":[32,100,97,121,115]},{"token":",","logprob":-0.00001700133,"bytes":[44]},{"token":" + the","logprob":-0.0000118755715,"bytes":[32,116,104,101]},{"token":" + dark","logprob":-5.5122365e-7,"bytes":[32,100,97,114,107]},{"token":" + sacred","logprob":-5.4385737e-6,"bytes":[32,115,97,99,114,101,100]},{"token":" + nights","logprob":-4.00813e-6,"bytes":[32,110,105,103,104,116,115]},{"token":",","logprob":-0.0036910512,"bytes":[44]},{"token":" + and","logprob":-0.0031903093,"bytes":[32,97,110,100]},{"token":" + I","logprob":-1.504853e-6,"bytes":[32,73]},{"token":" + think","logprob":-4.3202e-7,"bytes":[32,116,104,105,110,107]},{"token":" + to","logprob":-1.9361265e-7,"bytes":[32,116,111]},{"token":" + myself","logprob":-1.7432603e-6,"bytes":[32,109,121,115,101,108,102]},{"token":",","logprob":-0.29254505,"bytes":[44]},{"token":" + what","logprob":-0.016815351,"bytes":[32,119,104,97,116]},{"token":" + a","logprob":-3.1281633e-7,"bytes":[32,97]},{"token":" + wonderful","logprob":-2.1008714e-6,"bytes":[32,119,111,110,100,101,114,102,117,108]},{"token":" + world","logprob":-8.180258e-6,"bytes":[32,119,111,114,108,100]},{"token":".","logprob":-0.014231676,"bytes":[46]}],"usage":{"input_tokens":14,"input_token_details":{"text_tokens":0,"audio_tokens":14},"output_tokens":45,"total_tokens":59}} + - title: Logprobs + request: + curl: | + curl https://api.openai.com/v1/audio/transcriptions \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: multipart/form-data" \ + -F file="@/path/to/file/audio.mp3" \ + -F "include[]=logprobs" \ + -F model="gpt-4o-transcribe" \ + -F response_format="json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for transcription in client.audio.transcriptions.create( + file=b"Example data", + model="gpt-4o-transcribe", + ): + print(transcription) + javascript: | + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const transcription = await openai.audio.transcriptions.create({ + file: fs.createReadStream("audio.mp3"), + model: "gpt-4o-transcribe", + response_format: "json", + include: ["logprobs"] + }); + + console.log(transcription); + } + main(); + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const transcription = await client.audio.transcriptions.create({ + file: fs.createReadStream('speech.mp3'), + model: 'gpt-4o-transcribe', + }); + + console.log(transcription); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\ttranscription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\tModel: openai.AudioModelGPT4oTranscribe,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", transcription)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.audio.AudioModel; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateParams; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateResponse; + + import java.io.ByteArrayInputStream; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + TranscriptionCreateParams params = TranscriptionCreateParams.builder() + .file(new ByteArrayInputStream("Example data".getBytes())) + .model(AudioModel.GPT_4O_TRANSCRIBE) + .build(); + TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + transcription = openai.audio.transcriptions.create(file: + StringIO.new("Example data"), model: :"gpt-4o-transcribe") + + + puts(transcription) + response: | + { + "text": "Hey, my knee is hurting and I want to see the doctor tomorrow ideally.", + "logprobs": [ + { "token": "Hey", "logprob": -1.0415299, "bytes": [72, 101, 121] }, + { "token": ",", "logprob": -9.805982e-5, "bytes": [44] }, + { "token": " my", "logprob": -0.00229799, "bytes": [32, 109, 121] }, + { + "token": " knee", + "logprob": -4.7159858e-5, + "bytes": [32, 107, 110, 101, 101] + }, + { "token": " is", "logprob": -0.043909557, "bytes": [32, 105, 115] }, + { + "token": " hurting", + "logprob": -1.1041146e-5, + "bytes": [32, 104, 117, 114, 116, 105, 110, 103] + }, + { "token": " and", "logprob": -0.011076359, "bytes": [32, 97, 110, 100] }, + { "token": " I", "logprob": -5.3193703e-6, "bytes": [32, 73] }, + { + "token": " want", + "logprob": -0.0017156356, + "bytes": [32, 119, 97, 110, 116] + }, + { "token": " to", "logprob": -7.89631e-7, "bytes": [32, 116, 111] }, + { "token": " see", "logprob": -5.5122365e-7, "bytes": [32, 115, 101, 101] }, + { "token": " the", "logprob": -0.0040786397, "bytes": [32, 116, 104, 101] }, + { + "token": " doctor", + "logprob": -2.3392786e-6, + "bytes": [32, 100, 111, 99, 116, 111, 114] + }, + { + "token": " tomorrow", + "logprob": -7.89631e-7, + "bytes": [32, 116, 111, 109, 111, 114, 114, 111, 119] + }, + { + "token": " ideally", + "logprob": -0.5800861, + "bytes": [32, 105, 100, 101, 97, 108, 108, 121] + }, + { "token": ".", "logprob": -0.00011093382, "bytes": [46] } + ], + "usage": { + "type": "tokens", + "input_tokens": 14, + "input_token_details": { + "text_tokens": 0, + "audio_tokens": 14 + }, + "output_tokens": 45, + "total_tokens": 59 + } + } + - title: Word timestamps + request: + curl: | + curl https://api.openai.com/v1/audio/transcriptions \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: multipart/form-data" \ + -F file="@/path/to/file/audio.mp3" \ + -F "timestamp_granularities[]=word" \ + -F model="whisper-1" \ + -F response_format="verbose_json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for transcription in client.audio.transcriptions.create( + file=b"Example data", + model="gpt-4o-transcribe", + ): + print(transcription) + javascript: | + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const transcription = await openai.audio.transcriptions.create({ + file: fs.createReadStream("audio.mp3"), + model: "whisper-1", + response_format: "verbose_json", + timestamp_granularities: ["word"] + }); + + console.log(transcription.text); + } + main(); + csharp: > + using System; + + + using OpenAI.Audio; + + + string audioFilePath = "audio.mp3"; + + + AudioClient client = new( + model: "whisper-1", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + AudioTranscriptionOptions options = new() + + { + ResponseFormat = AudioTranscriptionFormat.Verbose, + TimestampGranularities = AudioTimestampGranularities.Word, + }; + + + AudioTranscription transcription = + client.TranscribeAudio(audioFilePath, options); + + + Console.WriteLine($"{transcription.Text}"); + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const transcription = await client.audio.transcriptions.create({ + file: fs.createReadStream('speech.mp3'), + model: 'gpt-4o-transcribe', + }); + + console.log(transcription); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\ttranscription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\tModel: openai.AudioModelGPT4oTranscribe,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", transcription)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.audio.AudioModel; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateParams; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateResponse; + + import java.io.ByteArrayInputStream; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + TranscriptionCreateParams params = TranscriptionCreateParams.builder() + .file(new ByteArrayInputStream("Example data".getBytes())) + .model(AudioModel.GPT_4O_TRANSCRIBE) + .build(); + TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + transcription = openai.audio.transcriptions.create(file: + StringIO.new("Example data"), model: :"gpt-4o-transcribe") + + + puts(transcription) + response: | + { + "task": "transcribe", + "language": "english", + "duration": 8.470000267028809, + "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.", + "words": [ + { + "word": "The", + "start": 0.0, + "end": 0.23999999463558197 + }, + ... + { + "word": "volleyball", + "start": 7.400000095367432, + "end": 7.900000095367432 + } + ], + "usage": { + "type": "duration", + "seconds": 9 + } + } + - title: Segment timestamps + request: + curl: | + curl https://api.openai.com/v1/audio/transcriptions \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: multipart/form-data" \ + -F file="@/path/to/file/audio.mp3" \ + -F "timestamp_granularities[]=segment" \ + -F model="whisper-1" \ + -F response_format="verbose_json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for transcription in client.audio.transcriptions.create( + file=b"Example data", + model="gpt-4o-transcribe", + ): + print(transcription) + javascript: | + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const transcription = await openai.audio.transcriptions.create({ + file: fs.createReadStream("audio.mp3"), + model: "whisper-1", + response_format: "verbose_json", + timestamp_granularities: ["segment"] + }); + + console.log(transcription.text); + } + main(); + csharp: > + using System; + + + using OpenAI.Audio; + + + string audioFilePath = "audio.mp3"; + + + AudioClient client = new( + model: "whisper-1", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + AudioTranscriptionOptions options = new() + + { + ResponseFormat = AudioTranscriptionFormat.Verbose, + TimestampGranularities = AudioTimestampGranularities.Segment, + }; + + + AudioTranscription transcription = + client.TranscribeAudio(audioFilePath, options); + + + Console.WriteLine($"{transcription.Text}"); + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const transcription = await client.audio.transcriptions.create({ + file: fs.createReadStream('speech.mp3'), + model: 'gpt-4o-transcribe', + }); + + console.log(transcription); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\ttranscription, err := client.Audio.Transcriptions.New(context.TODO(), openai.AudioTranscriptionNewParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\tModel: openai.AudioModelGPT4oTranscribe,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", transcription)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.audio.AudioModel; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateParams; + + import + com.openai.models.audio.transcriptions.TranscriptionCreateResponse; + + import java.io.ByteArrayInputStream; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + TranscriptionCreateParams params = TranscriptionCreateParams.builder() + .file(new ByteArrayInputStream("Example data".getBytes())) + .model(AudioModel.GPT_4O_TRANSCRIBE) + .build(); + TranscriptionCreateResponse transcription = client.audio().transcriptions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + transcription = openai.audio.transcriptions.create(file: + StringIO.new("Example data"), model: :"gpt-4o-transcribe") + + + puts(transcription) + response: | + { + "task": "transcribe", + "language": "english", + "duration": 8.470000267028809, + "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.", + "segments": [ + { + "id": 0, + "seek": 0, + "start": 0.0, + "end": 3.319999933242798, + "text": " The beach was a popular spot on a hot summer day.", + "tokens": [ + 50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530 + ], + "temperature": 0.0, + "avg_logprob": -0.2860786020755768, + "compression_ratio": 1.2363636493682861, + "no_speech_prob": 0.00985979475080967 + }, + ... + ], + "usage": { + "type": "duration", + "seconds": 9 + } + } + /audio/translations: + post: + operationId: createTranslation + tags: + - Audio + summary: Translates audio into English. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateTranslationRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + oneOf: + - $ref: '#/components/schemas/CreateTranslationResponseJson' + - $ref: '#/components/schemas/CreateTranslationResponseVerboseJson' + x-oaiMeta: + name: Create translation + group: audio + examples: + request: + curl: | + curl https://api.openai.com/v1/audio/translations \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: multipart/form-data" \ + -F file="@/path/to/file/german.m4a" \ + -F model="whisper-1" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + translation = client.audio.translations.create( + file=b"Example data", + model="whisper-1", + ) + print(translation) + javascript: | + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const translation = await openai.audio.translations.create({ + file: fs.createReadStream("speech.mp3"), + model: "whisper-1", + }); + + console.log(translation.text); + } + main(); + csharp: > + using System; + + + using OpenAI.Audio; + + + string audioFilePath = "audio.mp3"; + + + AudioClient client = new( + model: "whisper-1", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + AudioTranscription transcription = + client.TranscribeAudio(audioFilePath); + + + Console.WriteLine($"{transcription.Text}"); + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const translation = await client.audio.translations.create({ + file: fs.createReadStream('speech.mp3'), + model: 'whisper-1', + }); + + console.log(translation); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\ttranslation, err := client.Audio.Translations.New(context.TODO(), openai.AudioTranslationNewParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\tModel: openai.AudioModelWhisper1,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", translation)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.audio.AudioModel; + + import + com.openai.models.audio.translations.TranslationCreateParams; + + import + com.openai.models.audio.translations.TranslationCreateResponse; + + import java.io.ByteArrayInputStream; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + TranslationCreateParams params = TranslationCreateParams.builder() + .file(new ByteArrayInputStream("Example data".getBytes())) + .model(AudioModel.WHISPER_1) + .build(); + TranslationCreateResponse translation = client.audio().translations().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + translation = openai.audio.translations.create(file: + StringIO.new("Example data"), model: :"whisper-1") + + + puts(translation) + response: | + { + "text": "Hello, my name is Wolfgang and I come from Germany. Where are you heading today?" + } + /audio/voice_consents: + post: + operationId: createVoiceConsent + tags: + - Audio + summary: Upload a voice consent recording. + description: > + Upload a consent recording that authorizes creation of a custom voice. + + + See the [custom voices guide](/docs/guides/text-to-speech#custom-voices) + for requirements and best practices. Custom voices are limited to + eligible customers. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateVoiceConsentRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VoiceConsentResource' + x-oaiMeta: + name: Create voice consent + group: audio + examples: + request: + curl: | + curl https://api.openai.com/v1/audio/voice_consents \ + -X POST \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F "name=John Doe" \ + -F "language=en-US" \ + -F "recording=@$HOME/consent_recording.wav;type=audio/x-wav" + response: '' + get: + operationId: listVoiceConsents + tags: + - Audio + summary: Returns a list of voice consent recordings. + description: > + List consent recordings available to your organization for creating + custom voices. + + + See the [custom voices + guide](/docs/guides/text-to-speech#custom-voices). Custom voices are + limited to eligible customers. + parameters: + - in: query + name: after + required: false + schema: + type: string + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VoiceConsentListResource' + x-oaiMeta: + name: List voice consents + group: audio + examples: + request: + curl: | + curl https://api.openai.com/v1/audio/voice_consents?limit=20 \ + -H "Authorization: Bearer $OPENAI_API_KEY" + response: '' + /audio/voice_consents/{consent_id}: + get: + operationId: getVoiceConsent + tags: + - Audio + summary: Retrieves a voice consent recording. + description: > + Retrieve consent recording metadata used for creating custom voices. + + + See the [custom voices + guide](/docs/guides/text-to-speech#custom-voices). Custom voices are + limited to eligible customers. + parameters: + - in: path + name: consent_id + required: true + schema: + type: string + description: The ID of the consent recording to retrieve. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VoiceConsentResource' + x-oaiMeta: + name: Retrieve voice consent + group: audio + examples: + request: + curl: | + curl https://api.openai.com/v1/audio/voice_consents/cons_1234 \ + -H "Authorization: Bearer $OPENAI_API_KEY" + response: '' + post: + operationId: updateVoiceConsent + tags: + - Audio + summary: Updates a voice consent recording (metadata only). + description: > + Update consent recording metadata used for creating custom voices. This + endpoint updates metadata only and does not replace the underlying + audio. + + + See the [custom voices + guide](/docs/guides/text-to-speech#custom-voices). Custom voices are + limited to eligible customers. + parameters: + - in: path + name: consent_id + required: true + schema: + type: string + description: The ID of the consent recording to update. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateVoiceConsentRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VoiceConsentResource' + x-oaiMeta: + name: Update voice consent + group: audio + examples: + request: + curl: | + curl https://api.openai.com/v1/audio/voice_consents/cons_1234 \ + -X POST \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "John Doe" + }' + response: '' + delete: + operationId: deleteVoiceConsent + tags: + - Audio + summary: Deletes a voice consent recording. + description: > + Delete a consent recording that was uploaded for creating custom voices. + + + See the [custom voices + guide](/docs/guides/text-to-speech#custom-voices). Custom voices are + limited to eligible customers. + parameters: + - in: path + name: consent_id + required: true + schema: + type: string + description: The ID of the consent recording to delete. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VoiceConsentDeletedResource' + x-oaiMeta: + name: Delete voice consent + group: audio + examples: + request: + curl: | + curl https://api.openai.com/v1/audio/voice_consents/cons_1234 \ + -X DELETE \ + -H "Authorization: Bearer $OPENAI_API_KEY" + response: '' + /audio/voices: + post: + operationId: createVoice + tags: + - Audio + summary: Creates a custom voice. + description: > + Create a custom voice you can use for audio output (for example, in + Text-to-Speech and the Realtime API). This requires an audio sample and + a previously uploaded consent recording. + + + See the [custom voices guide](/docs/guides/text-to-speech#custom-voices) + for requirements and best practices. Custom voices are limited to + eligible customers. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateVoiceRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VoiceResource' + x-oaiMeta: + name: Create voice + group: audio + examples: + request: + curl: | + curl https://api.openai.com/v1/audio/voices \ + -X POST \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F "name=My new voice" \ + -F "consent=cons_1234" \ + -F "audio_sample=@$HOME/audio_sample.wav;type=audio/x-wav" + response: '' + /batches: + post: + summary: Creates and executes a batch from an uploaded file of requests + operationId: createBatch + tags: + - Batch + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - input_file_id + - endpoint + - completion_window + properties: + input_file_id: + type: string + description: > + The ID of an uploaded file that contains requests for the + new batch. + + + See [upload file](/docs/api-reference/files/create) for how + to upload a file. + + + Your input file must be formatted as a [JSONL + file](/docs/api-reference/batch/request-input), and must be + uploaded with the purpose `batch`. The file can contain up + to 50,000 requests, and can be up to 200 MB in size. + endpoint: + type: string + enum: + - /v1/responses + - /v1/chat/completions + - /v1/embeddings + - /v1/completions + - /v1/moderations + - /v1/images/generations + - /v1/images/edits + - /v1/videos + description: >- + The endpoint to be used for all requests in the batch. + Currently `/v1/responses`, `/v1/chat/completions`, + `/v1/embeddings`, `/v1/completions`, `/v1/moderations`, + `/v1/images/generations`, `/v1/images/edits`, and + `/v1/videos` are supported. Note that `/v1/embeddings` + batches are also restricted to a maximum of 50,000 embedding + inputs across all requests in the batch. + completion_window: + type: string + enum: + - 24h + description: >- + The time frame within which the batch should be processed. + Currently only `24h` is supported. + metadata: + $ref: '#/components/schemas/Metadata' + output_expires_after: + $ref: '#/components/schemas/BatchFileExpirationAfter' + responses: + '200': + description: Batch created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Batch' + x-oaiMeta: + name: Create batch + group: batch + examples: + request: + curl: | + curl https://api.openai.com/v1/batches \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "input_file_id": "file-abc123", + "endpoint": "/v1/chat/completions", + "completion_window": "24h" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + batch = client.batches.create( + completion_window="24h", + endpoint="/v1/responses", + input_file_id="input_file_id", + ) + print(batch.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const batch = await openai.batches.create({ + input_file_id: "file-abc123", + endpoint: "/v1/chat/completions", + completion_window: "24h" + }); + + console.log(batch); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const batch = await client.batches.create({ + completion_window: '24h', + endpoint: '/v1/responses', + input_file_id: 'input_file_id', + }); + + console.log(batch.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tbatch, err := client.Batches.New(context.TODO(), openai.BatchNewParams{\n\t\tCompletionWindow: openai.BatchNewParamsCompletionWindow24h,\n\t\tEndpoint: openai.BatchNewParamsEndpointV1Responses,\n\t\tInputFileID: \"input_file_id\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", batch.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.batches.Batch; + import com.openai.models.batches.BatchCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + BatchCreateParams params = BatchCreateParams.builder() + .completionWindow(BatchCreateParams.CompletionWindow._24H) + .endpoint(BatchCreateParams.Endpoint.V1_RESPONSES) + .inputFileId("input_file_id") + .build(); + Batch batch = client.batches().create(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + batch = openai.batches.create( + completion_window: :"24h", + endpoint: :"/v1/responses", + input_file_id: "input_file_id" + ) + + puts(batch) + response: | + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/chat/completions", + "errors": null, + "input_file_id": "file-abc123", + "completion_window": "24h", + "status": "validating", + "output_file_id": null, + "error_file_id": null, + "created_at": 1711471533, + "in_progress_at": null, + "expires_at": null, + "finalizing_at": null, + "completed_at": null, + "failed_at": null, + "expired_at": null, + "cancelling_at": null, + "cancelled_at": null, + "request_counts": { + "total": 0, + "completed": 0, + "failed": 0 + }, + "metadata": { + "customer_id": "user_123456789", + "batch_description": "Nightly eval job", + } + } + get: + operationId: listBatches + tags: + - Batch + summary: List your organization's batches. + parameters: + - in: query + name: after + required: false + schema: + type: string + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + responses: + '200': + description: Batch listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ListBatchesResponse' + x-oaiMeta: + name: List batches + group: batch + examples: + request: + curl: | + curl https://api.openai.com/v1/batches?limit=2 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.batches.list() + page = page.data[0] + print(page.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const list = await openai.batches.list(); + + for await (const batch of list) { + console.log(batch); + } + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + // Automatically fetches more pages as needed. + for await (const batch of client.batches.list()) { + console.log(batch.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Batches.List(context.TODO(), openai.BatchListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.batches.BatchListPage; + import com.openai.models.batches.BatchListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + BatchListPage page = client.batches().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.batches.list + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/chat/completions", + "errors": null, + "input_file_id": "file-abc123", + "completion_window": "24h", + "status": "completed", + "output_file_id": "file-cvaTdG", + "error_file_id": "file-HOWS94", + "created_at": 1711471533, + "in_progress_at": 1711471538, + "expires_at": 1711557933, + "finalizing_at": 1711493133, + "completed_at": 1711493163, + "failed_at": null, + "expired_at": null, + "cancelling_at": null, + "cancelled_at": null, + "request_counts": { + "total": 100, + "completed": 95, + "failed": 5 + }, + "metadata": { + "customer_id": "user_123456789", + "batch_description": "Nightly job", + } + }, + { ... }, + ], + "first_id": "batch_abc123", + "last_id": "batch_abc456", + "has_more": true + } + /batches/{batch_id}: + get: + operationId: retrieveBatch + tags: + - Batch + summary: Retrieves a batch. + parameters: + - in: path + name: batch_id + required: true + schema: + type: string + description: The ID of the batch to retrieve. + responses: + '200': + description: Batch retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Batch' + x-oaiMeta: + name: Retrieve batch + group: batch + examples: + request: + curl: | + curl https://api.openai.com/v1/batches/batch_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + batch = client.batches.retrieve( + "batch_id", + ) + print(batch.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const batch = await openai.batches.retrieve("batch_abc123"); + + console.log(batch); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const batch = await client.batches.retrieve('batch_id'); + + console.log(batch.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tbatch, err := client.Batches.Get(context.TODO(), \"batch_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", batch.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.batches.Batch; + import com.openai.models.batches.BatchRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Batch batch = client.batches().retrieve("batch_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + batch = openai.batches.retrieve("batch_id") + + puts(batch) + response: | + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/completions", + "errors": null, + "input_file_id": "file-abc123", + "completion_window": "24h", + "status": "completed", + "output_file_id": "file-cvaTdG", + "error_file_id": "file-HOWS94", + "created_at": 1711471533, + "in_progress_at": 1711471538, + "expires_at": 1711557933, + "finalizing_at": 1711493133, + "completed_at": 1711493163, + "failed_at": null, + "expired_at": null, + "cancelling_at": null, + "cancelled_at": null, + "request_counts": { + "total": 100, + "completed": 95, + "failed": 5 + }, + "metadata": { + "customer_id": "user_123456789", + "batch_description": "Nightly eval job", + } + } + /batches/{batch_id}/cancel: + post: + operationId: cancelBatch + tags: + - Batch + summary: >- + Cancels an in-progress batch. The batch will be in status `cancelling` + for up to 10 minutes, before changing to `cancelled`, where it will have + partial results (if any) available in the output file. + parameters: + - in: path + name: batch_id + required: true + schema: + type: string + description: The ID of the batch to cancel. + responses: + '200': + description: Batch is cancelling. Returns the cancelling batch's details. + content: + application/json: + schema: + $ref: '#/components/schemas/Batch' + x-oaiMeta: + name: Cancel batch + group: batch + examples: + request: + curl: | + curl https://api.openai.com/v1/batches/batch_abc123/cancel \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -X POST + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + batch = client.batches.cancel( + "batch_id", + ) + print(batch.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const batch = await openai.batches.cancel("batch_abc123"); + + console.log(batch); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const batch = await client.batches.cancel('batch_id'); + + console.log(batch.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tbatch, err := client.Batches.Cancel(context.TODO(), \"batch_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", batch.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.batches.Batch; + import com.openai.models.batches.BatchCancelParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Batch batch = client.batches().cancel("batch_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + batch = openai.batches.cancel("batch_id") + + puts(batch) + response: | + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/chat/completions", + "errors": null, + "input_file_id": "file-abc123", + "completion_window": "24h", + "status": "cancelling", + "output_file_id": null, + "error_file_id": null, + "created_at": 1711471533, + "in_progress_at": 1711471538, + "expires_at": 1711557933, + "finalizing_at": null, + "completed_at": null, + "failed_at": null, + "expired_at": null, + "cancelling_at": 1711475133, + "cancelled_at": null, + "request_counts": { + "total": 100, + "completed": 23, + "failed": 1 + }, + "metadata": { + "customer_id": "user_123456789", + "batch_description": "Nightly eval job", + } + } + /chat/completions: + get: + operationId: listChatCompletions + tags: + - Chat + summary: > + List stored Chat Completions. Only Chat Completions that have been + stored + + with the `store` parameter set to `true` will be returned. + parameters: + - name: model + in: query + description: The model used to generate the Chat Completions. + required: false + schema: + type: string + - name: metadata + in: query + description: | + A list of metadata keys to filter the Chat Completions by. Example: + + `metadata[key1]=value1&metadata[key2]=value2` + required: false + schema: + $ref: '#/components/schemas/Metadata' + - name: after + in: query + description: >- + Identifier for the last chat completion from the previous pagination + request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of Chat Completions to retrieve. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: >- + Sort order for Chat Completions by timestamp. Use `asc` for + ascending order or `desc` for descending order. Defaults to `asc`. + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + responses: + '200': + description: A list of Chat Completions + content: + application/json: + schema: + $ref: '#/components/schemas/ChatCompletionList' + x-oaiMeta: + name: List Chat Completions + group: chat + path: list + examples: + request: + curl: | + curl https://api.openai.com/v1/chat/completions \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.chat.completions.list() + page = page.data[0] + print(page.id) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const chatCompletion of client.chat.completions.list()) + { + console.log(chatCompletion.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Chat.Completions.List(context.TODO(), openai.ChatCompletionListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.chat.completions.ChatCompletionListPage; + + import + com.openai.models.chat.completions.ChatCompletionListParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatCompletionListPage page = client.chat().completions().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.chat.completions.list + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "object": "chat.completion", + "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", + "model": "gpt-5.4", + "created": 1738960610, + "request_id": "req_ded8ab984ec4bf840f37566c1011c417", + "tool_choice": null, + "usage": { + "total_tokens": 31, + "completion_tokens": 18, + "prompt_tokens": 13 + }, + "seed": 4944116822809979520, + "top_p": 1.0, + "temperature": 1.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0, + "system_fingerprint": "fp_50cad350e4", + "input_user": null, + "service_tier": "default", + "tools": null, + "metadata": {}, + "choices": [ + { + "index": 0, + "message": { + "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", + "role": "assistant", + "tool_calls": null, + "function_call": null + }, + "finish_reason": "stop", + "logprobs": null + } + ], + "response_format": null + } + ], + "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", + "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", + "has_more": false + } + post: + operationId: createChatCompletion + tags: + - Chat + summary: > + **Starting a new project?** We recommend trying + [Responses](/docs/api-reference/responses) + + to take advantage of the latest OpenAI platform features. Compare + + [Chat Completions with + Responses](/docs/guides/responses-vs-chat-completions?api-mode=responses). + + + --- + + + Creates a model response for the given chat conversation. Learn more in + the + + [text generation](/docs/guides/text-generation), + [vision](/docs/guides/vision), + + and [audio](/docs/guides/audio) guides. + + + Parameter support can differ depending on the model used to generate the + + response, particularly for newer reasoning models. Parameters that are + only + + supported for reasoning models are noted below. For the current state of + + unsupported parameters in reasoning models, + + [refer to the reasoning guide](/docs/guides/reasoning). + + + Returns a chat completion object, or a streamed sequence of chat + completion + + chunk objects if the request is streamed. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateChatCompletionRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/CreateChatCompletionResponse' + text/event-stream: + schema: + $ref: '#/components/schemas/CreateChatCompletionStreamResponse' + x-oaiMeta: + name: Create chat completion + group: chat + path: create + examples: + - title: Default + request: + curl: | + curl https://api.openai.com/v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "VAR_chat_model_id", + "messages": [ + { + "role": "developer", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Hello!" + } + ] + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for completion in client.chat.completions.create( + messages=[{ + "content": "string", + "role": "developer", + }], + model="gpt-5.4", + ): + print(completion) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const completion = await openai.chat.completions.create({ + messages: [{ role: "developer", content: "You are a helpful assistant." }], + model: "VAR_chat_model_id", + store: true, + }); + + console.log(completion.choices[0]); + } + + main(); + csharp: | + using System; + using System.Collections.Generic; + + using OpenAI.Chat; + + ChatClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + List messages = + [ + new SystemChatMessage("You are a helpful assistant."), + new UserChatMessage("Hello!") + ]; + + ChatCompletion completion = client.CompleteChat(messages); + + Console.WriteLine(completion.Content[0].Text); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const chatCompletion = await client.chat.completions.create({ + messages: [{ content: 'string', role: 'developer' }], + model: 'gpt-5.4', + }); + + console.log(chatCompletion); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n\t\tMessages: []openai.ChatCompletionMessageParamUnion{{\n\t\t\tOfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n\t\t\t\tContent: openai.ChatCompletionDeveloperMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(\"string\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}},\n\t\tModel: shared.ChatModelGPT5_4,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatCompletion)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.ChatModel; + + import com.openai.models.chat.completions.ChatCompletion; + + import + com.openai.models.chat.completions.ChatCompletionCreateParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() + .addDeveloperMessage("string") + .model(ChatModel.GPT_5_4) + .build(); + ChatCompletion chatCompletion = client.chat().completions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + chat_completion = openai.chat.completions.create(messages: + [{content: "string", role: :developer}], model: :"gpt-5.4") + + + puts(chat_completion) + response: | + { + "id": "chatcmpl-B9MBs8CjcvOU2jLn4n570S5qMJKcT", + "object": "chat.completion", + "created": 1741569952, + "model": "gpt-5.4", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "Hello! How can I assist you today?", + "refusal": null, + "annotations": [] + }, + "logprobs": null, + "finish_reason": "stop" + } + ], + "usage": { + "prompt_tokens": 19, + "completion_tokens": 10, + "total_tokens": 29, + "prompt_tokens_details": { + "cached_tokens": 0, + "audio_tokens": 0 + }, + "completion_tokens_details": { + "reasoning_tokens": 0, + "audio_tokens": 0, + "accepted_prediction_tokens": 0, + "rejected_prediction_tokens": 0 + } + }, + "service_tier": "default" + } + - title: Image input + request: + curl: | + curl https://api.openai.com/v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.4", + "messages": [ + { + "role": "user", + "content": [ + { + "type": "text", + "text": "What is in this image?" + }, + { + "type": "image_url", + "image_url": { + "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" + } + } + ] + } + ], + "max_tokens": 300 + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for completion in client.chat.completions.create( + messages=[{ + "content": "string", + "role": "developer", + }], + model="gpt-5.4", + ): + print(completion) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const response = await openai.chat.completions.create({ + model: "gpt-5.4", + messages: [ + { + role: "user", + content: [ + { type: "text", text: "What's in this image?" }, + { + type: "image_url", + image_url: { + "url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", + }, + } + ], + }, + ], + }); + console.log(response.choices[0]); + } + main(); + csharp: | + using System; + using System.Collections.Generic; + + using OpenAI.Chat; + + ChatClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + List messages = + [ + new UserChatMessage( + [ + ChatMessageContentPart.CreateTextPart("What's in this image?"), + ChatMessageContentPart.CreateImagePart(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg")) + ]) + ]; + + ChatCompletion completion = client.CompleteChat(messages); + + Console.WriteLine(completion.Content[0].Text); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const chatCompletion = await client.chat.completions.create({ + messages: [{ content: 'string', role: 'developer' }], + model: 'gpt-5.4', + }); + + console.log(chatCompletion); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n\t\tMessages: []openai.ChatCompletionMessageParamUnion{{\n\t\t\tOfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n\t\t\t\tContent: openai.ChatCompletionDeveloperMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(\"string\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}},\n\t\tModel: shared.ChatModelGPT5_4,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatCompletion)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.ChatModel; + + import com.openai.models.chat.completions.ChatCompletion; + + import + com.openai.models.chat.completions.ChatCompletionCreateParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() + .addDeveloperMessage("string") + .model(ChatModel.GPT_5_4) + .build(); + ChatCompletion chatCompletion = client.chat().completions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + chat_completion = openai.chat.completions.create(messages: + [{content: "string", role: :developer}], model: :"gpt-5.4") + + + puts(chat_completion) + response: | + { + "id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG", + "object": "chat.completion", + "created": 1741570283, + "model": "gpt-5.4", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.", + "refusal": null, + "annotations": [] + }, + "logprobs": null, + "finish_reason": "stop" + } + ], + "usage": { + "prompt_tokens": 1117, + "completion_tokens": 46, + "total_tokens": 1163, + "prompt_tokens_details": { + "cached_tokens": 0, + "audio_tokens": 0 + }, + "completion_tokens_details": { + "reasoning_tokens": 0, + "audio_tokens": 0, + "accepted_prediction_tokens": 0, + "rejected_prediction_tokens": 0 + } + }, + "service_tier": "default" + } + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "VAR_chat_model_id", + "messages": [ + { + "role": "developer", + "content": "You are a helpful assistant." + }, + { + "role": "user", + "content": "Hello!" + } + ], + "stream": true + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for completion in client.chat.completions.create( + messages=[{ + "content": "string", + "role": "developer", + }], + model="gpt-5.4", + ): + print(completion) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const completion = await openai.chat.completions.create({ + model: "VAR_chat_model_id", + messages: [ + {"role": "developer", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hello!"} + ], + stream: true, + }); + + for await (const chunk of completion) { + console.log(chunk.choices[0].delta.content); + } + } + + main(); + csharp: > + using System; + + using System.ClientModel; + + using System.Collections.Generic; + + using System.Threading.Tasks; + + + using OpenAI.Chat; + + + ChatClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + List messages = + + [ + new SystemChatMessage("You are a helpful assistant."), + new UserChatMessage("Hello!") + ]; + + + AsyncCollectionResult + completionUpdates = client.CompleteChatStreamingAsync(messages); + + + await foreach (StreamingChatCompletionUpdate completionUpdate in + completionUpdates) + + { + if (completionUpdate.ContentUpdate.Count > 0) + { + Console.Write(completionUpdate.ContentUpdate[0].Text); + } + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const chatCompletion = await client.chat.completions.create({ + messages: [{ content: 'string', role: 'developer' }], + model: 'gpt-5.4', + }); + + console.log(chatCompletion); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n\t\tMessages: []openai.ChatCompletionMessageParamUnion{{\n\t\t\tOfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n\t\t\t\tContent: openai.ChatCompletionDeveloperMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(\"string\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}},\n\t\tModel: shared.ChatModelGPT5_4,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatCompletion)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.ChatModel; + + import com.openai.models.chat.completions.ChatCompletion; + + import + com.openai.models.chat.completions.ChatCompletionCreateParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() + .addDeveloperMessage("string") + .model(ChatModel.GPT_5_4) + .build(); + ChatCompletion chatCompletion = client.chat().completions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + chat_completion = openai.chat.completions.create(messages: + [{content: "string", role: :developer}], model: :"gpt-5.4") + + + puts(chat_completion) + response: > + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", + "system_fingerprint": "fp_44709d6fcb", + "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} + + + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", + "system_fingerprint": "fp_44709d6fcb", + "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} + + + .... + + + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", + "system_fingerprint": "fp_44709d6fcb", + "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + - title: Functions + request: + curl: | + curl https://api.openai.com/v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.4", + "messages": [ + { + "role": "user", + "content": "What is the weather like in Boston today?" + } + ], + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"] + } + }, + "required": ["location"] + } + } + } + ], + "tool_choice": "auto" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for completion in client.chat.completions.create( + messages=[{ + "content": "string", + "role": "developer", + }], + model="gpt-5.4", + ): + print(completion) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const messages = [{"role": "user", "content": "What's the weather like in Boston today?"}]; + const tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + } + } + ]; + + const response = await openai.chat.completions.create({ + model: "gpt-5.4", + messages: messages, + tools: tools, + tool_choice: "auto", + }); + + console.log(response); + } + + main(); + csharp: > + using System; + + using System.Collections.Generic; + + + using OpenAI.Chat; + + + ChatClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + ChatTool getCurrentWeatherTool = ChatTool.CreateFunctionTool( + functionName: "get_current_weather", + functionDescription: "Get the current weather in a given location", + functionParameters: BinaryData.FromString(""" + { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": [ "celsius", "fahrenheit" ] + } + }, + "required": [ "location" ] + } + """) + ); + + + List messages = + + [ + new UserChatMessage("What's the weather like in Boston today?"), + ]; + + + ChatCompletionOptions options = new() + + { + Tools = + { + getCurrentWeatherTool + }, + ToolChoice = ChatToolChoice.CreateAutoChoice(), + }; + + + ChatCompletion completion = client.CompleteChat(messages, + options); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const chatCompletion = await client.chat.completions.create({ + messages: [{ content: 'string', role: 'developer' }], + model: 'gpt-5.4', + }); + + console.log(chatCompletion); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n\t\tMessages: []openai.ChatCompletionMessageParamUnion{{\n\t\t\tOfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n\t\t\t\tContent: openai.ChatCompletionDeveloperMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(\"string\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}},\n\t\tModel: shared.ChatModelGPT5_4,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatCompletion)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.ChatModel; + + import com.openai.models.chat.completions.ChatCompletion; + + import + com.openai.models.chat.completions.ChatCompletionCreateParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() + .addDeveloperMessage("string") + .model(ChatModel.GPT_5_4) + .build(); + ChatCompletion chatCompletion = client.chat().completions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + chat_completion = openai.chat.completions.create(messages: + [{content: "string", role: :developer}], model: :"gpt-5.4") + + + puts(chat_completion) + response: | + { + "id": "chatcmpl-abc123", + "object": "chat.completion", + "created": 1699896916, + "model": "gpt-4o-mini", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": null, + "tool_calls": [ + { + "id": "call_abc123", + "type": "function", + "function": { + "name": "get_current_weather", + "arguments": "{\n\"location\": \"Boston, MA\"\n}" + } + } + ] + }, + "logprobs": null, + "finish_reason": "tool_calls" + } + ], + "usage": { + "prompt_tokens": 82, + "completion_tokens": 17, + "total_tokens": 99, + "completion_tokens_details": { + "reasoning_tokens": 0, + "accepted_prediction_tokens": 0, + "rejected_prediction_tokens": 0 + } + } + } + - title: Logprobs + request: + curl: | + curl https://api.openai.com/v1/chat/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "VAR_chat_model_id", + "messages": [ + { + "role": "user", + "content": "Hello!" + } + ], + "logprobs": true, + "top_logprobs": 2 + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for completion in client.chat.completions.create( + messages=[{ + "content": "string", + "role": "developer", + }], + model="gpt-5.4", + ): + print(completion) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const completion = await openai.chat.completions.create({ + messages: [{ role: "user", content: "Hello!" }], + model: "VAR_chat_model_id", + logprobs: true, + top_logprobs: 2, + }); + + console.log(completion.choices[0]); + } + + main(); + csharp: > + using System; + + using System.Collections.Generic; + + + using OpenAI.Chat; + + + ChatClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + List messages = + + [ + new UserChatMessage("Hello!") + ]; + + + ChatCompletionOptions options = new() + + { + IncludeLogProbabilities = true, + TopLogProbabilityCount = 2 + }; + + + ChatCompletion completion = client.CompleteChat(messages, + options); + + + Console.WriteLine(completion.Content[0].Text); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const chatCompletion = await client.chat.completions.create({ + messages: [{ content: 'string', role: 'developer' }], + model: 'gpt-5.4', + }); + + console.log(chatCompletion); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatCompletion, err := client.Chat.Completions.New(context.TODO(), openai.ChatCompletionNewParams{\n\t\tMessages: []openai.ChatCompletionMessageParamUnion{{\n\t\t\tOfDeveloper: &openai.ChatCompletionDeveloperMessageParam{\n\t\t\t\tContent: openai.ChatCompletionDeveloperMessageParamContentUnion{\n\t\t\t\t\tOfString: openai.String(\"string\"),\n\t\t\t\t},\n\t\t\t},\n\t\t}},\n\t\tModel: shared.ChatModelGPT5_4,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatCompletion)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.ChatModel; + + import com.openai.models.chat.completions.ChatCompletion; + + import + com.openai.models.chat.completions.ChatCompletionCreateParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatCompletionCreateParams params = ChatCompletionCreateParams.builder() + .addDeveloperMessage("string") + .model(ChatModel.GPT_5_4) + .build(); + ChatCompletion chatCompletion = client.chat().completions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + chat_completion = openai.chat.completions.create(messages: + [{content: "string", role: :developer}], model: :"gpt-5.4") + + + puts(chat_completion) + response: | + { + "id": "chatcmpl-123", + "object": "chat.completion", + "created": 1702685778, + "model": "gpt-4o-mini", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "Hello! How can I assist you today?" + }, + "logprobs": { + "content": [ + { + "token": "Hello", + "logprob": -0.31725305, + "bytes": [72, 101, 108, 108, 111], + "top_logprobs": [ + { + "token": "Hello", + "logprob": -0.31725305, + "bytes": [72, 101, 108, 108, 111] + }, + { + "token": "Hi", + "logprob": -1.3190403, + "bytes": [72, 105] + } + ] + }, + { + "token": "!", + "logprob": -0.02380986, + "bytes": [ + 33 + ], + "top_logprobs": [ + { + "token": "!", + "logprob": -0.02380986, + "bytes": [33] + }, + { + "token": " there", + "logprob": -3.787621, + "bytes": [32, 116, 104, 101, 114, 101] + } + ] + }, + { + "token": " How", + "logprob": -0.000054669687, + "bytes": [32, 72, 111, 119], + "top_logprobs": [ + { + "token": " How", + "logprob": -0.000054669687, + "bytes": [32, 72, 111, 119] + }, + { + "token": "<|end|>", + "logprob": -10.953937, + "bytes": null + } + ] + }, + { + "token": " can", + "logprob": -0.015801601, + "bytes": [32, 99, 97, 110], + "top_logprobs": [ + { + "token": " can", + "logprob": -0.015801601, + "bytes": [32, 99, 97, 110] + }, + { + "token": " may", + "logprob": -4.161023, + "bytes": [32, 109, 97, 121] + } + ] + }, + { + "token": " I", + "logprob": -3.7697225e-6, + "bytes": [ + 32, + 73 + ], + "top_logprobs": [ + { + "token": " I", + "logprob": -3.7697225e-6, + "bytes": [32, 73] + }, + { + "token": " assist", + "logprob": -13.596657, + "bytes": [32, 97, 115, 115, 105, 115, 116] + } + ] + }, + { + "token": " assist", + "logprob": -0.04571125, + "bytes": [32, 97, 115, 115, 105, 115, 116], + "top_logprobs": [ + { + "token": " assist", + "logprob": -0.04571125, + "bytes": [32, 97, 115, 115, 105, 115, 116] + }, + { + "token": " help", + "logprob": -3.1089056, + "bytes": [32, 104, 101, 108, 112] + } + ] + }, + { + "token": " you", + "logprob": -5.4385737e-6, + "bytes": [32, 121, 111, 117], + "top_logprobs": [ + { + "token": " you", + "logprob": -5.4385737e-6, + "bytes": [32, 121, 111, 117] + }, + { + "token": " today", + "logprob": -12.807695, + "bytes": [32, 116, 111, 100, 97, 121] + } + ] + }, + { + "token": " today", + "logprob": -0.0040071653, + "bytes": [32, 116, 111, 100, 97, 121], + "top_logprobs": [ + { + "token": " today", + "logprob": -0.0040071653, + "bytes": [32, 116, 111, 100, 97, 121] + }, + { + "token": "?", + "logprob": -5.5247097, + "bytes": [63] + } + ] + }, + { + "token": "?", + "logprob": -0.0008108172, + "bytes": [63], + "top_logprobs": [ + { + "token": "?", + "logprob": -0.0008108172, + "bytes": [63] + }, + { + "token": "?\n", + "logprob": -7.184561, + "bytes": [63, 10] + } + ] + } + ] + }, + "finish_reason": "stop" + } + ], + "usage": { + "prompt_tokens": 9, + "completion_tokens": 9, + "total_tokens": 18, + "completion_tokens_details": { + "reasoning_tokens": 0, + "accepted_prediction_tokens": 0, + "rejected_prediction_tokens": 0 + } + }, + "system_fingerprint": null + } + /chat/completions/{completion_id}: + get: + operationId: getChatCompletion + tags: + - Chat + summary: > + Get a stored chat completion. Only Chat Completions that have been + created + + with the `store` parameter set to `true` will be returned. + parameters: + - in: path + name: completion_id + required: true + schema: + type: string + description: The ID of the chat completion to retrieve. + responses: + '200': + description: A chat completion + content: + application/json: + schema: + $ref: '#/components/schemas/CreateChatCompletionResponse' + x-oaiMeta: + name: Get chat completion + group: chat + examples: + request: + curl: | + curl https://api.openai.com/v1/chat/completions/chatcmpl-abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + chat_completion = client.chat.completions.retrieve( + "completion_id", + ) + print(chat_completion.id) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const chatCompletion = await + client.chat.completions.retrieve('completion_id'); + + + console.log(chatCompletion.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatCompletion, err := client.Chat.Completions.Get(context.TODO(), \"completion_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatCompletion.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.chat.completions.ChatCompletion; + + import + com.openai.models.chat.completions.ChatCompletionRetrieveParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatCompletion chatCompletion = client.chat().completions().retrieve("completion_id"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + chat_completion = + openai.chat.completions.retrieve("completion_id") + + + puts(chat_completion) + response: | + { + "object": "chat.completion", + "id": "chatcmpl-abc123", + "model": "gpt-4o-2024-08-06", + "created": 1738960610, + "request_id": "req_ded8ab984ec4bf840f37566c1011c417", + "tool_choice": null, + "usage": { + "total_tokens": 31, + "completion_tokens": 18, + "prompt_tokens": 13 + }, + "seed": 4944116822809979520, + "top_p": 1.0, + "temperature": 1.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0, + "system_fingerprint": "fp_50cad350e4", + "input_user": null, + "service_tier": "default", + "tools": null, + "metadata": {}, + "choices": [ + { + "index": 0, + "message": { + "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", + "role": "assistant", + "tool_calls": null, + "function_call": null + }, + "finish_reason": "stop", + "logprobs": null + } + ], + "response_format": null + } + post: + operationId: updateChatCompletion + tags: + - Chat + summary: > + Modify a stored chat completion. Only Chat Completions that have been + + created with the `store` parameter set to `true` can be modified. + Currently, + + the only supported modification is to update the `metadata` field. + parameters: + - in: path + name: completion_id + required: true + schema: + type: string + description: The ID of the chat completion to update. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - metadata + properties: + metadata: + $ref: '#/components/schemas/Metadata' + responses: + '200': + description: A chat completion + content: + application/json: + schema: + $ref: '#/components/schemas/CreateChatCompletionResponse' + x-oaiMeta: + name: Update chat completion + group: chat + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/chat/completions/chat_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"metadata": {"foo": "bar"}}' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + chat_completion = client.chat.completions.update( + completion_id="completion_id", + metadata={ + "foo": "string" + }, + ) + print(chat_completion.id) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const chatCompletion = await + client.chat.completions.update('completion_id', { + metadata: { foo: 'string' }, + }); + + + console.log(chatCompletion.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatCompletion, err := client.Chat.Completions.Update(\n\t\tcontext.TODO(),\n\t\t\"completion_id\",\n\t\topenai.ChatCompletionUpdateParams{\n\t\t\tMetadata: shared.Metadata{\n\t\t\t\t\"foo\": \"string\",\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatCompletion.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.core.JsonValue; + + import com.openai.models.chat.completions.ChatCompletion; + + import + com.openai.models.chat.completions.ChatCompletionUpdateParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatCompletionUpdateParams params = ChatCompletionUpdateParams.builder() + .completionId("completion_id") + .metadata(ChatCompletionUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build()) + .build(); + ChatCompletion chatCompletion = client.chat().completions().update(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + chat_completion = openai.chat.completions.update("completion_id", + metadata: {foo: "string"}) + + + puts(chat_completion) + response: | + { + "object": "chat.completion", + "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", + "model": "gpt-4o-2024-08-06", + "created": 1738960610, + "request_id": "req_ded8ab984ec4bf840f37566c1011c417", + "tool_choice": null, + "usage": { + "total_tokens": 31, + "completion_tokens": 18, + "prompt_tokens": 13 + }, + "seed": 4944116822809979520, + "top_p": 1.0, + "temperature": 1.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0, + "system_fingerprint": "fp_50cad350e4", + "input_user": null, + "service_tier": "default", + "tools": null, + "metadata": { + "foo": "bar" + }, + "choices": [ + { + "index": 0, + "message": { + "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", + "role": "assistant", + "tool_calls": null, + "function_call": null + }, + "finish_reason": "stop", + "logprobs": null + } + ], + "response_format": null + } + delete: + operationId: deleteChatCompletion + tags: + - Chat + summary: | + Delete a stored chat completion. Only Chat Completions that have been + created with the `store` parameter set to `true` can be deleted. + parameters: + - in: path + name: completion_id + required: true + schema: + type: string + description: The ID of the chat completion to delete. + responses: + '200': + description: The chat completion was deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ChatCompletionDeleted' + x-oaiMeta: + name: Delete chat completion + group: chat + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/chat/completions/chat_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + chat_completion_deleted = client.chat.completions.delete( + "completion_id", + ) + print(chat_completion_deleted.id) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const chatCompletionDeleted = await + client.chat.completions.delete('completion_id'); + + + console.log(chatCompletionDeleted.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatCompletionDeleted, err := client.Chat.Completions.Delete(context.TODO(), \"completion_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatCompletionDeleted.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.chat.completions.ChatCompletionDeleteParams; + + import com.openai.models.chat.completions.ChatCompletionDeleted; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatCompletionDeleted chatCompletionDeleted = client.chat().completions().delete("completion_id"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + chat_completion_deleted = + openai.chat.completions.delete("completion_id") + + + puts(chat_completion_deleted) + response: | + { + "object": "chat.completion.deleted", + "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", + "deleted": true + } + /chat/completions/{completion_id}/messages: + get: + operationId: getChatCompletionMessages + tags: + - Chat + summary: | + Get the messages in a stored chat completion. Only Chat Completions that + have been created with the `store` parameter set to `true` will be + returned. + parameters: + - in: path + name: completion_id + required: true + schema: + type: string + description: The ID of the chat completion to retrieve messages from. + - name: after + in: query + description: >- + Identifier for the last message from the previous pagination + request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of messages to retrieve. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: >- + Sort order for messages by timestamp. Use `asc` for ascending order + or `desc` for descending order. Defaults to `asc`. + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + responses: + '200': + description: A list of messages + content: + application/json: + schema: + $ref: '#/components/schemas/ChatCompletionMessageList' + x-oaiMeta: + name: Get chat messages + group: chat + examples: + request: + curl: > + curl + https://api.openai.com/v1/chat/completions/chat_abc123/messages \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.chat.completions.messages.list( + completion_id="completion_id", + ) + page = page.data[0] + print(page) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const chatCompletionStoreMessage of + client.chat.completions.messages.list( + 'completion_id', + )) { + console.log(chatCompletionStoreMessage); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Chat.Completions.Messages.List(\n\t\tcontext.TODO(),\n\t\t\"completion_id\",\n\t\topenai.ChatCompletionMessageListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.chat.completions.messages.MessageListPage; + + import + com.openai.models.chat.completions.messages.MessageListParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + MessageListPage page = client.chat().completions().messages().list("completion_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.chat.completions.messages.list("completion_id") + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", + "role": "user", + "content": "write a haiku about ai", + "name": null, + "content_parts": null + } + ], + "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", + "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", + "has_more": false + } + /completions: + post: + operationId: createCompletion + tags: + - Completions + summary: > + Creates a completion for the provided prompt and parameters. + + + Returns a completion object, or a sequence of completion objects if the + request is streamed. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateCompletionRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/CreateCompletionResponse' + x-oaiMeta: + name: Create completion + group: completions + legacy: true + examples: + - title: No streaming + request: + curl: | + curl https://api.openai.com/v1/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "VAR_completion_model_id", + "prompt": "Say this is a test", + "max_tokens": 7, + "temperature": 0 + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for completion in client.completions.create( + model="gpt-3.5-turbo-instruct", + prompt="This is a test.", + ): + print(completion) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const completion = await openai.completions.create({ + model: "VAR_completion_model_id", + prompt: "Say this is a test.", + max_tokens: 7, + temperature: 0, + }); + + console.log(completion); + } + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const completion = await client.completions.create({ + model: 'gpt-3.5-turbo-instruct', + prompt: 'This is a test.', + }); + + console.log(completion); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tcompletion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{\n\t\tModel: openai.CompletionNewParamsModelGPT3_5TurboInstruct,\n\t\tPrompt: openai.CompletionNewParamsPromptUnion{\n\t\t\tOfString: openai.String(\"This is a test.\"),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", completion)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.completions.Completion; + import com.openai.models.completions.CompletionCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + CompletionCreateParams params = CompletionCreateParams.builder() + .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT) + .prompt("This is a test.") + .build(); + Completion completion = client.completions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + completion = openai.completions.create(model: + :"gpt-3.5-turbo-instruct", prompt: "This is a test.") + + + puts(completion) + response: | + { + "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", + "object": "text_completion", + "created": 1589478378, + "model": "VAR_completion_model_id", + "system_fingerprint": "fp_44709d6fcb", + "choices": [ + { + "text": "\n\nThis is indeed a test", + "index": 0, + "logprobs": null, + "finish_reason": "length" + } + ], + "usage": { + "prompt_tokens": 5, + "completion_tokens": 7, + "total_tokens": 12 + } + } + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/completions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "VAR_completion_model_id", + "prompt": "Say this is a test", + "max_tokens": 7, + "temperature": 0, + "stream": true + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for completion in client.completions.create( + model="gpt-3.5-turbo-instruct", + prompt="This is a test.", + ): + print(completion) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const stream = await openai.completions.create({ + model: "VAR_completion_model_id", + prompt: "Say this is a test.", + stream: true, + }); + + for await (const chunk of stream) { + console.log(chunk.choices[0].text) + } + } + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const completion = await client.completions.create({ + model: 'gpt-3.5-turbo-instruct', + prompt: 'This is a test.', + }); + + console.log(completion); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tcompletion, err := client.Completions.New(context.TODO(), openai.CompletionNewParams{\n\t\tModel: openai.CompletionNewParamsModelGPT3_5TurboInstruct,\n\t\tPrompt: openai.CompletionNewParamsPromptUnion{\n\t\t\tOfString: openai.String(\"This is a test.\"),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", completion)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.completions.Completion; + import com.openai.models.completions.CompletionCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + CompletionCreateParams params = CompletionCreateParams.builder() + .model(CompletionCreateParams.Model.GPT_3_5_TURBO_INSTRUCT) + .prompt("This is a test.") + .build(); + Completion completion = client.completions().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + completion = openai.completions.create(model: + :"gpt-3.5-turbo-instruct", prompt: "This is a test.") + + + puts(completion) + response: | + { + "id": "cmpl-7iA7iJjj8V2zOkCGvWF2hAkDWBQZe", + "object": "text_completion", + "created": 1690759702, + "choices": [ + { + "text": "This", + "index": 0, + "logprobs": null, + "finish_reason": null + } + ], + "model": "gpt-3.5-turbo-instruct" + "system_fingerprint": "fp_44709d6fcb", + } + /containers: + get: + summary: List Containers + description: Lists containers. + operationId: ListContainers + parameters: + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: name + in: query + description: Filter results by container name. + required: false + schema: + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ContainerListResource' + x-oaiMeta: + name: List containers + group: containers + path: get + examples: + request: + curl: | + curl https://api.openai.com/v1/containers \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const containerListResponse of + client.containers.list()) { + console.log(containerListResponse.id); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.containers.list() + page = page.data[0] + print(page.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Containers.List(context.TODO(), openai.ContainerListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.containers.ContainerListPage; + import com.openai.models.containers.ContainerListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ContainerListPage page = client.containers().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.containers.list + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", + "object": "container", + "created_at": 1747844794, + "status": "running", + "expires_after": { + "anchor": "last_active_at", + "minutes": 20 + }, + "last_active_at": 1747844794, + "memory_limit": "4g", + "name": "My Container" + } + ], + "first_id": "container_123", + "last_id": "container_123", + "has_more": false + } + post: + summary: Create Container + description: Creates a container. + operationId: CreateContainer + parameters: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CreateContainerBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ContainerResource' + x-oaiMeta: + name: Create container + group: containers + path: post + examples: + request: + curl: | + curl https://api.openai.com/v1/containers \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "My Container", + "memory_limit": "4g", + "skills": [ + { + "type": "skill_reference", + "skill_id": "skill_4db6f1a2c9e73508b41f9da06e2c7b5f" + }, + { + "type": "skill_reference", + "skill_id": "openai-spreadsheets", + "version": "latest" + } + ], + "network_policy": { + "type": "allowlist", + "allowed_domains": ["api.buildkite.com"] + } + }' + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const container = await client.containers.create({ name: 'name' + }); + + + console.log(container.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + container = client.containers.create( + name="name", + ) + print(container.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tcontainer, err := client.Containers.New(context.TODO(), openai.ContainerNewParams{\n\t\tName: \"name\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", container.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.containers.ContainerCreateParams; + import com.openai.models.containers.ContainerCreateResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ContainerCreateParams params = ContainerCreateParams.builder() + .name("name") + .build(); + ContainerCreateResponse container = client.containers().create(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + container = openai.containers.create(name: "name") + + puts(container) + response: | + { + "id": "cntr_682e30645a488191b6363a0cbefc0f0a025ec61b66250591", + "object": "container", + "created_at": 1747857508, + "status": "running", + "expires_after": { + "anchor": "last_active_at", + "minutes": 20 + }, + "last_active_at": 1747857508, + "network_policy": { + "type": "allowlist", + "allowed_domains": ["api.buildkite.com"] + }, + "memory_limit": "4g", + "name": "My Container" + } + /containers/{container_id}: + get: + summary: Retrieve Container + description: Retrieves a container. + operationId: RetrieveContainer + parameters: + - name: container_id + in: path + required: true + schema: + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ContainerResource' + x-oaiMeta: + name: Retrieve container + group: containers + path: get + examples: + request: + curl: > + curl + https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const container = await + client.containers.retrieve('container_id'); + + + console.log(container.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + container = client.containers.retrieve( + "container_id", + ) + print(container.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tcontainer, err := client.Containers.Get(context.TODO(), \"container_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", container.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.containers.ContainerRetrieveParams; + import com.openai.models.containers.ContainerRetrieveResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ContainerRetrieveResponse container = client.containers().retrieve("container_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + container = openai.containers.retrieve("container_id") + + puts(container) + response: | + { + "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", + "object": "container", + "created_at": 1747844794, + "status": "running", + "expires_after": { + "anchor": "last_active_at", + "minutes": 20 + }, + "last_active_at": 1747844794, + "memory_limit": "4g", + "name": "My Container" + } + delete: + operationId: DeleteContainer + summary: Delete Container + description: Delete a container. + parameters: + - name: container_id + in: path + description: The ID of the container to delete. + required: true + schema: + type: string + responses: + '200': + description: OK + x-oaiMeta: + name: Delete a container + group: containers + path: delete + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + await client.containers.delete('container_id'); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + client.containers.delete( + "container_id", + ) + go: "package main\n\nimport (\n\t\"context\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\terr := client.Containers.Delete(context.TODO(), \"container_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.containers.ContainerDeleteParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + client.containers().delete("container_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + result = openai.containers.delete("container_id") + + puts(result) + response: | + { + "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", + "object": "container.deleted", + "deleted": true + } + /containers/{container_id}/files: + post: + summary: > + Create a Container File + + + You can send either a multipart/form-data request with the raw file + content, or a JSON request with a file ID. + description: | + Creates a container file. + operationId: CreateContainerFile + parameters: + - name: container_id + in: path + required: true + schema: + type: string + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateContainerFileBody' + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateContainerFileBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ContainerFileResource' + x-oaiMeta: + name: Create container file + group: containers + path: post + examples: + request: + curl: > + curl + https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F file="@example.txt" + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const file = await client.containers.files.create('container_id'); + + console.log(file.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + file = client.containers.files.create( + container_id="container_id", + ) + print(file.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfile, err := client.Containers.Files.New(\n\t\tcontext.TODO(),\n\t\t\"container_id\",\n\t\topenai.ContainerFileNewParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", file.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.containers.files.FileCreateParams; + import com.openai.models.containers.files.FileCreateResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileCreateResponse file = client.containers().files().create("container_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + file = openai.containers.files.create("container_id") + + puts(file) + response: | + { + "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", + "object": "container.file", + "created_at": 1747848842, + "bytes": 880, + "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", + "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", + "source": "user" + } + get: + summary: List Container files + description: Lists container files. + operationId: ListContainerFiles + parameters: + - name: container_id + in: path + required: true + schema: + type: string + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ContainerFileListResource' + x-oaiMeta: + name: List container files + group: containers + path: get + examples: + request: + curl: > + curl + https://api.openai.com/v1/containers/cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04/files + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const fileListResponse of + client.containers.files.list('container_id')) { + console.log(fileListResponse.id); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.containers.files.list( + container_id="container_id", + ) + page = page.data[0] + print(page.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Containers.Files.List(\n\t\tcontext.TODO(),\n\t\t\"container_id\",\n\t\topenai.ContainerFileListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.containers.files.FileListPage; + import com.openai.models.containers.files.FileListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileListPage page = client.containers().files().list("container_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.containers.files.list("container_id") + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", + "object": "container.file", + "created_at": 1747848842, + "bytes": 880, + "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", + "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", + "source": "user" + } + ], + "first_id": "cfile_682e0e8a43c88191a7978f477a09bdf5", + "has_more": false, + "last_id": "cfile_682e0e8a43c88191a7978f477a09bdf5" + } + /containers/{container_id}/files/{file_id}: + get: + summary: Retrieve Container File + description: Retrieves a container file. + operationId: RetrieveContainerFile + parameters: + - name: container_id + in: path + required: true + schema: + type: string + - name: file_id + in: path + required: true + schema: + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ContainerFileResource' + x-oaiMeta: + name: Retrieve container file + group: containers + path: get + examples: + request: + curl: > + curl + https://api.openai.com/v1/containers/container_123/files/file_456 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const file = await client.containers.files.retrieve('file_id', { + container_id: 'container_id' }); + + + console.log(file.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + file = client.containers.files.retrieve( + file_id="file_id", + container_id="container_id", + ) + print(file.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfile, err := client.Containers.Files.Get(\n\t\tcontext.TODO(),\n\t\t\"container_id\",\n\t\t\"file_id\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", file.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.containers.files.FileRetrieveParams; + import com.openai.models.containers.files.FileRetrieveResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileRetrieveParams params = FileRetrieveParams.builder() + .containerId("container_id") + .fileId("file_id") + .build(); + FileRetrieveResponse file = client.containers().files().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + file = openai.containers.files.retrieve("file_id", container_id: + "container_id") + + + puts(file) + response: | + { + "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", + "object": "container.file", + "created_at": 1747848842, + "bytes": 880, + "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", + "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", + "source": "user" + } + delete: + operationId: DeleteContainerFile + summary: Delete Container File + description: Delete a container file. + parameters: + - name: container_id + in: path + required: true + schema: + type: string + - name: file_id + in: path + required: true + schema: + type: string + responses: + '200': + description: OK + x-oaiMeta: + name: Delete a container file + group: containers + path: delete + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/containers/cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863/files/cfile_682e0e8a43c88191a7978f477a09bdf5 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + await client.containers.files.delete('file_id', { container_id: + 'container_id' }); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + client.containers.files.delete( + file_id="file_id", + container_id="container_id", + ) + go: "package main\n\nimport (\n\t\"context\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\terr := client.Containers.Files.Delete(\n\t\tcontext.TODO(),\n\t\t\"container_id\",\n\t\t\"file_id\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.containers.files.FileDeleteParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileDeleteParams params = FileDeleteParams.builder() + .containerId("container_id") + .fileId("file_id") + .build(); + client.containers().files().delete(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + result = openai.containers.files.delete("file_id", container_id: + "container_id") + + + puts(result) + response: | + { + "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", + "object": "container.file.deleted", + "deleted": true + } + /containers/{container_id}/files/{file_id}/content: + get: + summary: Retrieve Container File Content + description: Retrieves a container file content. + operationId: RetrieveContainerFileContent + parameters: + - name: container_id + in: path + required: true + schema: + type: string + - name: file_id + in: path + required: true + schema: + type: string + responses: + '200': + description: Success + x-oaiMeta: + name: Retrieve container file content + group: containers + path: get + examples: + request: + curl: > + curl + https://api.openai.com/v1/containers/container_123/files/cfile_456/content + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const content = await + client.containers.files.content.retrieve('file_id', { + container_id: 'container_id', + }); + + + console.log(content); + + + const data = await content.blob(); + + console.log(data); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + content = client.containers.files.content.retrieve( + file_id="file_id", + container_id="container_id", + ) + print(content) + data = content.read() + print(data) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tcontent, err := client.Containers.Files.Content.Get(\n\t\tcontext.TODO(),\n\t\t\"container_id\",\n\t\t\"file_id\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", content)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.core.http.HttpResponse; + + import + com.openai.models.containers.files.content.ContentRetrieveParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ContentRetrieveParams params = ContentRetrieveParams.builder() + .containerId("container_id") + .fileId("file_id") + .build(); + HttpResponse content = client.containers().files().content().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + content = openai.containers.files.content.retrieve("file_id", + container_id: "container_id") + + + puts(content) + response: | + + /conversations/{conversation_id}/items: + post: + operationId: createConversationItems + tags: + - Conversations + summary: Create items in a conversation with the given ID. + parameters: + - in: path + name: conversation_id + required: true + schema: + type: string + example: conv_123 + description: The ID of the conversation to add the item to. + - name: include + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/IncludeEnum' + description: > + Additional fields to include in the response. See the `include` + + parameter for [listing Conversation items + above](/docs/api-reference/conversations/list-items#conversations_list_items-include) + for more information. + requestBody: + required: true + content: + application/json: + schema: + properties: + items: + type: array + description: > + The items to add to the conversation. You may add up to 20 + items at a time. + items: + $ref: '#/components/schemas/InputItem' + maxItems: 20 + required: + - items + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationItemList' + x-oaiMeta: + name: Create items + group: conversations + path: create-item + examples: + request: + curl: | + curl https://api.openai.com/v1/conversations/conv_123/items \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "items": [ + { + "type": "message", + "role": "user", + "content": [ + {"type": "input_text", "text": "Hello!"} + ] + }, + { + "type": "message", + "role": "user", + "content": [ + {"type": "input_text", "text": "How are you?"} + ] + } + ] + }' + javascript: | + import OpenAI from "openai"; + const client = new OpenAI(); + + const items = await client.conversations.items.create( + "conv_123", + { + items: [ + { + type: "message", + role: "user", + content: [{ type: "input_text", text: "Hello!" }], + }, + { + type: "message", + role: "user", + content: [{ type: "input_text", text: "How are you?" }], + }, + ], + } + ); + console.log(items.data); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + conversation_item_list = client.conversations.items.create( + conversation_id="conv_123", + items=[{ + "content": "string", + "role": "user", + "type": "message", + }], + ) + print(conversation_item_list.first_id) + csharp: | + using System; + using System.Collections.Generic; + using OpenAI.Conversations; + + OpenAIConversationClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + ConversationItemList created = client.ConversationItems.Create( + conversationId: "conv_123", + new CreateConversationItemsOptions + { + Items = new List + { + new ConversationMessage + { + Role = "user", + Content = + { + new ConversationInputText { Text = "Hello!" } + } + }, + new ConversationMessage + { + Role = "user", + Content = + { + new ConversationInputText { Text = "How are you?" } + } + } + } + } + ); + Console.WriteLine(created.Data.Count); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const conversationItemList = await + client.conversations.items.create('conv_123', { + items: [ + { + content: 'string', + role: 'user', + type: 'message', + }, + ], + }); + + + console.log(conversationItemList.first_id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/conversations\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tconversationItemList, err := client.Conversations.Items.New(\n\t\tcontext.TODO(),\n\t\t\"conv_123\",\n\t\tconversations.ItemNewParams{\n\t\t\tItems: []responses.ResponseInputItemUnionParam{{\n\t\t\t\tOfMessage: &responses.EasyInputMessageParam{\n\t\t\t\t\tContent: responses.EasyInputMessageContentUnionParam{\n\t\t\t\t\t\tOfString: openai.String(\"string\"),\n\t\t\t\t\t},\n\t\t\t\t\tRole: responses.EasyInputMessageRoleUser,\n\t\t\t\t\tType: responses.EasyInputMessageTypeMessage,\n\t\t\t\t},\n\t\t\t}},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", conversationItemList.FirstID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.conversations.items.ConversationItemList; + import com.openai.models.conversations.items.ItemCreateParams; + import com.openai.models.responses.EasyInputMessage; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ItemCreateParams params = ItemCreateParams.builder() + .conversationId("conv_123") + .addItem(EasyInputMessage.builder() + .content("string") + .role(EasyInputMessage.Role.USER) + .type(EasyInputMessage.Type.MESSAGE) + .build()) + .build(); + ConversationItemList conversationItemList = client.conversations().items().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + conversation_item_list = + openai.conversations.items.create("conv_123", items: [{content: + "string", role: :user, type: :message}]) + + + puts(conversation_item_list) + response: | + { + "object": "list", + "data": [ + { + "type": "message", + "id": "msg_abc", + "status": "completed", + "role": "user", + "content": [ + {"type": "input_text", "text": "Hello!"} + ] + }, + { + "type": "message", + "id": "msg_def", + "status": "completed", + "role": "user", + "content": [ + {"type": "input_text", "text": "How are you?"} + ] + } + ], + "first_id": "msg_abc", + "last_id": "msg_def", + "has_more": false + } + get: + operationId: listConversationItems + tags: + - Conversations + summary: List all items for a conversation with the given ID. + parameters: + - in: path + name: conversation_id + required: true + schema: + type: string + example: conv_123 + description: The ID of the conversation to list items for. + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between + + 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - in: query + name: order + schema: + type: string + enum: + - asc + - desc + description: | + The order to return the input items in. Default is `desc`. + - `asc`: Return the input items in ascending order. + - `desc`: Return the input items in descending order. + - in: query + name: after + schema: + type: string + description: | + An item ID to list items after, used in pagination. + - name: include + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/IncludeEnum' + description: >- + 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). + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationItemList' + x-oaiMeta: + name: List items + group: conversations + path: list-items + examples: + request: + curl: > + curl + "https://api.openai.com/v1/conversations/conv_123/items?limit=10" + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: > + import OpenAI from "openai"; + + const client = new OpenAI(); + + + const items = await client.conversations.items.list("conv_123", { + limit: 10 }); + + console.log(items.data); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.conversations.items.list( + conversation_id="conv_123", + ) + page = page.data[0] + print(page) + csharp: | + using System; + using OpenAI.Conversations; + + OpenAIConversationClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + ConversationItemList items = client.ConversationItems.List( + conversationId: "conv_123", + new ListConversationItemsOptions { Limit = 10 } + ); + Console.WriteLine(items.Data.Count); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const conversationItem of + client.conversations.items.list('conv_123')) { + console.log(conversationItem); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/conversations\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Conversations.Items.List(\n\t\tcontext.TODO(),\n\t\t\"conv_123\",\n\t\tconversations.ItemListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.conversations.items.ItemListPage; + import com.openai.models.conversations.items.ItemListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ItemListPage page = client.conversations().items().list("conv_123"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.conversations.items.list("conv_123") + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "type": "message", + "id": "msg_abc", + "status": "completed", + "role": "user", + "content": [ + {"type": "input_text", "text": "Hello!"} + ] + } + ], + "first_id": "msg_abc", + "last_id": "msg_abc", + "has_more": false + } + /conversations/{conversation_id}/items/{item_id}: + get: + operationId: getConversationItem + tags: + - Conversations + summary: Get a single item from a conversation with the given IDs. + parameters: + - in: path + name: conversation_id + required: true + schema: + type: string + example: conv_123 + description: The ID of the conversation that contains the item. + - in: path + name: item_id + required: true + schema: + type: string + example: msg_abc + description: The ID of the item to retrieve. + - name: include + in: query + required: false + schema: + type: array + items: + $ref: '#/components/schemas/IncludeEnum' + description: > + Additional fields to include in the response. See the `include` + + parameter for [listing Conversation items + above](/docs/api-reference/conversations/list-items#conversations_list_items-include) + for more information. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationItem' + x-oaiMeta: + name: Retrieve an item + group: conversations + path: get-item + examples: + request: + curl: > + curl + https://api.openai.com/v1/conversations/conv_123/items/msg_abc \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: | + import OpenAI from "openai"; + const client = new OpenAI(); + + const item = await client.conversations.items.retrieve( + "conv_123", + "msg_abc" + ); + console.log(item); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + conversation_item = client.conversations.items.retrieve( + item_id="msg_abc", + conversation_id="conv_123", + ) + print(conversation_item) + csharp: | + using System; + using OpenAI.Conversations; + + OpenAIConversationClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + ConversationItem item = client.ConversationItems.Get( + conversationId: "conv_123", + itemId: "msg_abc" + ); + Console.WriteLine(item.Id); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const conversationItem = await + client.conversations.items.retrieve('msg_abc', { + conversation_id: 'conv_123', + }); + + + console.log(conversationItem); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/conversations\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tconversationItem, err := client.Conversations.Items.Get(\n\t\tcontext.TODO(),\n\t\t\"conv_123\",\n\t\t\"msg_abc\",\n\t\tconversations.ItemGetParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", conversationItem)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.conversations.items.ConversationItem; + import com.openai.models.conversations.items.ItemRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ItemRetrieveParams params = ItemRetrieveParams.builder() + .conversationId("conv_123") + .itemId("msg_abc") + .build(); + ConversationItem conversationItem = client.conversations().items().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + conversation_item = openai.conversations.items.retrieve("msg_abc", + conversation_id: "conv_123") + + + puts(conversation_item) + response: | + { + "type": "message", + "id": "msg_abc", + "status": "completed", + "role": "user", + "content": [ + {"type": "input_text", "text": "Hello!"} + ] + } + delete: + operationId: deleteConversationItem + tags: + - Conversations + summary: Delete an item from a conversation with the given IDs. + parameters: + - in: path + name: conversation_id + required: true + schema: + type: string + example: conv_123 + description: The ID of the conversation that contains the item. + - in: path + name: item_id + required: true + schema: + type: string + example: msg_abc + description: The ID of the item to delete. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationResource' + x-oaiMeta: + name: Delete an item + group: conversations + path: delete-item + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/conversations/conv_123/items/msg_abc \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: | + import OpenAI from "openai"; + const client = new OpenAI(); + + const conversation = await client.conversations.items.delete( + "conv_123", + "msg_abc" + ); + console.log(conversation); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + conversation = client.conversations.items.delete( + item_id="msg_abc", + conversation_id="conv_123", + ) + print(conversation.id) + csharp: | + using System; + using OpenAI.Conversations; + + OpenAIConversationClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + Conversation conversation = client.ConversationItems.Delete( + conversationId: "conv_123", + itemId: "msg_abc" + ); + Console.WriteLine(conversation.Id); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const conversation = await + client.conversations.items.delete('msg_abc', { + conversation_id: 'conv_123', + }); + + + console.log(conversation.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tconversation, err := client.Conversations.Items.Delete(\n\t\tcontext.TODO(),\n\t\t\"conv_123\",\n\t\t\"msg_abc\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", conversation.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.conversations.Conversation; + import com.openai.models.conversations.items.ItemDeleteParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ItemDeleteParams params = ItemDeleteParams.builder() + .conversationId("conv_123") + .itemId("msg_abc") + .build(); + Conversation conversation = client.conversations().items().delete(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + conversation = openai.conversations.items.delete("msg_abc", + conversation_id: "conv_123") + + + puts(conversation) + response: | + { + "id": "conv_123", + "object": "conversation", + "created_at": 1741900000, + "metadata": {"topic": "demo"} + } + /embeddings: + post: + operationId: createEmbedding + tags: + - Embeddings + summary: Creates an embedding vector representing the input text. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateEmbeddingRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/CreateEmbeddingResponse' + x-oaiMeta: + name: Create embeddings + group: embeddings + examples: + request: + curl: | + curl https://api.openai.com/v1/embeddings \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "input": "The food was delicious and the waiter...", + "model": "text-embedding-ada-002", + "encoding_format": "float" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + create_embedding_response = client.embeddings.create( + input="The quick brown fox jumped over the lazy dog", + model="text-embedding-3-small", + ) + print(create_embedding_response.data) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const embedding = await openai.embeddings.create({ + model: "text-embedding-ada-002", + input: "The quick brown fox jumped over the lazy dog", + encoding_format: "float", + }); + + console.log(embedding); + } + + main(); + csharp: > + using System; + + + using OpenAI.Embeddings; + + + EmbeddingClient client = new( + model: "text-embedding-3-small", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + OpenAIEmbedding embedding = client.GenerateEmbedding(input: "The + quick brown fox jumped over the lazy dog"); + + ReadOnlyMemory vector = embedding.ToFloats(); + + + for (int i = 0; i < vector.Length; i++) + + { + Console.WriteLine($" [{i,4}] = {vector.Span[i]}"); + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const createEmbeddingResponse = await client.embeddings.create({ + input: 'The quick brown fox jumped over the lazy dog', + model: 'text-embedding-3-small', + }); + + console.log(createEmbeddingResponse.data); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tcreateEmbeddingResponse, err := client.Embeddings.New(context.TODO(), openai.EmbeddingNewParams{\n\t\tInput: openai.EmbeddingNewParamsInputUnion{\n\t\t\tOfString: openai.String(\"The quick brown fox jumped over the lazy dog\"),\n\t\t},\n\t\tModel: openai.EmbeddingModelTextEmbedding3Small,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", createEmbeddingResponse.Data)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.embeddings.CreateEmbeddingResponse; + import com.openai.models.embeddings.EmbeddingCreateParams; + import com.openai.models.embeddings.EmbeddingModel; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + EmbeddingCreateParams params = EmbeddingCreateParams.builder() + .input("The quick brown fox jumped over the lazy dog") + .model(EmbeddingModel.TEXT_EMBEDDING_3_SMALL) + .build(); + CreateEmbeddingResponse createEmbeddingResponse = client.embeddings().create(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + create_embedding_response = openai.embeddings.create( + input: "The quick brown fox jumped over the lazy dog", + model: :"text-embedding-3-small" + ) + + puts(create_embedding_response) + response: | + { + "object": "list", + "data": [ + { + "object": "embedding", + "embedding": [ + 0.0023064255, + -0.009327292, + .... (1536 floats total for ada-002) + -0.0028842222, + ], + "index": 0 + } + ], + "model": "text-embedding-ada-002", + "usage": { + "prompt_tokens": 8, + "total_tokens": 8 + } + } + /evals: + get: + operationId: listEvals + tags: + - Evals + summary: | + List evaluations for a project. + parameters: + - name: after + in: query + description: Identifier for the last eval from the previous pagination request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of evals to retrieve. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: >- + Sort order for evals by timestamp. Use `asc` for ascending order or + `desc` for descending order. + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + - name: order_by + in: query + description: > + Evals can be ordered by creation time or last updated time. Use + + `created_at` for creation time or `updated_at` for last updated + time. + required: false + schema: + type: string + enum: + - created_at + - updated_at + default: created_at + responses: + '200': + description: A list of evals + content: + application/json: + schema: + $ref: '#/components/schemas/EvalList' + x-oaiMeta: + name: List evals + group: evals + path: list + examples: + request: + curl: | + curl https://api.openai.com/v1/evals?limit=1 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.evals.list() + page = page.data[0] + print(page.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const evals = await openai.evals.list({ limit: 1 }); + console.log(evals); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + // Automatically fetches more pages as needed. + for await (const evalListResponse of client.evals.list()) { + console.log(evalListResponse.id); + } + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.evals.EvalListPage; + import com.openai.models.evals.EvalListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + EvalListPage page = client.evals().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.evals.list + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "eval_67abd54d9b0081909a86353f6fb9317a", + "object": "eval", + "data_source_config": { + "type": "stored_completions", + "metadata": { + "usecase": "push_notifications_summarizer" + }, + "schema": { + "type": "object", + "properties": { + "item": { + "type": "object" + }, + "sample": { + "type": "object" + } + }, + "required": [ + "item", + "sample" + ] + } + }, + "testing_criteria": [ + { + "name": "Push Notification Summary Grader", + "id": "Push Notification Summary Grader-9b876f24-4762-4be9-aff4-db7a9b31c673", + "type": "label_model", + "model": "o3-mini", + "input": [ + { + "type": "message", + "role": "developer", + "content": { + "type": "input_text", + "text": "\nLabel the following push notification summary as either correct or incorrect.\nThe push notification and the summary will be provided below.\nA good push notificiation summary is concise and snappy.\nIf it is good, then label it as correct, if not, then incorrect.\n" + } + }, + { + "type": "message", + "role": "user", + "content": { + "type": "input_text", + "text": "\nPush notifications: {{item.input}}\nSummary: {{sample.output_text}}\n" + } + } + ], + "passing_labels": [ + "correct" + ], + "labels": [ + "correct", + "incorrect" + ], + "sampling_params": null + } + ], + "name": "Push Notification Summary Grader", + "created_at": 1739314509, + "metadata": { + "description": "A stored completions eval for push notification summaries" + } + } + ], + "first_id": "eval_67abd54d9b0081909a86353f6fb9317a", + "last_id": "eval_67aa884cf6688190b58f657d4441c8b7", + "has_more": true + } + post: + operationId: createEval + tags: + - Evals + summary: > + Create the structure of an evaluation that can be used to test a model's + performance. + + An evaluation is a set of testing criteria and the config for a data + source, which dictates the schema of the data used in the evaluation. + After creating an evaluation, you can run it on different models and + model parameters. We support several types of graders and datasources. + + For more information, see the [Evals guide](/docs/guides/evals). + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateEvalRequest' + responses: + '201': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Eval' + x-oaiMeta: + name: Create eval + group: evals + path: post + examples: + request: + curl: | + curl https://api.openai.com/v1/evals \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Sentiment", + "data_source_config": { + "type": "stored_completions", + "metadata": { + "usecase": "chatbot" + } + }, + "testing_criteria": [ + { + "type": "label_model", + "model": "o3-mini", + "input": [ + { + "role": "developer", + "content": "Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'" + }, + { + "role": "user", + "content": "Statement: {{item.input}}" + } + ], + "passing_labels": [ + "positive" + ], + "labels": [ + "positive", + "neutral", + "negative" + ], + "name": "Example label grader" + } + ] + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + eval = client.evals.create( + data_source_config={ + "item_schema": { + "foo": "bar" + }, + "type": "custom", + }, + testing_criteria=[{ + "input": [{ + "content": "content", + "role": "role", + }], + "labels": ["string"], + "model": "model", + "name": "name", + "passing_labels": ["string"], + "type": "label_model", + }], + ) + print(eval.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const evalObj = await openai.evals.create({ + name: "Sentiment", + data_source_config: { + type: "stored_completions", + metadata: { usecase: "chatbot" } + }, + testing_criteria: [ + { + type: "label_model", + model: "o3-mini", + input: [ + { role: "developer", content: "Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'" }, + { role: "user", content: "Statement: {{item.input}}" } + ], + passing_labels: ["positive"], + labels: ["positive", "neutral", "negative"], + name: "Example label grader" + } + ] + }); + console.log(evalObj); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const _eval = await client.evals.create({ + data_source_config: { + item_schema: { foo: 'bar' }, + type: 'custom', + }, + testing_criteria: [ + { + input: [{ content: 'content', role: 'role' }], + labels: ['string'], + model: 'model', + name: 'name', + passing_labels: ['string'], + type: 'label_model', + }, + ], + }); + + console.log(_eval.id); + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.core.JsonValue; + import com.openai.models.evals.EvalCreateParams; + import com.openai.models.evals.EvalCreateResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + EvalCreateParams params = EvalCreateParams.builder() + .customDataSourceConfig(EvalCreateParams.DataSourceConfig.Custom.ItemSchema.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build()) + .addTestingCriterion(EvalCreateParams.TestingCriterion.LabelModel.builder() + .addInput(EvalCreateParams.TestingCriterion.LabelModel.Input.SimpleInputMessage.builder() + .content("content") + .role("role") + .build()) + .addLabel("string") + .model("model") + .name("name") + .addPassingLabel("string") + .build()) + .build(); + EvalCreateResponse eval = client.evals().create(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + eval_ = openai.evals.create( + data_source_config: {item_schema: {foo: "bar"}, type: :custom}, + testing_criteria: [ + { + input: [{content: "content", role: "role"}], + labels: ["string"], + model: "model", + name: "name", + passing_labels: ["string"], + type: :label_model + } + ] + ) + + puts(eval_) + response: | + { + "object": "eval", + "id": "eval_67b7fa9a81a88190ab4aa417e397ea21", + "data_source_config": { + "type": "stored_completions", + "metadata": { + "usecase": "chatbot" + }, + "schema": { + "type": "object", + "properties": { + "item": { + "type": "object" + }, + "sample": { + "type": "object" + } + }, + "required": [ + "item", + "sample" + ] + }, + "testing_criteria": [ + { + "name": "Example label grader", + "type": "label_model", + "model": "o3-mini", + "input": [ + { + "type": "message", + "role": "developer", + "content": { + "type": "input_text", + "text": "Classify the sentiment of the following statement as one of positive, neutral, or negative" + } + }, + { + "type": "message", + "role": "user", + "content": { + "type": "input_text", + "text": "Statement: {{item.input}}" + } + } + ], + "passing_labels": [ + "positive" + ], + "labels": [ + "positive", + "neutral", + "negative" + ] + } + ], + "name": "Sentiment", + "created_at": 1740110490, + "metadata": { + "description": "An eval for sentiment analysis" + } + } + /evals/{eval_id}: + get: + operationId: getEval + tags: + - Evals + summary: | + Get an evaluation by ID. + parameters: + - name: eval_id + in: path + required: true + schema: + type: string + description: The ID of the evaluation to retrieve. + responses: + '200': + description: The evaluation + content: + application/json: + schema: + $ref: '#/components/schemas/Eval' + x-oaiMeta: + name: Get an eval + group: evals + path: get + examples: + request: + curl: > + curl + https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + eval = client.evals.retrieve( + "eval_id", + ) + print(eval.id) + javascript: > + import OpenAI from "openai"; + + + const openai = new OpenAI(); + + + const evalObj = await + openai.evals.retrieve("eval_67abd54d9b0081909a86353f6fb9317a"); + + console.log(evalObj); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const _eval = await client.evals.retrieve('eval_id'); + + console.log(_eval.id); + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.evals.EvalRetrieveParams; + import com.openai.models.evals.EvalRetrieveResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + EvalRetrieveResponse eval = client.evals().retrieve("eval_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + eval_ = openai.evals.retrieve("eval_id") + + puts(eval_) + response: | + { + "object": "eval", + "id": "eval_67abd54d9b0081909a86353f6fb9317a", + "data_source_config": { + "type": "custom", + "schema": { + "type": "object", + "properties": { + "item": { + "type": "object", + "properties": { + "input": { + "type": "string" + }, + "ground_truth": { + "type": "string" + } + }, + "required": [ + "input", + "ground_truth" + ] + } + }, + "required": [ + "item" + ] + } + }, + "testing_criteria": [ + { + "name": "String check", + "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2", + "type": "string_check", + "input": "{{item.input}}", + "reference": "{{item.ground_truth}}", + "operation": "eq" + } + ], + "name": "External Data Eval", + "created_at": 1739314509, + "metadata": {}, + } + post: + operationId: updateEval + tags: + - Evals + summary: | + Update certain properties of an evaluation. + parameters: + - name: eval_id + in: path + required: true + schema: + type: string + description: The ID of the evaluation to update. + requestBody: + description: Request to update an evaluation + required: true + content: + application/json: + schema: + type: object + properties: + name: + type: string + description: Rename the evaluation. + metadata: + $ref: '#/components/schemas/Metadata' + responses: + '200': + description: The updated evaluation + content: + application/json: + schema: + $ref: '#/components/schemas/Eval' + x-oaiMeta: + name: Update an eval + group: evals + path: update + examples: + request: + curl: > + curl + https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"name": "Updated Eval", "metadata": {"description": "Updated description"}}' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + eval = client.evals.update( + eval_id="eval_id", + ) + print(eval.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const updatedEval = await openai.evals.update( + "eval_67abd54d9b0081909a86353f6fb9317a", + { + name: "Updated Eval", + metadata: { description: "Updated description" } + } + ); + console.log(updatedEval); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const _eval = await client.evals.update('eval_id'); + + console.log(_eval.id); + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.evals.EvalUpdateParams; + import com.openai.models.evals.EvalUpdateResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + EvalUpdateResponse eval = client.evals().update("eval_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + eval_ = openai.evals.update("eval_id") + + puts(eval_) + response: | + { + "object": "eval", + "id": "eval_67abd54d9b0081909a86353f6fb9317a", + "data_source_config": { + "type": "custom", + "schema": { + "type": "object", + "properties": { + "item": { + "type": "object", + "properties": { + "input": { + "type": "string" + }, + "ground_truth": { + "type": "string" + } + }, + "required": [ + "input", + "ground_truth" + ] + } + }, + "required": [ + "item" + ] + } + }, + "testing_criteria": [ + { + "name": "String check", + "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2", + "type": "string_check", + "input": "{{item.input}}", + "reference": "{{item.ground_truth}}", + "operation": "eq" + } + ], + "name": "Updated Eval", + "created_at": 1739314509, + "metadata": {"description": "Updated description"}, + } + delete: + operationId: deleteEval + tags: + - Evals + summary: | + Delete an evaluation. + parameters: + - name: eval_id + in: path + required: true + schema: + type: string + description: The ID of the evaluation to delete. + responses: + '200': + description: Successfully deleted the evaluation. + content: + application/json: + schema: + type: object + properties: + object: + type: string + example: eval.deleted + deleted: + type: boolean + example: true + eval_id: + type: string + example: eval_abc123 + required: + - object + - deleted + - eval_id + '404': + description: Evaluation not found. + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + x-oaiMeta: + name: Delete an eval + group: evals + examples: + request: + curl: | + curl https://api.openai.com/v1/evals/eval_abc123 \ + -X DELETE \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + eval = client.evals.delete( + "eval_id", + ) + print(eval.eval_id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const deleted = await openai.evals.delete("eval_abc123"); + console.log(deleted); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const _eval = await client.evals.delete('eval_id'); + + console.log(_eval.eval_id); + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.evals.EvalDeleteParams; + import com.openai.models.evals.EvalDeleteResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + EvalDeleteResponse eval = client.evals().delete("eval_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + eval_ = openai.evals.delete("eval_id") + + puts(eval_) + response: | + { + "object": "eval.deleted", + "deleted": true, + "eval_id": "eval_abc123" + } + /evals/{eval_id}/runs: + get: + operationId: getEvalRuns + tags: + - Evals + summary: | + Get a list of runs for an evaluation. + parameters: + - name: eval_id + in: path + required: true + schema: + type: string + description: The ID of the evaluation to retrieve runs for. + - name: after + in: query + description: Identifier for the last run from the previous pagination request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of runs to retrieve. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: >- + Sort order for runs by timestamp. Use `asc` for ascending order or + `desc` for descending order. Defaults to `asc`. + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + - name: status + in: query + description: >- + Filter runs by status. One of `queued` | `in_progress` | `failed` | + `completed` | `canceled`. + required: false + schema: + type: string + enum: + - queued + - in_progress + - completed + - canceled + - failed + responses: + '200': + description: A list of runs for the evaluation + content: + application/json: + schema: + $ref: '#/components/schemas/EvalRunList' + x-oaiMeta: + name: Get eval runs + group: evals + path: get-runs + examples: + request: + curl: > + curl + https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.evals.runs.list( + eval_id="eval_id", + ) + page = page.data[0] + print(page.id) + javascript: > + import OpenAI from "openai"; + + + const openai = new OpenAI(); + + + const runs = await + openai.evals.runs.list("egroup_67abd54d9b0081909a86353f6fb9317a"); + + console.log(runs); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const runListResponse of + client.evals.runs.list('eval_id')) { + console.log(runListResponse.id); + } + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.evals.runs.RunListPage; + import com.openai.models.evals.runs.RunListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunListPage page = client.evals().runs().list("eval_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.evals.runs.list("eval_id") + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "object": "eval.run", + "id": "evalrun_67e0c7d31560819090d60c0780591042", + "eval_id": "eval_67e0c726d560819083f19a957c4c640b", + "report_url": "https://platform.openai.com/evaluations/eval_67e0c726d560819083f19a957c4c640b", + "status": "completed", + "model": "o3-mini", + "name": "bulk_with_negative_examples_o3-mini", + "created_at": 1742784467, + "result_counts": { + "total": 1, + "errored": 0, + "failed": 0, + "passed": 1 + }, + "per_model_usage": [ + { + "model_name": "o3-mini", + "invocation_count": 1, + "prompt_tokens": 563, + "completion_tokens": 874, + "total_tokens": 1437, + "cached_tokens": 0 + } + ], + "per_testing_criteria_results": [ + { + "testing_criteria": "Push Notification Summary Grader-1808cd0b-eeec-4e0b-a519-337e79f4f5d1", + "passed": 1, + "failed": 0 + } + ], + "data_source": { + "type": "completions", + "source": { + "type": "file_content", + "content": [ + { + "item": { + "notifications": "\n- New message from Sarah: \"Can you call me later?\"\n- Your package has been delivered!\n- Flash sale: 20% off electronics for the next 2 hours!\n" + } + } + ] + }, + "input_messages": { + "type": "template", + "template": [ + { + "type": "message", + "role": "developer", + "content": { + "type": "input_text", + "text": "\n\n\n\nYou are a helpful assistant that takes in an array of push notifications and returns a collapsed summary of them.\nThe push notification will be provided as follows:\n\n...notificationlist...\n\n\nYou should return just the summary and nothing else.\n\n\nYou should return a summary that is concise and snappy.\n\n\nHere is an example of a good summary:\n\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\n\n\nTraffic alert, package expected by 5pm, suggestion for new friend (Emily).\n\n\n\nHere is an example of a bad summary:\n\n- Traffic alert: Accident reported on Main Street.- Package out for delivery: Expected by 5 PM.- New friend suggestion: Connect with Emma.\n\n\nTraffic alert reported on main street. You have a package that will arrive by 5pm, Emily is a new friend suggested for you.\n\n" + } + }, + { + "type": "message", + "role": "user", + "content": { + "type": "input_text", + "text": "{{item.notifications}}" + } + } + ] + }, + "model": "o3-mini", + "sampling_params": null + }, + "error": null, + "metadata": {} + } + ], + "first_id": "evalrun_67e0c7d31560819090d60c0780591042", + "last_id": "evalrun_67e0c7d31560819090d60c0780591042", + "has_more": true + } + post: + operationId: createEvalRun + tags: + - Evals + summary: > + Kicks off a new run for a given evaluation, specifying the data source, + and what model configuration to use to test. The datasource will be + validated against the schema specified in the config of the evaluation. + parameters: + - in: path + name: eval_id + required: true + schema: + type: string + description: The ID of the evaluation to create a run for. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateEvalRunRequest' + responses: + '201': + description: Successfully created a run for the evaluation + content: + application/json: + schema: + $ref: '#/components/schemas/EvalRun' + '400': + description: Bad request (for example, missing eval object) + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + x-oaiMeta: + name: Create eval run + group: evals + examples: + request: + curl: > + curl + https://api.openai.com/v1/evals/eval_67e579652b548190aaa83ada4b125f47/runs + \ + -X POST \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"name":"gpt-4o-mini","data_source":{"type":"completions","input_messages":{"type":"template","template":[{"role":"developer","content":"Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n"} , {"role":"user","content":"{{item.input}}"}]} ,"sampling_params":{"temperature":1,"max_completions_tokens":2048,"top_p":1,"seed":42},"model":"gpt-4o-mini","source":{"type":"file_content","content":[{"item":{"input":"Tech Company Launches Advanced Artificial Intelligence Platform","ground_truth":"Technology"}}]}}' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + run = client.evals.runs.create( + eval_id="eval_id", + data_source={ + "source": { + "content": [{ + "item": { + "foo": "bar" + } + }], + "type": "file_content", + }, + "type": "jsonl", + }, + ) + print(run.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const run = await openai.evals.runs.create( + "eval_67e579652b548190aaa83ada4b125f47", + { + name: "gpt-4o-mini", + data_source: { + type: "completions", + input_messages: { + type: "template", + template: [ + { + role: "developer", + content: "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" + }, + { + role: "user", + content: "{{item.input}}" + } + ] + }, + sampling_params: { + temperature: 1, + max_completions_tokens: 2048, + top_p: 1, + seed: 42 + }, + model: "gpt-4o-mini", + source: { + type: "file_content", + content: [ + { + item: { + input: "Tech Company Launches Advanced Artificial Intelligence Platform", + ground_truth: "Technology" + } + } + ] + } + } + } + ); + console.log(run); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const run = await client.evals.runs.create('eval_id', { + data_source: { + source: { content: [{ item: { foo: 'bar' } }], type: 'file_content' }, + type: 'jsonl', + }, + }); + + console.log(run.id); + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.core.JsonValue; + import com.openai.models.evals.runs.CreateEvalJsonlRunDataSource; + import com.openai.models.evals.runs.RunCreateParams; + import com.openai.models.evals.runs.RunCreateResponse; + import java.util.List; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunCreateParams params = RunCreateParams.builder() + .evalId("eval_id") + .dataSource(CreateEvalJsonlRunDataSource.builder() + .fileContentSource(List.of(CreateEvalJsonlRunDataSource.Source.FileContent.Content.builder() + .item(CreateEvalJsonlRunDataSource.Source.FileContent.Content.Item.builder() + .putAdditionalProperty("foo", JsonValue.from("bar")) + .build()) + .build())) + .build()) + .build(); + RunCreateResponse run = client.evals().runs().create(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + run = openai.evals.runs.create( + "eval_id", + data_source: {source: {content: [{item: {foo: "bar"}}], type: :file_content}, type: :jsonl} + ) + + puts(run) + response: | + { + "object": "eval.run", + "id": "evalrun_67e57965b480819094274e3a32235e4c", + "eval_id": "eval_67e579652b548190aaa83ada4b125f47", + "report_url": "https://platform.openai.com/evaluations/eval_67e579652b548190aaa83ada4b125f47&run_id=evalrun_67e57965b480819094274e3a32235e4c", + "status": "queued", + "model": "gpt-4o-mini", + "name": "gpt-4o-mini", + "created_at": 1743092069, + "result_counts": { + "total": 0, + "errored": 0, + "failed": 0, + "passed": 0 + }, + "per_model_usage": null, + "per_testing_criteria_results": null, + "data_source": { + "type": "completions", + "source": { + "type": "file_content", + "content": [ + { + "item": { + "input": "Tech Company Launches Advanced Artificial Intelligence Platform", + "ground_truth": "Technology" + } + } + ] + }, + "input_messages": { + "type": "template", + "template": [ + { + "type": "message", + "role": "developer", + "content": { + "type": "input_text", + "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" + } + }, + { + "type": "message", + "role": "user", + "content": { + "type": "input_text", + "text": "{{item.input}}" + } + } + ] + }, + "model": "gpt-4o-mini", + "sampling_params": { + "seed": 42, + "temperature": 1.0, + "top_p": 1.0, + "max_completions_tokens": 2048 + } + }, + "error": null, + "metadata": {} + } + /evals/{eval_id}/runs/{run_id}: + get: + operationId: getEvalRun + tags: + - Evals + summary: | + Get an evaluation run by ID. + parameters: + - name: eval_id + in: path + required: true + schema: + type: string + description: The ID of the evaluation to retrieve runs for. + - name: run_id + in: path + required: true + schema: + type: string + description: The ID of the run to retrieve. + responses: + '200': + description: The evaluation run + content: + application/json: + schema: + $ref: '#/components/schemas/EvalRun' + x-oaiMeta: + name: Get an eval run + group: evals + path: get + examples: + request: + curl: > + curl + https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + run = client.evals.runs.retrieve( + run_id="run_id", + eval_id="eval_id", + ) + print(run.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const run = await openai.evals.runs.retrieve( + "evalrun_67abd54d60ec8190832b46859da808f7", + { eval_id: "eval_67abd54d9b0081909a86353f6fb9317a" } + ); + console.log(run); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.evals.runs.retrieve('run_id', { eval_id: + 'eval_id' }); + + + console.log(run.id); + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.evals.runs.RunRetrieveParams; + import com.openai.models.evals.runs.RunRetrieveResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunRetrieveParams params = RunRetrieveParams.builder() + .evalId("eval_id") + .runId("run_id") + .build(); + RunRetrieveResponse run = client.evals().runs().retrieve(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + run = openai.evals.runs.retrieve("run_id", eval_id: "eval_id") + + puts(run) + response: | + { + "object": "eval.run", + "id": "evalrun_67abd54d60ec8190832b46859da808f7", + "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", + "report_url": "https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7", + "status": "queued", + "model": "gpt-4o-mini", + "name": "gpt-4o-mini", + "created_at": 1743092069, + "result_counts": { + "total": 0, + "errored": 0, + "failed": 0, + "passed": 0 + }, + "per_model_usage": null, + "per_testing_criteria_results": null, + "data_source": { + "type": "completions", + "source": { + "type": "file_content", + "content": [ + { + "item": { + "input": "Tech Company Launches Advanced Artificial Intelligence Platform", + "ground_truth": "Technology" + } + }, + { + "item": { + "input": "Central Bank Increases Interest Rates Amid Inflation Concerns", + "ground_truth": "Markets" + } + }, + { + "item": { + "input": "International Summit Addresses Climate Change Strategies", + "ground_truth": "World" + } + }, + { + "item": { + "input": "Major Retailer Reports Record-Breaking Holiday Sales", + "ground_truth": "Business" + } + }, + { + "item": { + "input": "National Team Qualifies for World Championship Finals", + "ground_truth": "Sports" + } + }, + { + "item": { + "input": "Stock Markets Rally After Positive Economic Data Released", + "ground_truth": "Markets" + } + }, + { + "item": { + "input": "Global Manufacturer Announces Merger with Competitor", + "ground_truth": "Business" + } + }, + { + "item": { + "input": "Breakthrough in Renewable Energy Technology Unveiled", + "ground_truth": "Technology" + } + }, + { + "item": { + "input": "World Leaders Sign Historic Climate Agreement", + "ground_truth": "World" + } + }, + { + "item": { + "input": "Professional Athlete Sets New Record in Championship Event", + "ground_truth": "Sports" + } + }, + { + "item": { + "input": "Financial Institutions Adapt to New Regulatory Requirements", + "ground_truth": "Business" + } + }, + { + "item": { + "input": "Tech Conference Showcases Advances in Artificial Intelligence", + "ground_truth": "Technology" + } + }, + { + "item": { + "input": "Global Markets Respond to Oil Price Fluctuations", + "ground_truth": "Markets" + } + }, + { + "item": { + "input": "International Cooperation Strengthened Through New Treaty", + "ground_truth": "World" + } + }, + { + "item": { + "input": "Sports League Announces Revised Schedule for Upcoming Season", + "ground_truth": "Sports" + } + } + ] + }, + "input_messages": { + "type": "template", + "template": [ + { + "type": "message", + "role": "developer", + "content": { + "type": "input_text", + "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" + } + }, + { + "type": "message", + "role": "user", + "content": { + "type": "input_text", + "text": "{{item.input}}" + } + } + ] + }, + "model": "gpt-4o-mini", + "sampling_params": { + "seed": 42, + "temperature": 1.0, + "top_p": 1.0, + "max_completions_tokens": 2048 + } + }, + "error": null, + "metadata": {} + } + post: + operationId: cancelEvalRun + tags: + - Evals + summary: | + Cancel an ongoing evaluation run. + parameters: + - name: eval_id + in: path + required: true + schema: + type: string + description: The ID of the evaluation whose run you want to cancel. + - name: run_id + in: path + required: true + schema: + type: string + description: The ID of the run to cancel. + responses: + '200': + description: The canceled eval run object + content: + application/json: + schema: + $ref: '#/components/schemas/EvalRun' + x-oaiMeta: + name: Cancel eval run + group: evals + path: post + examples: + request: + curl: > + curl + https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/cancel + \ + -X POST \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.evals.runs.cancel( + run_id="run_id", + eval_id="eval_id", + ) + print(response.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const canceledRun = await openai.evals.runs.cancel( + "evalrun_67abd54d60ec8190832b46859da808f7", + { eval_id: "eval_67abd54d9b0081909a86353f6fb9317a" } + ); + console.log(canceledRun); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const response = await client.evals.runs.cancel('run_id', { + eval_id: 'eval_id' }); + + + console.log(response.id); + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.evals.runs.RunCancelParams; + import com.openai.models.evals.runs.RunCancelResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunCancelParams params = RunCancelParams.builder() + .evalId("eval_id") + .runId("run_id") + .build(); + RunCancelResponse response = client.evals().runs().cancel(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.evals.runs.cancel("run_id", eval_id: "eval_id") + + puts(response) + response: | + { + "object": "eval.run", + "id": "evalrun_67abd54d60ec8190832b46859da808f7", + "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", + "report_url": "https://platform.openai.com/evaluations/eval_67abd54d9b0081909a86353f6fb9317a?run_id=evalrun_67abd54d60ec8190832b46859da808f7", + "status": "canceled", + "model": "gpt-4o-mini", + "name": "gpt-4o-mini", + "created_at": 1743092069, + "result_counts": { + "total": 0, + "errored": 0, + "failed": 0, + "passed": 0 + }, + "per_model_usage": null, + "per_testing_criteria_results": null, + "data_source": { + "type": "completions", + "source": { + "type": "file_content", + "content": [ + { + "item": { + "input": "Tech Company Launches Advanced Artificial Intelligence Platform", + "ground_truth": "Technology" + } + }, + { + "item": { + "input": "Central Bank Increases Interest Rates Amid Inflation Concerns", + "ground_truth": "Markets" + } + }, + { + "item": { + "input": "International Summit Addresses Climate Change Strategies", + "ground_truth": "World" + } + }, + { + "item": { + "input": "Major Retailer Reports Record-Breaking Holiday Sales", + "ground_truth": "Business" + } + }, + { + "item": { + "input": "National Team Qualifies for World Championship Finals", + "ground_truth": "Sports" + } + }, + { + "item": { + "input": "Stock Markets Rally After Positive Economic Data Released", + "ground_truth": "Markets" + } + }, + { + "item": { + "input": "Global Manufacturer Announces Merger with Competitor", + "ground_truth": "Business" + } + }, + { + "item": { + "input": "Breakthrough in Renewable Energy Technology Unveiled", + "ground_truth": "Technology" + } + }, + { + "item": { + "input": "World Leaders Sign Historic Climate Agreement", + "ground_truth": "World" + } + }, + { + "item": { + "input": "Professional Athlete Sets New Record in Championship Event", + "ground_truth": "Sports" + } + }, + { + "item": { + "input": "Financial Institutions Adapt to New Regulatory Requirements", + "ground_truth": "Business" + } + }, + { + "item": { + "input": "Tech Conference Showcases Advances in Artificial Intelligence", + "ground_truth": "Technology" + } + }, + { + "item": { + "input": "Global Markets Respond to Oil Price Fluctuations", + "ground_truth": "Markets" + } + }, + { + "item": { + "input": "International Cooperation Strengthened Through New Treaty", + "ground_truth": "World" + } + }, + { + "item": { + "input": "Sports League Announces Revised Schedule for Upcoming Season", + "ground_truth": "Sports" + } + } + ] + }, + "input_messages": { + "type": "template", + "template": [ + { + "type": "message", + "role": "developer", + "content": { + "type": "input_text", + "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" + } + }, + { + "type": "message", + "role": "user", + "content": { + "type": "input_text", + "text": "{{item.input}}" + } + } + ] + }, + "model": "gpt-4o-mini", + "sampling_params": { + "seed": 42, + "temperature": 1.0, + "top_p": 1.0, + "max_completions_tokens": 2048 + } + }, + "error": null, + "metadata": {} + } + delete: + operationId: deleteEvalRun + tags: + - Evals + summary: | + Delete an eval run. + parameters: + - name: eval_id + in: path + required: true + schema: + type: string + description: The ID of the evaluation to delete the run from. + - name: run_id + in: path + required: true + schema: + type: string + description: The ID of the run to delete. + responses: + '200': + description: Successfully deleted the eval run + content: + application/json: + schema: + type: object + properties: + object: + type: string + example: eval.run.deleted + deleted: + type: boolean + example: true + run_id: + type: string + example: evalrun_677469f564d48190807532a852da3afb + '404': + description: Run not found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + x-oaiMeta: + name: Delete eval run + group: evals + path: delete + examples: + request: + curl: > + curl + https://api.openai.com/v1/evals/eval_123abc/runs/evalrun_abc456 \ + -X DELETE \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + run = client.evals.runs.delete( + run_id="run_id", + eval_id="eval_id", + ) + print(run.run_id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const deleted = await openai.evals.runs.delete( + "eval_123abc", + "evalrun_abc456" + ); + console.log(deleted); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.evals.runs.delete('run_id', { eval_id: + 'eval_id' }); + + + console.log(run.run_id); + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.evals.runs.RunDeleteParams; + import com.openai.models.evals.runs.RunDeleteResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunDeleteParams params = RunDeleteParams.builder() + .evalId("eval_id") + .runId("run_id") + .build(); + RunDeleteResponse run = client.evals().runs().delete(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + run = openai.evals.runs.delete("run_id", eval_id: "eval_id") + + puts(run) + response: | + { + "object": "eval.run.deleted", + "deleted": true, + "run_id": "evalrun_abc456" + } + /evals/{eval_id}/runs/{run_id}/output_items: + get: + operationId: getEvalRunOutputItems + tags: + - Evals + summary: | + Get a list of output items for an evaluation run. + parameters: + - name: eval_id + in: path + required: true + schema: + type: string + description: The ID of the evaluation to retrieve runs for. + - name: run_id + in: path + required: true + schema: + type: string + description: The ID of the run to retrieve output items for. + - name: after + in: query + description: >- + Identifier for the last output item from the previous pagination + request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of output items to retrieve. + required: false + schema: + type: integer + default: 20 + - name: status + in: query + description: > + Filter output items by status. Use `failed` to filter by failed + output + + items or `pass` to filter by passed output items. + required: false + schema: + type: string + enum: + - fail + - pass + - name: order + in: query + description: >- + Sort order for output items by timestamp. Use `asc` for ascending + order or `desc` for descending order. Defaults to `asc`. + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + responses: + '200': + description: A list of output items for the evaluation run + content: + application/json: + schema: + $ref: '#/components/schemas/EvalRunOutputItemList' + x-oaiMeta: + name: Get eval run output items + group: evals + path: get + examples: + request: + curl: > + curl + https://api.openai.com/v1/evals/egroup_67abd54d9b0081909a86353f6fb9317a/runs/erun_67abd54d60ec8190832b46859da808f7/output_items + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.evals.runs.output_items.list( + run_id="run_id", + eval_id="eval_id", + ) + page = page.data[0] + print(page.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const outputItems = await openai.evals.runs.outputItems.list( + "egroup_67abd54d9b0081909a86353f6fb9317a", + "erun_67abd54d60ec8190832b46859da808f7" + ); + console.log(outputItems); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const outputItemListResponse of + client.evals.runs.outputItems.list('run_id', { + eval_id: 'eval_id', + })) { + console.log(outputItemListResponse.id); + } + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.evals.runs.outputitems.OutputItemListPage; + + import + com.openai.models.evals.runs.outputitems.OutputItemListParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + OutputItemListParams params = OutputItemListParams.builder() + .evalId("eval_id") + .runId("run_id") + .build(); + OutputItemListPage page = client.evals().runs().outputItems().list(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + page = openai.evals.runs.output_items.list("run_id", eval_id: + "eval_id") + + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "object": "eval.run.output_item", + "id": "outputitem_67e5796c28e081909917bf79f6e6214d", + "created_at": 1743092076, + "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", + "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", + "status": "pass", + "datasource_item_id": 5, + "datasource_item": { + "input": "Stock Markets Rally After Positive Economic Data Released", + "ground_truth": "Markets" + }, + "results": [ + { + "name": "String check-a2486074-d803-4445-b431-ad2262e85d47", + "sample": null, + "passed": true, + "score": 1.0 + } + ], + "sample": { + "input": [ + { + "role": "developer", + "content": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n", + "tool_call_id": null, + "tool_calls": null, + "function_call": null + }, + { + "role": "user", + "content": "Stock Markets Rally After Positive Economic Data Released", + "tool_call_id": null, + "tool_calls": null, + "function_call": null + } + ], + "output": [ + { + "role": "assistant", + "content": "Markets", + "tool_call_id": null, + "tool_calls": null, + "function_call": null + } + ], + "finish_reason": "stop", + "model": "gpt-4o-mini-2024-07-18", + "usage": { + "total_tokens": 325, + "completion_tokens": 2, + "prompt_tokens": 323, + "cached_tokens": 0 + }, + "error": null, + "temperature": 1.0, + "max_completion_tokens": 2048, + "top_p": 1.0, + "seed": 42 + } + } + ], + "first_id": "outputitem_67e5796c28e081909917bf79f6e6214d", + "last_id": "outputitem_67e5796c28e081909917bf79f6e6214d", + "has_more": true + } + /evals/{eval_id}/runs/{run_id}/output_items/{output_item_id}: + get: + operationId: getEvalRunOutputItem + tags: + - Evals + summary: | + Get an evaluation run output item by ID. + parameters: + - name: eval_id + in: path + required: true + schema: + type: string + description: The ID of the evaluation to retrieve runs for. + - name: run_id + in: path + required: true + schema: + type: string + description: The ID of the run to retrieve. + - name: output_item_id + in: path + required: true + schema: + type: string + description: The ID of the output item to retrieve. + responses: + '200': + description: The evaluation run output item + content: + application/json: + schema: + $ref: '#/components/schemas/EvalRunOutputItem' + x-oaiMeta: + name: Get an output item of an eval run + group: evals + path: get + examples: + request: + curl: > + curl + https://api.openai.com/v1/evals/eval_67abd54d9b0081909a86353f6fb9317a/runs/evalrun_67abd54d60ec8190832b46859da808f7/output_items/outputitem_67abd55eb6548190bb580745d5644a33 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + output_item = client.evals.runs.output_items.retrieve( + output_item_id="output_item_id", + eval_id="eval_id", + run_id="run_id", + ) + print(output_item.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const outputItem = await openai.evals.runs.outputItems.retrieve( + "outputitem_67abd55eb6548190bb580745d5644a33", + { + eval_id: "eval_67abd54d9b0081909a86353f6fb9317a", + run_id: "evalrun_67abd54d60ec8190832b46859da808f7", + } + ); + console.log(outputItem); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const outputItem = await + client.evals.runs.outputItems.retrieve('output_item_id', { + eval_id: 'eval_id', + run_id: 'run_id', + }); + + + console.log(outputItem.id); + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.evals.runs.outputitems.OutputItemRetrieveParams; + + import + com.openai.models.evals.runs.outputitems.OutputItemRetrieveResponse; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + OutputItemRetrieveParams params = OutputItemRetrieveParams.builder() + .evalId("eval_id") + .runId("run_id") + .outputItemId("output_item_id") + .build(); + OutputItemRetrieveResponse outputItem = client.evals().runs().outputItems().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + output_item = + openai.evals.runs.output_items.retrieve("output_item_id", eval_id: + "eval_id", run_id: "run_id") + + + puts(output_item) + response: | + { + "object": "eval.run.output_item", + "id": "outputitem_67e5796c28e081909917bf79f6e6214d", + "created_at": 1743092076, + "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", + "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", + "status": "pass", + "datasource_item_id": 5, + "datasource_item": { + "input": "Stock Markets Rally After Positive Economic Data Released", + "ground_truth": "Markets" + }, + "results": [ + { + "name": "String check-a2486074-d803-4445-b431-ad2262e85d47", + "sample": null, + "passed": true, + "score": 1.0 + } + ], + "sample": { + "input": [ + { + "role": "developer", + "content": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n", + "tool_call_id": null, + "tool_calls": null, + "function_call": null + }, + { + "role": "user", + "content": "Stock Markets Rally After Positive Economic Data Released", + "tool_call_id": null, + "tool_calls": null, + "function_call": null + } + ], + "output": [ + { + "role": "assistant", + "content": "Markets", + "tool_call_id": null, + "tool_calls": null, + "function_call": null + } + ], + "finish_reason": "stop", + "model": "gpt-4o-mini-2024-07-18", + "usage": { + "total_tokens": 325, + "completion_tokens": 2, + "prompt_tokens": 323, + "cached_tokens": 0 + }, + "error": null, + "temperature": 1.0, + "max_completion_tokens": 2048, + "top_p": 1.0, + "seed": 42 + } + } + /files: + get: + operationId: listFiles + tags: + - Files + summary: Returns a list of files. + parameters: + - in: query + name: purpose + required: false + schema: + type: string + description: Only return files with the given purpose. + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 10,000, and the default is 10,000. + required: false + schema: + type: integer + default: 10000 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListFilesResponse' + x-oaiMeta: + name: List files + group: files + examples: + request: + curl: | + curl https://api.openai.com/v1/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.files.list() + page = page.data[0] + print(page) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const list = await openai.files.list(); + + for await (const file of list) { + console.log(file); + } + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + // Automatically fetches more pages as needed. + for await (const fileObject of client.files.list()) { + console.log(fileObject); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Files.List(context.TODO(), openai.FileListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.files.FileListPage; + import com.openai.models.files.FileListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileListPage page = client.files().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.files.list + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "file-abc123", + "object": "file", + "bytes": 175, + "created_at": 1613677385, + "expires_at": 1677614202, + "filename": "salesOverview.pdf", + "purpose": "assistants", + }, + { + "id": "file-abc456", + "object": "file", + "bytes": 140, + "created_at": 1613779121, + "expires_at": 1677614202, + "filename": "puppy.jsonl", + "purpose": "fine-tune", + } + ], + "first_id": "file-abc123", + "last_id": "file-abc456", + "has_more": false + } + post: + operationId: createFile + tags: + - Files + summary: > + Upload a file that can be used across various endpoints. Individual + files + + can be up to 512 MB, and each project can store up to 2.5 TB of files in + + total. There is no organization-wide storage limit. + + + - The Assistants API supports files up to 2 million tokens and of + specific + file types. See the [Assistants Tools guide](/docs/assistants/tools) for + details. + - The Fine-tuning API only supports `.jsonl` files. The input also has + certain required formats for fine-tuning + [chat](/docs/api-reference/fine-tuning/chat-input) or + [completions](/docs/api-reference/fine-tuning/completions-input) models. + - The Batch API only supports `.jsonl` files up to 200 MB in size. The + input + also has a specific required + [format](/docs/api-reference/batch/request-input). + + Please [contact us](https://help.openai.com/) if you need to increase + these + + storage limits. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateFileRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/OpenAIFile' + x-oaiMeta: + name: Upload file + group: files + examples: + request: + curl: | + curl https://api.openai.com/v1/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F purpose="fine-tune" \ + -F file="@mydata.jsonl" + -F expires_after[anchor]="created_at" + -F expires_after[seconds]=2592000 + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + file_object = client.files.create( + file=b"Example data", + purpose="assistants", + ) + print(file_object.id) + javascript: |- + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const file = await openai.files.create({ + file: fs.createReadStream("mydata.jsonl"), + purpose: "fine-tune", + expires_after: { + anchor: "created_at", + seconds: 2592000 + } + }); + + console.log(file); + } + + main(); + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const fileObject = await client.files.create({ + file: fs.createReadStream('fine-tune.jsonl'), + purpose: 'assistants', + }); + + console.log(fileObject.id); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfileObject, err := client.Files.New(context.TODO(), openai.FileNewParams{\n\t\tFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\tPurpose: openai.FilePurposeAssistants,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fileObject.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.files.FileCreateParams; + import com.openai.models.files.FileObject; + import com.openai.models.files.FilePurpose; + import java.io.ByteArrayInputStream; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileCreateParams params = FileCreateParams.builder() + .file(new ByteArrayInputStream("Example data".getBytes())) + .purpose(FilePurpose.ASSISTANTS) + .build(); + FileObject fileObject = client.files().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + file_object = openai.files.create(file: StringIO.new("Example + data"), purpose: :assistants) + + + puts(file_object) + response: | + { + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "expires_at": 1677614202, + "filename": "mydata.jsonl", + "purpose": "fine-tune", + } + /files/{file_id}: + delete: + operationId: deleteFile + tags: + - Files + summary: Delete a file and remove it from all vector stores. + parameters: + - in: path + name: file_id + required: true + schema: + type: string + description: The ID of the file to use for this request. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteFileResponse' + x-oaiMeta: + name: Delete file + group: files + examples: + request: + curl: | + curl https://api.openai.com/v1/files/file-abc123 \ + -X DELETE \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + file_deleted = client.files.delete( + "file_id", + ) + print(file_deleted.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const file = await openai.files.delete("file-abc123"); + + console.log(file); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const fileDeleted = await client.files.delete('file_id'); + + console.log(fileDeleted.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfileDeleted, err := client.Files.Delete(context.TODO(), \"file_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fileDeleted.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.files.FileDeleteParams; + import com.openai.models.files.FileDeleted; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileDeleted fileDeleted = client.files().delete("file_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + file_deleted = openai.files.delete("file_id") + + puts(file_deleted) + response: | + { + "id": "file-abc123", + "object": "file", + "deleted": true + } + get: + operationId: retrieveFile + tags: + - Files + summary: Returns information about a specific file. + parameters: + - in: path + name: file_id + required: true + schema: + type: string + description: The ID of the file to use for this request. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/OpenAIFile' + x-oaiMeta: + name: Retrieve file + group: files + examples: + request: + curl: | + curl https://api.openai.com/v1/files/file-abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + file_object = client.files.retrieve( + "file_id", + ) + print(file_object.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const file = await openai.files.retrieve("file-abc123"); + + console.log(file); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const fileObject = await client.files.retrieve('file_id'); + + console.log(fileObject.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfileObject, err := client.Files.Get(context.TODO(), \"file_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fileObject.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.files.FileObject; + import com.openai.models.files.FileRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileObject fileObject = client.files().retrieve("file_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + file_object = openai.files.retrieve("file_id") + + puts(file_object) + response: | + { + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "expires_at": 1677614202, + "filename": "mydata.jsonl", + "purpose": "fine-tune", + } + /files/{file_id}/content: + get: + operationId: downloadFile + tags: + - Files + summary: Returns the contents of the specified file. + parameters: + - in: path + name: file_id + required: true + schema: + type: string + description: The ID of the file to use for this request. + responses: + '200': + description: OK + content: + application/json: + schema: + type: string + x-oaiMeta: + name: Retrieve file content + group: files + examples: + request: + curl: | + curl https://api.openai.com/v1/files/file-abc123/content \ + -H "Authorization: Bearer $OPENAI_API_KEY" > file.jsonl + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.files.content( + "file_id", + ) + print(response) + content = response.read() + print(content) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const file = await openai.files.content("file-abc123"); + + console.log(file); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.files.content('file_id'); + + console.log(response); + + const content = await response.blob(); + console.log(content); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Files.Content(context.TODO(), \"file_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.core.http.HttpResponse; + import com.openai.models.files.FileContentParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + HttpResponse response = client.files().content("file_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.files.content("file_id") + + puts(response) + response: '' + /fine_tuning/alpha/graders/run: + post: + operationId: runGrader + tags: + - Fine-tuning + summary: | + Run a grader. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RunGraderRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/RunGraderResponse' + x-oaiMeta: + name: Run grader + beta: true + group: graders + examples: + - title: Score text alignment + request: + curl: > + curl -X POST + https://api.openai.com/v1/fine_tuning/alpha/graders/run \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "grader": { + "type": "score_model", + "name": "Example score model grader", + "input": [ + { + "role": "user", + "content": [ + { + "type": "input_text", + "text": "Score how close the reference answer is to the model answer on a 0-1 scale. Return only the score.\n\nReference answer: {{item.reference_answer}}\n\nModel answer: {{sample.output_text}}" + } + ] + } + ], + "model": "gpt-5-mini", + "sampling_params": { + "temperature": 1, + "top_p": 1, + "seed": 42 + } + }, + "item": { + "reference_answer": "fuzzy wuzzy was a bear" + }, + "model_sample": "fuzzy wuzzy was a bear" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.fine_tuning.alpha.graders.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + ) + print(response.metadata) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const result = await openai.fineTuning.alpha.graders.run({ + grader: { + type: "score_model", + name: "Example score model grader", + input: [ + { + role: "user", + content: [ + { + type: "input_text", + text: "Score how close the reference answer is to the model answer on a 0-1 scale. Return only the score.\n\nReference answer: {{item.reference_answer}}\n\nModel answer: {{sample.output_text}}", + }, + ], + }, + ], + model: "gpt-5-mini", + sampling_params: { temperature: 1, top_p: 1, seed: 42 }, + }, + item: { reference_answer: "fuzzy wuzzy was a bear" }, + model_sample: "fuzzy wuzzy was a bear", + }); + console.log(result); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.fineTuning.alpha.graders.run({ + grader: { + input: 'input', + name: 'name', + operation: 'eq', + reference: 'reference', + type: 'string_check', + }, + model_sample: 'model_sample', + }); + + console.log(response.metadata); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.FineTuning.Alpha.Graders.Run(context.TODO(), openai.FineTuningAlphaGraderRunParams{\n\t\tGrader: openai.FineTuningAlphaGraderRunParamsGraderUnion{\n\t\t\tOfStringCheck: &openai.StringCheckGraderParam{\n\t\t\t\tInput: \"input\",\n\t\t\t\tName: \"name\",\n\t\t\t\tOperation: openai.StringCheckGraderOperationEq,\n\t\t\t\tReference: \"reference\",\n\t\t\t},\n\t\t},\n\t\tModelSample: \"model_sample\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.Metadata)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.finetuning.alpha.graders.GraderRunParams; + + import + com.openai.models.finetuning.alpha.graders.GraderRunResponse; + + import com.openai.models.graders.gradermodels.StringCheckGrader; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + GraderRunParams params = GraderRunParams.builder() + .grader(StringCheckGrader.builder() + .input("input") + .name("name") + .operation(StringCheckGrader.Operation.EQ) + .reference("reference") + .build()) + .modelSample("model_sample") + .build(); + GraderRunResponse response = client.fineTuning().alpha().graders().run(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.fine_tuning.alpha.graders.run( + grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check}, + model_sample: "model_sample" + ) + + puts(response) + response: | + { + "reward": 1.0, + "metadata": { + "name": "Example score model grader", + "type": "score_model", + "errors": { + "formula_parse_error": false, + "sample_parse_error": false, + "truncated_observation_error": false, + "unresponsive_reward_error": false, + "invalid_variable_error": false, + "other_error": false, + "python_grader_server_error": false, + "python_grader_server_error_type": null, + "python_grader_runtime_error": false, + "python_grader_runtime_error_details": null, + "model_grader_server_error": false, + "model_grader_refusal_error": false, + "model_grader_parse_error": false, + "model_grader_server_error_details": null + }, + "execution_time": 4.365238428115845, + "scores": {}, + "token_usage": { + "prompt_tokens": 190, + "total_tokens": 324, + "completion_tokens": 134, + "cached_tokens": 0 + }, + "sampled_model_name": "gpt-4o-2024-08-06" + }, + "sub_rewards": {}, + "model_grader_token_usage_per_model": { + "gpt-4o-2024-08-06": { + "prompt_tokens": 190, + "total_tokens": 324, + "completion_tokens": 134, + "cached_tokens": 0 + } + } + } + - title: Score an image caption + request: + curl: > + curl -X POST + https://api.openai.com/v1/fine_tuning/alpha/graders/run \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "grader": { + "type": "score_model", + "name": "Image caption grader", + "input": [ + { + "role": "user", + "content": [ + { + "type": "input_text", + "text": "Score how well the provided caption matches the image on a 0-1 scale. Only return the score.\n\nCaption: {{sample.output_text}}" + }, + { + "type": "input_image", + "image_url": "https://example.com/dog-catching-ball.png", + "file_id": null, + "detail": "high" + } + ] + } + ], + "model": "gpt-5-mini", + "sampling_params": { + "temperature": 0.2 + } + }, + "item": { + "expected_caption": "A golden retriever jumps to catch a tennis ball" + }, + "model_sample": "A dog leaps to grab a tennis ball mid-air" + }' + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.fineTuning.alpha.graders.run({ + grader: { + input: 'input', + name: 'name', + operation: 'eq', + reference: 'reference', + type: 'string_check', + }, + model_sample: 'model_sample', + }); + + console.log(response.metadata); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.fine_tuning.alpha.graders.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + ) + print(response.metadata) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.FineTuning.Alpha.Graders.Run(context.TODO(), openai.FineTuningAlphaGraderRunParams{\n\t\tGrader: openai.FineTuningAlphaGraderRunParamsGraderUnion{\n\t\t\tOfStringCheck: &openai.StringCheckGraderParam{\n\t\t\t\tInput: \"input\",\n\t\t\t\tName: \"name\",\n\t\t\t\tOperation: openai.StringCheckGraderOperationEq,\n\t\t\t\tReference: \"reference\",\n\t\t\t},\n\t\t},\n\t\tModelSample: \"model_sample\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.Metadata)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.finetuning.alpha.graders.GraderRunParams; + + import + com.openai.models.finetuning.alpha.graders.GraderRunResponse; + + import com.openai.models.graders.gradermodels.StringCheckGrader; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + GraderRunParams params = GraderRunParams.builder() + .grader(StringCheckGrader.builder() + .input("input") + .name("name") + .operation(StringCheckGrader.Operation.EQ) + .reference("reference") + .build()) + .modelSample("model_sample") + .build(); + GraderRunResponse response = client.fineTuning().alpha().graders().run(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.fine_tuning.alpha.graders.run( + grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check}, + model_sample: "model_sample" + ) + + puts(response) + - title: Score an audio response + request: + curl: > + curl -X POST + https://api.openai.com/v1/fine_tuning/alpha/graders/run \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "grader": { + "type": "score_model", + "name": "Audio clarity grader", + "input": [ + { + "role": "user", + "content": [ + { + "type": "input_text", + "text": "Listen to the clip and return a confidence score from 0 to 1 that the speaker said: {{item.target_phrase}}" + }, + { + "type": "input_audio", + "input_audio": { + "data": "{{item.audio_clip_b64}}", + "format": "mp3" + } + } + ] + } + ], + "model": "gpt-audio", + "sampling_params": { + "temperature": 0.2, + "top_p": 1, + "seed": 123 + } + }, + "item": { + "target_phrase": "Please deliver the package on Tuesday", + "audio_clip_b64": "" + }, + "model_sample": "Please deliver the package on Tuesday" + }' + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.fineTuning.alpha.graders.run({ + grader: { + input: 'input', + name: 'name', + operation: 'eq', + reference: 'reference', + type: 'string_check', + }, + model_sample: 'model_sample', + }); + + console.log(response.metadata); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.fine_tuning.alpha.graders.run( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + model_sample="model_sample", + ) + print(response.metadata) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.FineTuning.Alpha.Graders.Run(context.TODO(), openai.FineTuningAlphaGraderRunParams{\n\t\tGrader: openai.FineTuningAlphaGraderRunParamsGraderUnion{\n\t\t\tOfStringCheck: &openai.StringCheckGraderParam{\n\t\t\t\tInput: \"input\",\n\t\t\t\tName: \"name\",\n\t\t\t\tOperation: openai.StringCheckGraderOperationEq,\n\t\t\t\tReference: \"reference\",\n\t\t\t},\n\t\t},\n\t\tModelSample: \"model_sample\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.Metadata)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.finetuning.alpha.graders.GraderRunParams; + + import + com.openai.models.finetuning.alpha.graders.GraderRunResponse; + + import com.openai.models.graders.gradermodels.StringCheckGrader; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + GraderRunParams params = GraderRunParams.builder() + .grader(StringCheckGrader.builder() + .input("input") + .name("name") + .operation(StringCheckGrader.Operation.EQ) + .reference("reference") + .build()) + .modelSample("model_sample") + .build(); + GraderRunResponse response = client.fineTuning().alpha().graders().run(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.fine_tuning.alpha.graders.run( + grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check}, + model_sample: "model_sample" + ) + + puts(response) + /fine_tuning/alpha/graders/validate: + post: + operationId: validateGrader + tags: + - Fine-tuning + summary: | + Validate a grader. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ValidateGraderRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ValidateGraderResponse' + x-oaiMeta: + name: Validate grader + beta: true + group: graders + examples: + request: + curl: > + curl https://api.openai.com/v1/fine_tuning/alpha/graders/validate + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "grader": { + "type": "string_check", + "name": "Example string check grader", + "input": "{{sample.output_text}}", + "reference": "{{item.label}}", + "operation": "eq" + } + }' + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.fineTuning.alpha.graders.validate({ + grader: { + input: 'input', + name: 'name', + operation: 'eq', + reference: 'reference', + type: 'string_check', + }, + }); + + console.log(response.grader); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.fine_tuning.alpha.graders.validate( + grader={ + "input": "input", + "name": "name", + "operation": "eq", + "reference": "reference", + "type": "string_check", + }, + ) + print(response.grader) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.FineTuning.Alpha.Graders.Validate(context.TODO(), openai.FineTuningAlphaGraderValidateParams{\n\t\tGrader: openai.FineTuningAlphaGraderValidateParamsGraderUnion{\n\t\t\tOfStringCheckGrader: &openai.StringCheckGraderParam{\n\t\t\t\tInput: \"input\",\n\t\t\t\tName: \"name\",\n\t\t\t\tOperation: openai.StringCheckGraderOperationEq,\n\t\t\t\tReference: \"reference\",\n\t\t\t},\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.Grader)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.finetuning.alpha.graders.GraderValidateParams; + + import + com.openai.models.finetuning.alpha.graders.GraderValidateResponse; + + import com.openai.models.graders.gradermodels.StringCheckGrader; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + GraderValidateParams params = GraderValidateParams.builder() + .grader(StringCheckGrader.builder() + .input("input") + .name("name") + .operation(StringCheckGrader.Operation.EQ) + .reference("reference") + .build()) + .build(); + GraderValidateResponse response = client.fineTuning().alpha().graders().validate(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.fine_tuning.alpha.graders.validate( + grader: {input: "input", name: "name", operation: :eq, reference: "reference", type: :string_check} + ) + + puts(response) + response: | + { + "grader": { + "type": "string_check", + "name": "Example string check grader", + "input": "{{sample.output_text}}", + "reference": "{{item.label}}", + "operation": "eq" + } + } + /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions: + get: + operationId: listFineTuningCheckpointPermissions + tags: + - Fine-tuning + summary: > + **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + + + Organization owners can use this endpoint to view all permissions for a + fine-tuned model checkpoint. + parameters: + - in: path + name: fine_tuned_model_checkpoint + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuned model checkpoint to get permissions for. + - name: project_id + in: query + description: The ID of the project to get permissions for. + required: false + schema: + type: string + - name: after + in: query + description: >- + Identifier for the last permission ID from the previous pagination + request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of permissions to retrieve. + required: false + schema: + type: integer + default: 10 + - name: order + in: query + description: The order in which to retrieve permissions. + required: false + schema: + type: string + enum: + - ascending + - descending + default: descending + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: >- + #/components/schemas/ListFineTuningCheckpointPermissionResponse + x-oaiMeta: + name: List checkpoint permissions + group: fine-tuning + examples: + request: + curl: > + curl + https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const permission = await + client.fineTuning.checkpoints.permissions.retrieve( + 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + ); + + + console.log(permission.first_id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + permission = client.fine_tuning.checkpoints.permissions.retrieve( + fine_tuned_model_checkpoint="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + print(permission.first_id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpermission, err := client.FineTuning.Checkpoints.Permissions.Get(\n\t\tcontext.TODO(),\n\t\t\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n\t\topenai.FineTuningCheckpointPermissionGetParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", permission.FirstID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveParams; + + import + com.openai.models.finetuning.checkpoints.permissions.PermissionRetrieveResponse; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + PermissionRetrieveResponse permission = client.fineTuning().checkpoints().permissions().retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + permission = + openai.fine_tuning.checkpoints.permissions.retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F") + + + puts(permission) + response: | + { + "object": "list", + "data": [ + { + "object": "checkpoint.permission", + "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", + "created_at": 1721764867, + "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH" + }, + { + "object": "checkpoint.permission", + "id": "cp_enQCFmOTGj3syEpYVhBRLTSy", + "created_at": 1721764800, + "project_id": "proj_iqGMw1llN8IrBb6SvvY5A1oF" + }, + ], + "first_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", + "last_id": "cp_enQCFmOTGj3syEpYVhBRLTSy", + "has_more": false + } + post: + operationId: createFineTuningCheckpointPermission + tags: + - Fine-tuning + summary: > + **NOTE:** Calling this endpoint requires an [admin API + key](../admin-api-keys). + + + This enables organization owners to share fine-tuned models with other + projects in their organization. + parameters: + - in: path + name: fine_tuned_model_checkpoint + required: true + schema: + type: string + example: ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd + description: > + The ID of the fine-tuned model checkpoint to create a permission + for. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateFineTuningCheckpointPermissionRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: >- + #/components/schemas/ListFineTuningCheckpointPermissionResponse + x-oaiMeta: + name: Create checkpoint permissions + group: fine-tuning + examples: + request: + curl: > + curl + https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + -d '{"project_ids": ["proj_abGMw1llN8IrBb6SvvY5A1iH"]}' + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const permissionCreateResponse of + client.fineTuning.checkpoints.permissions.create( + 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + { project_ids: ['string'] }, + )) { + console.log(permissionCreateResponse.id); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.fine_tuning.checkpoints.permissions.create( + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + project_ids=["string"], + ) + page = page.data[0] + print(page.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.FineTuning.Checkpoints.Permissions.New(\n\t\tcontext.TODO(),\n\t\t\"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\",\n\t\topenai.FineTuningCheckpointPermissionNewParams{\n\t\t\tProjectIDs: []string{\"string\"},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.finetuning.checkpoints.permissions.PermissionCreatePage; + + import + com.openai.models.finetuning.checkpoints.permissions.PermissionCreateParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + PermissionCreateParams params = PermissionCreateParams.builder() + .fineTunedModelCheckpoint("ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd") + .addProjectId("string") + .build(); + PermissionCreatePage page = client.fineTuning().checkpoints().permissions().create(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.fine_tuning.checkpoints.permissions.create( + "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + project_ids: ["string"] + ) + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "object": "checkpoint.permission", + "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", + "created_at": 1721764867, + "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH" + } + ], + "first_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", + "last_id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", + "has_more": false + } + /fine_tuning/checkpoints/{fine_tuned_model_checkpoint}/permissions/{permission_id}: + delete: + operationId: deleteFineTuningCheckpointPermission + tags: + - Fine-tuning + summary: > + **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + + + Organization owners can use this endpoint to delete a permission for a + fine-tuned model checkpoint. + parameters: + - in: path + name: fine_tuned_model_checkpoint + required: true + schema: + type: string + example: ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd + description: > + The ID of the fine-tuned model checkpoint to delete a permission + for. + - in: path + name: permission_id + required: true + schema: + type: string + example: cp_zc4Q7MP6XxulcVzj4MZdwsAB + description: | + The ID of the fine-tuned model checkpoint permission to delete. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: >- + #/components/schemas/DeleteFineTuningCheckpointPermissionResponse + x-oaiMeta: + name: Delete checkpoint permission + group: fine-tuning + examples: + request: + curl: > + curl + https://api.openai.com/v1/fine_tuning/checkpoints/ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd/permissions/cp_zc4Q7MP6XxulcVzj4MZdwsAB + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const permission = await + client.fineTuning.checkpoints.permissions.delete( + 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + { fine_tuned_model_checkpoint: 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd' }, + ); + + + console.log(permission.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + permission = client.fine_tuning.checkpoints.permissions.delete( + permission_id="cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint="ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd", + ) + print(permission.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpermission, err := client.FineTuning.Checkpoints.Permissions.Delete(\n\t\tcontext.TODO(),\n\t\t\"ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd\",\n\t\t\"cp_zc4Q7MP6XxulcVzj4MZdwsAB\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", permission.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteParams; + + import + com.openai.models.finetuning.checkpoints.permissions.PermissionDeleteResponse; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + PermissionDeleteParams params = PermissionDeleteParams.builder() + .fineTunedModelCheckpoint("ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd") + .permissionId("cp_zc4Q7MP6XxulcVzj4MZdwsAB") + .build(); + PermissionDeleteResponse permission = client.fineTuning().checkpoints().permissions().delete(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + permission = openai.fine_tuning.checkpoints.permissions.delete( + "cp_zc4Q7MP6XxulcVzj4MZdwsAB", + fine_tuned_model_checkpoint: "ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd" + ) + + puts(permission) + response: | + { + "object": "checkpoint.permission", + "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", + "deleted": true + } + /fine_tuning/jobs: + post: + operationId: createFineTuningJob + tags: + - Fine-tuning + summary: > + Creates a fine-tuning job which begins the process of creating a new + model from a given dataset. + + + Response includes details of the enqueued job including job status and + the name of the fine-tuned models once complete. + + + [Learn more about fine-tuning](/docs/guides/model-optimization) + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateFineTuningJobRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/FineTuningJob' + x-oaiMeta: + name: Create fine-tuning job + group: fine-tuning + examples: + - title: Default + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "training_file": "file-BK7bzQj3FfZFXr7DbL6xJwfo", + "model": "gpt-4o-mini" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.create( + model="gpt-4o-mini", + training_file="file-abc123", + ) + print(fine_tuning_job.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.create({ + training_file: "file-abc123" + }); + + console.log(fineTune); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const fineTuningJob = await client.fineTuning.jobs.create({ + model: 'gpt-4o-mini', + training_file: 'file-abc123', + }); + + console.log(fineTuningJob.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n\t\tModel: openai.FineTuningJobNewParamsModelGPT4oMini,\n\t\tTrainingFile: \"file-abc123\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + JobCreateParams params = JobCreateParams.builder() + .model(JobCreateParams.Model.GPT_4O_MINI) + .trainingFile("file-abc123") + .build(); + FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = openai.fine_tuning.jobs.create(model: + :"gpt-4o-mini", training_file: "file-abc123") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": null, + "training_file": "file-abc123", + "method": { + "type": "supervised", + "supervised": { + "hyperparameters": { + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + } + } + }, + "metadata": null + } + - title: Epochs + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "training_file": "file-abc123", + "model": "gpt-4o-mini", + "method": { + "type": "supervised", + "supervised": { + "hyperparameters": { + "n_epochs": 2 + } + } + } + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.create( + model="gpt-4o-mini", + training_file="file-abc123", + ) + print(fine_tuning_job.id) + javascript: > + import OpenAI from "openai"; + + import { SupervisedMethod, SupervisedHyperparameters } from + "openai/resources/fine-tuning/methods"; + + + const openai = new OpenAI(); + + + async function main() { + const fineTune = await openai.fineTuning.jobs.create({ + training_file: "file-abc123", + model: "gpt-4o-mini", + method: { + type: "supervised", + supervised: { + hyperparameters: { + n_epochs: 2 + } + } + } + }); + + console.log(fineTune); + } + + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const fineTuningJob = await client.fineTuning.jobs.create({ + model: 'gpt-4o-mini', + training_file: 'file-abc123', + }); + + console.log(fineTuningJob.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n\t\tModel: openai.FineTuningJobNewParamsModelGPT4oMini,\n\t\tTrainingFile: \"file-abc123\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + JobCreateParams params = JobCreateParams.builder() + .model(JobCreateParams.Model.GPT_4O_MINI) + .trainingFile("file-abc123") + .build(); + FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = openai.fine_tuning.jobs.create(model: + :"gpt-4o-mini", training_file: "file-abc123") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": null, + "training_file": "file-abc123", + "hyperparameters": { + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": 2 + }, + "method": { + "type": "supervised", + "supervised": { + "hyperparameters": { + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": 2 + } + } + }, + "metadata": null, + "error": { + "code": null, + "message": null, + "param": null + }, + "finished_at": null, + "seed": 683058546, + "trained_tokens": null, + "estimated_finish": null, + "integrations": [], + "user_provided_suffix": null, + "usage_metrics": null, + "shared_with_openai": false + } + - title: DPO + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "training_file": "file-abc123", + "validation_file": "file-abc123", + "model": "gpt-4o-mini", + "method": { + "type": "dpo", + "dpo": { + "hyperparameters": { + "beta": 0.1 + } + } + } + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.create( + model="gpt-4o-mini", + training_file="file-abc123", + ) + print(fine_tuning_job.id) + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const fineTuningJob = await client.fineTuning.jobs.create({ + model: 'gpt-4o-mini', + training_file: 'file-abc123', + }); + + console.log(fineTuningJob.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n\t\tModel: openai.FineTuningJobNewParamsModelGPT4oMini,\n\t\tTrainingFile: \"file-abc123\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + JobCreateParams params = JobCreateParams.builder() + .model(JobCreateParams.Model.GPT_4O_MINI) + .trainingFile("file-abc123") + .build(); + FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = openai.fine_tuning.jobs.create(model: + :"gpt-4o-mini", training_file: "file-abc123") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc", + "model": "gpt-4o-mini", + "created_at": 1746130590, + "fine_tuned_model": null, + "organization_id": "org-abc", + "result_files": [], + "status": "queued", + "validation_file": "file-123", + "training_file": "file-abc", + "method": { + "type": "dpo", + "dpo": { + "hyperparameters": { + "beta": 0.1, + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto" + } + } + }, + "metadata": null, + "error": { + "code": null, + "message": null, + "param": null + }, + "finished_at": null, + "hyperparameters": null, + "seed": 1036326793, + "estimated_finish": null, + "integrations": [], + "user_provided_suffix": null, + "usage_metrics": null, + "shared_with_openai": false + } + - title: Reinforcement + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "training_file": "file-abc", + "validation_file": "file-123", + "model": "o4-mini", + "method": { + "type": "reinforcement", + "reinforcement": { + "grader": { + "type": "string_check", + "name": "Example string check grader", + "input": "{{sample.output_text}}", + "reference": "{{item.label}}", + "operation": "eq" + }, + "hyperparameters": { + "reasoning_effort": "medium" + } + } + } + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.create( + model="gpt-4o-mini", + training_file="file-abc123", + ) + print(fine_tuning_job.id) + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const fineTuningJob = await client.fineTuning.jobs.create({ + model: 'gpt-4o-mini', + training_file: 'file-abc123', + }); + + console.log(fineTuningJob.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n\t\tModel: openai.FineTuningJobNewParamsModelGPT4oMini,\n\t\tTrainingFile: \"file-abc123\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + JobCreateParams params = JobCreateParams.builder() + .model(JobCreateParams.Model.GPT_4O_MINI) + .trainingFile("file-abc123") + .build(); + FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = openai.fine_tuning.jobs.create(model: + :"gpt-4o-mini", training_file: "file-abc123") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "o4-mini", + "created_at": 1721764800, + "finished_at": null, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "validating_files", + "validation_file": "file-123", + "training_file": "file-abc", + "trained_tokens": null, + "error": {}, + "user_provided_suffix": null, + "seed": 950189191, + "estimated_finish": null, + "integrations": [], + "method": { + "type": "reinforcement", + "reinforcement": { + "hyperparameters": { + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + "eval_interval": "auto", + "eval_samples": "auto", + "compute_multiplier": "auto", + "reasoning_effort": "medium" + }, + "grader": { + "type": "string_check", + "name": "Example string check grader", + "input": "{{sample.output_text}}", + "reference": "{{item.label}}", + "operation": "eq" + }, + "response_format": null + } + }, + "metadata": null, + "usage_metrics": null, + "shared_with_openai": false + } + + - title: Validation file + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "training_file": "file-abc123", + "validation_file": "file-abc123", + "model": "gpt-4o-mini" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.create( + model="gpt-4o-mini", + training_file="file-abc123", + ) + print(fine_tuning_job.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.create({ + training_file: "file-abc123", + validation_file: "file-abc123" + }); + + console.log(fineTune); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const fineTuningJob = await client.fineTuning.jobs.create({ + model: 'gpt-4o-mini', + training_file: 'file-abc123', + }); + + console.log(fineTuningJob.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n\t\tModel: openai.FineTuningJobNewParamsModelGPT4oMini,\n\t\tTrainingFile: \"file-abc123\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + JobCreateParams params = JobCreateParams.builder() + .model(JobCreateParams.Model.GPT_4O_MINI) + .trainingFile("file-abc123") + .build(); + FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = openai.fine_tuning.jobs.create(model: + :"gpt-4o-mini", training_file: "file-abc123") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": "file-abc123", + "training_file": "file-abc123", + "method": { + "type": "supervised", + "supervised": { + "hyperparameters": { + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + } + } + }, + "metadata": null + } + - title: W&B Integration + request: + curl: | + curl https://api.openai.com/v1/fine_tuning/jobs \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "training_file": "file-abc123", + "validation_file": "file-abc123", + "model": "gpt-4o-mini", + "integrations": [ + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "name": "ft-run-display-name" + "tags": [ + "first-experiment", "v2" + ] + } + } + ] + }' + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const fineTuningJob = await client.fineTuning.jobs.create({ + model: 'gpt-4o-mini', + training_file: 'file-abc123', + }); + + console.log(fineTuningJob.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.create( + model="gpt-4o-mini", + training_file="file-abc123", + ) + print(fine_tuning_job.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.New(context.TODO(), openai.FineTuningJobNewParams{\n\t\tModel: openai.FineTuningJobNewParamsModelGPT4oMini,\n\t\tTrainingFile: \"file-abc123\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + JobCreateParams params = JobCreateParams.builder() + .model(JobCreateParams.Model.GPT_4O_MINI) + .trainingFile("file-abc123") + .build(); + FineTuningJob fineTuningJob = client.fineTuning().jobs().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = openai.fine_tuning.jobs.create(model: + :"gpt-4o-mini", training_file: "file-abc123") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": "file-abc123", + "training_file": "file-abc123", + "integrations": [ + { + "type": "wandb", + "wandb": { + "project": "my-wandb-project", + "entity": None, + "run_id": "ftjob-abc123" + } + } + ], + "method": { + "type": "supervised", + "supervised": { + "hyperparameters": { + "batch_size": "auto", + "learning_rate_multiplier": "auto", + "n_epochs": "auto", + } + } + }, + "metadata": null + } + get: + operationId: listPaginatedFineTuningJobs + tags: + - Fine-tuning + summary: | + List your organization's fine-tuning jobs + parameters: + - name: after + in: query + description: Identifier for the last job from the previous pagination request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of fine-tuning jobs to retrieve. + required: false + schema: + type: integer + default: 20 + - in: query + name: metadata + required: false + schema: + type: object + nullable: true + additionalProperties: + type: string + style: deepObject + explode: true + description: > + Optional metadata filter. To filter, use the syntax `metadata[k]=v`. + Alternatively, set `metadata=null` to indicate no metadata. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListPaginatedFineTuningJobsResponse' + x-oaiMeta: + name: List fine-tuning jobs + group: fine-tuning + examples: + request: + curl: > + curl + https://api.openai.com/v1/fine_tuning/jobs?limit=2&metadata[key]=value + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.fine_tuning.jobs.list() + page = page.data[0] + print(page.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const list = await openai.fineTuning.jobs.list(); + + for await (const fineTune of list) { + console.log(fineTune); + } + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + // Automatically fetches more pages as needed. + for await (const fineTuningJob of client.fineTuning.jobs.list()) { + console.log(fineTuningJob.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.FineTuning.Jobs.List(context.TODO(), openai.FineTuningJobListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.JobListPage; + import com.openai.models.finetuning.jobs.JobListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + JobListPage page = client.fineTuning().jobs().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.fine_tuning.jobs.list + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": null, + "training_file": "file-abc123", + "metadata": { + "key": "value" + } + }, + { ... }, + { ... } + ], "has_more": true + } + /fine_tuning/jobs/{fine_tuning_job_id}: + get: + operationId: retrieveFineTuningJob + tags: + - Fine-tuning + summary: | + Get info about a fine-tuning job. + + [Learn more about fine-tuning](/docs/guides/model-optimization) + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/FineTuningJob' + x-oaiMeta: + name: Retrieve fine-tuning job + group: fine-tuning + examples: + request: + curl: > + curl + https://api.openai.com/v1/fine_tuning/jobs/ft-AF1WoRqd3aJAHsqc9NY7iL8F + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.retrieve( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + print(fine_tuning_job.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.retrieve("ftjob-abc123"); + + console.log(fineTune); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const fineTuningJob = await + client.fineTuning.jobs.retrieve('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); + + + console.log(fineTuningJob.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.Get(context.TODO(), \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FineTuningJob fineTuningJob = client.fineTuning().jobs().retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = + openai.fine_tuning.jobs.retrieve("ft-AF1WoRqd3aJAHsqc9NY7iL8F") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "davinci-002", + "created_at": 1692661014, + "finished_at": 1692661190, + "fine_tuned_model": "ft:davinci-002:my-org:custom_suffix:7q8mpxmy", + "organization_id": "org-123", + "result_files": [ + "file-abc123" + ], + "status": "succeeded", + "validation_file": null, + "training_file": "file-abc123", + "hyperparameters": { + "n_epochs": 4, + "batch_size": 1, + "learning_rate_multiplier": 1.0 + }, + "trained_tokens": 5768, + "integrations": [], + "seed": 0, + "estimated_finish": 0, + "method": { + "type": "supervised", + "supervised": { + "hyperparameters": { + "n_epochs": 4, + "batch_size": 1, + "learning_rate_multiplier": 1.0 + } + } + } + } + /fine_tuning/jobs/{fine_tuning_job_id}/cancel: + post: + operationId: cancelFineTuningJob + tags: + - Fine-tuning + summary: | + Immediately cancel a fine-tune job. + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job to cancel. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/FineTuningJob' + x-oaiMeta: + name: Cancel fine-tuning + group: fine-tuning + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/cancel \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.cancel( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + print(fine_tuning_job.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.cancel("ftjob-abc123"); + + console.log(fineTune); + } + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const fineTuningJob = await + client.fineTuning.jobs.cancel('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); + + + console.log(fineTuningJob.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.Cancel(context.TODO(), \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobCancelParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FineTuningJob fineTuningJob = client.fineTuning().jobs().cancel("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = + openai.fine_tuning.jobs.cancel("ft-AF1WoRqd3aJAHsqc9NY7iL8F") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "cancelled", + "validation_file": "file-abc123", + "training_file": "file-abc123" + } + /fine_tuning/jobs/{fine_tuning_job_id}/checkpoints: + get: + operationId: listFineTuningJobCheckpoints + tags: + - Fine-tuning + summary: | + List checkpoints for a fine-tuning job. + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job to get checkpoints for. + - name: after + in: query + description: >- + Identifier for the last checkpoint ID from the previous pagination + request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of checkpoints to retrieve. + required: false + schema: + type: integer + default: 10 + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListFineTuningJobCheckpointsResponse' + x-oaiMeta: + name: List fine-tuning checkpoints + group: fine-tuning + examples: + request: + curl: > + curl + https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/checkpoints + \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const fineTuningJobCheckpoint of + client.fineTuning.jobs.checkpoints.list( + 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + )) { + console.log(fineTuningJobCheckpoint.id); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.fine_tuning.jobs.checkpoints.list( + fine_tuning_job_id="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + page = page.data[0] + print(page.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.FineTuning.Jobs.Checkpoints.List(\n\t\tcontext.TODO(),\n\t\t\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n\t\topenai.FineTuningJobCheckpointListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.finetuning.jobs.checkpoints.CheckpointListPage; + + import + com.openai.models.finetuning.jobs.checkpoints.CheckpointListParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + CheckpointListPage page = client.fineTuning().jobs().checkpoints().list("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + page = + openai.fine_tuning.jobs.checkpoints.list("ft-AF1WoRqd3aJAHsqc9NY7iL8F") + + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "object": "fine_tuning.job.checkpoint", + "id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", + "created_at": 1721764867, + "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:96olL566:ckpt-step-2000", + "metrics": { + "full_valid_loss": 0.134, + "full_valid_mean_token_accuracy": 0.874 + }, + "fine_tuning_job_id": "ftjob-abc123", + "step_number": 2000 + }, + { + "object": "fine_tuning.job.checkpoint", + "id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy", + "created_at": 1721764800, + "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom-suffix:7q8mpxmy:ckpt-step-1000", + "metrics": { + "full_valid_loss": 0.167, + "full_valid_mean_token_accuracy": 0.781 + }, + "fine_tuning_job_id": "ftjob-abc123", + "step_number": 1000 + } + ], + "first_id": "ftckpt_zc4Q7MP6XxulcVzj4MZdwsAB", + "last_id": "ftckpt_enQCFmOTGj3syEpYVhBRLTSy", + "has_more": true + } + /fine_tuning/jobs/{fine_tuning_job_id}/events: + get: + operationId: listFineTuningEvents + tags: + - Fine-tuning + summary: | + Get status updates for a fine-tuning job. + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job to get events for. + - name: after + in: query + description: Identifier for the last event from the previous pagination request. + required: false + schema: + type: string + - name: limit + in: query + description: Number of events to retrieve. + required: false + schema: + type: integer + default: 20 + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListFineTuningJobEventsResponse' + x-oaiMeta: + name: List fine-tuning events + group: fine-tuning + examples: + request: + curl: > + curl + https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/events \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.fine_tuning.jobs.list_events( + fine_tuning_job_id="ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + page = page.data[0] + print(page.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const list = await openai.fineTuning.list_events(id="ftjob-abc123", limit=2); + + for await (const fineTune of list) { + console.log(fineTune); + } + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const fineTuningJobEvent of + client.fineTuning.jobs.listEvents( + 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + )) { + console.log(fineTuningJobEvent.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.FineTuning.Jobs.ListEvents(\n\t\tcontext.TODO(),\n\t\t\"ft-AF1WoRqd3aJAHsqc9NY7iL8F\",\n\t\topenai.FineTuningJobListEventsParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.JobListEventsPage; + import com.openai.models.finetuning.jobs.JobListEventsParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + JobListEventsPage page = client.fineTuning().jobs().listEvents("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + page = + openai.fine_tuning.jobs.list_events("ft-AF1WoRqd3aJAHsqc9NY7iL8F") + + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "object": "fine_tuning.job.event", + "id": "ft-event-ddTJfwuMVpfLXseO0Am0Gqjm", + "created_at": 1721764800, + "level": "info", + "message": "Fine tuning job successfully completed", + "data": null, + "type": "message" + }, + { + "object": "fine_tuning.job.event", + "id": "ft-event-tyiGuB72evQncpH87xe505Sv", + "created_at": 1721764800, + "level": "info", + "message": "New fine-tuned model created: ft:gpt-4o-mini:openai::7p4lURel", + "data": null, + "type": "message" + } + ], + "has_more": true + } + /fine_tuning/jobs/{fine_tuning_job_id}/pause: + post: + operationId: pauseFineTuningJob + tags: + - Fine-tuning + summary: | + Pause a fine-tune job. + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job to pause. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/FineTuningJob' + x-oaiMeta: + name: Pause fine-tuning + group: fine-tuning + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/pause \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.pause( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + print(fine_tuning_job.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.pause("ftjob-abc123"); + + console.log(fineTune); + } + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const fineTuningJob = await + client.fineTuning.jobs.pause('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); + + + console.log(fineTuningJob.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.Pause(context.TODO(), \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobPauseParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FineTuningJob fineTuningJob = client.fineTuning().jobs().pause("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = + openai.fine_tuning.jobs.pause("ft-AF1WoRqd3aJAHsqc9NY7iL8F") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "paused", + "validation_file": "file-abc123", + "training_file": "file-abc123" + } + /fine_tuning/jobs/{fine_tuning_job_id}/resume: + post: + operationId: resumeFineTuningJob + tags: + - Fine-tuning + summary: | + Resume a fine-tune job. + parameters: + - in: path + name: fine_tuning_job_id + required: true + schema: + type: string + example: ft-AF1WoRqd3aJAHsqc9NY7iL8F + description: | + The ID of the fine-tuning job to resume. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/FineTuningJob' + x-oaiMeta: + name: Resume fine-tuning + group: fine-tuning + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/fine_tuning/jobs/ftjob-abc123/resume \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + fine_tuning_job = client.fine_tuning.jobs.resume( + "ft-AF1WoRqd3aJAHsqc9NY7iL8F", + ) + print(fine_tuning_job.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const fineTune = await openai.fineTuning.jobs.resume("ftjob-abc123"); + + console.log(fineTune); + } + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const fineTuningJob = await + client.fineTuning.jobs.resume('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); + + + console.log(fineTuningJob.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tfineTuningJob, err := client.FineTuning.Jobs.Resume(context.TODO(), \"ft-AF1WoRqd3aJAHsqc9NY7iL8F\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", fineTuningJob.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.finetuning.jobs.FineTuningJob; + import com.openai.models.finetuning.jobs.JobResumeParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FineTuningJob fineTuningJob = client.fineTuning().jobs().resume("ft-AF1WoRqd3aJAHsqc9NY7iL8F"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + fine_tuning_job = + openai.fine_tuning.jobs.resume("ft-AF1WoRqd3aJAHsqc9NY7iL8F") + + + puts(fine_tuning_job) + response: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "gpt-4o-mini-2024-07-18", + "created_at": 1721764800, + "fine_tuned_model": null, + "organization_id": "org-123", + "result_files": [], + "status": "queued", + "validation_file": "file-abc123", + "training_file": "file-abc123" + } + /images/edits: + post: + operationId: createImageEdit + tags: + - Images + summary: >- + Creates an edited or extended image given one or more source images and + a prompt. This endpoint supports GPT Image models (`gpt-image-1.5`, + `gpt-image-1`, `gpt-image-1-mini`, and `chatgpt-image-latest`) and + `dall-e-2`. + description: > + You can call this endpoint with either: + + + - `multipart/form-data`: use binary uploads via `image` (and optional + `mask`). + + - `application/json`: use `images` (and optional `mask`) as references + with either `image_url` or `file_id`. + + + Note that JSON requests use `images` (array) instead of the multipart + `image` field. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateImageEditRequest' + examples: + multipart_edit: + summary: Multipart form upload (binary image + prompt) + value: + model: gpt-image-1.5 + prompt: Add a watercolor effect to this image + image: + size: 1024x1024 + quality: high + application/json: + schema: + $ref: '#/components/schemas/EditImageBodyJsonParam' + examples: + json_with_url: + summary: JSON request with image URL + value: + model: gpt-image-1.5 + prompt: Add a watercolor effect to this image + images: + - image_url: https://example.com/source-image.png + size: 1024x1024 + quality: high + json_with_file_id: + summary: JSON request with uploaded file id + value: + model: gpt-image-1.5 + prompt: Replace the background with a snowy mountain scene + images: + - file_id: file-abc123 + mask: + file_id: file-mask123 + output_format: png + output_compression: 100 + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ImagesResponse' + text/event-stream: + schema: + $ref: '#/components/schemas/ImageEditStreamEvent' + x-oaiMeta: + name: Create image edit + group: images + examples: + - title: Edit image + request: + curl: | + curl -s -D >(grep -i x-request-id >&2) \ + -o >(jq -r '.data[0].b64_json' | base64 --decode > gift-basket.png) \ + -X POST "https://api.openai.com/v1/images/edits" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F "model=gpt-image-1.5" \ + -F "image[]=@body-lotion.png" \ + -F "image[]=@bath-bomb.png" \ + -F "image[]=@incense-kit.png" \ + -F "image[]=@soap.png" \ + -F 'prompt=Create a lovely gift basket with these four items in it' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for image in client.images.edit( + image=b"Example data", + prompt="A cute baby sea otter wearing a beret", + ): + print(image) + javascript: | + import fs from "fs"; + import OpenAI, { toFile } from "openai"; + + const client = new OpenAI(); + + const imageFiles = [ + "bath-bomb.png", + "body-lotion.png", + "incense-kit.png", + "soap.png", + ]; + + const images = await Promise.all( + imageFiles.map(async (file) => + await toFile(fs.createReadStream(file), null, { + type: "image/png", + }) + ), + ); + + const rsp = await client.images.edit({ + model: "gpt-image-1.5", + image: images, + prompt: "Create a lovely gift basket with these four items in it", + }); + + // Save the image to a file + const image_base64 = rsp.data[0].b64_json; + const image_bytes = Buffer.from(image_base64, "base64"); + fs.writeFileSync("basket.png", image_bytes); + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const imagesResponse = await client.images.edit({ + image: fs.createReadStream('path/to/file'), + prompt: 'A cute baby sea otter wearing a beret', + }); + + console.log(imagesResponse); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\timagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{\n\t\tImage: openai.ImageEditParamsImageUnion{\n\t\t\tOfFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\t},\n\t\tPrompt: \"A cute baby sea otter wearing a beret\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", imagesResponse)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.images.ImageEditParams; + import com.openai.models.images.ImagesResponse; + import java.io.ByteArrayInputStream; + import java.io.InputStream; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ImageEditParams params = ImageEditParams.builder() + .image(new ByteArrayInputStream("Example data".getBytes())) + .prompt("A cute baby sea otter wearing a beret") + .build(); + ImagesResponse imagesResponse = client.images().edit(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + images_response = openai.images.edit(image: + StringIO.new("Example data"), prompt: "A cute baby sea otter + wearing a beret") + + + puts(images_response) + - title: Streaming + request: + curl: | + curl -s -N -X POST "https://api.openai.com/v1/images/edits" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F "model=gpt-image-1.5" \ + -F "image[]=@body-lotion.png" \ + -F "image[]=@bath-bomb.png" \ + -F "image[]=@incense-kit.png" \ + -F "image[]=@soap.png" \ + -F 'prompt=Create a lovely gift basket with these four items in it' \ + -F "stream=true" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for image in client.images.edit( + image=b"Example data", + prompt="A cute baby sea otter wearing a beret", + ): + print(image) + javascript: | + import fs from "fs"; + import OpenAI, { toFile } from "openai"; + + const client = new OpenAI(); + + const imageFiles = [ + "bath-bomb.png", + "body-lotion.png", + "incense-kit.png", + "soap.png", + ]; + + const images = await Promise.all( + imageFiles.map(async (file) => + await toFile(fs.createReadStream(file), null, { + type: "image/png", + }) + ), + ); + + const stream = await client.images.edit({ + model: "gpt-image-1.5", + image: images, + prompt: "Create a lovely gift basket with these four items in it", + stream: true, + }); + + for await (const event of stream) { + console.log(event); + } + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const imagesResponse = await client.images.edit({ + image: fs.createReadStream('path/to/file'), + prompt: 'A cute baby sea otter wearing a beret', + }); + + console.log(imagesResponse); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\timagesResponse, err := client.Images.Edit(context.TODO(), openai.ImageEditParams{\n\t\tImage: openai.ImageEditParamsImageUnion{\n\t\t\tOfFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\t},\n\t\tPrompt: \"A cute baby sea otter wearing a beret\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", imagesResponse)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.images.ImageEditParams; + import com.openai.models.images.ImagesResponse; + import java.io.ByteArrayInputStream; + import java.io.InputStream; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ImageEditParams params = ImageEditParams.builder() + .image(new ByteArrayInputStream("Example data".getBytes())) + .prompt("A cute baby sea otter wearing a beret") + .build(); + ImagesResponse imagesResponse = client.images().edit(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + images_response = openai.images.edit(image: + StringIO.new("Example data"), prompt: "A cute baby sea otter + wearing a beret") + + + puts(images_response) + response: > + event: image_edit.partial_image + + data: + {"type":"image_edit.partial_image","b64_json":"...","partial_image_index":0} + + + event: image_edit.completed + + data: + {"type":"image_edit.completed","b64_json":"...","usage":{"total_tokens":100,"input_tokens":50,"output_tokens":50,"input_tokens_details":{"text_tokens":10,"image_tokens":40}}} + /images/generations: + post: + operationId: createImage + tags: + - Images + summary: | + Creates an image given a prompt. [Learn more](/docs/guides/images). + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateImageRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ImagesResponse' + text/event-stream: + schema: + $ref: '#/components/schemas/ImageGenStreamEvent' + x-oaiMeta: + name: Create image + group: images + examples: + - title: Generate image + request: + curl: | + curl https://api.openai.com/v1/images/generations \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-image-1.5", + "prompt": "A cute baby sea otter", + "n": 1, + "size": "1024x1024" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for image in client.images.generate( + prompt="A cute baby sea otter", + ): + print(image) + javascript: | + import OpenAI from "openai"; + import { writeFile } from "fs/promises"; + + const client = new OpenAI(); + + const img = await client.images.generate({ + model: "gpt-image-1.5", + prompt: "A cute baby sea otter", + n: 1, + size: "1024x1024" + }); + + const imageBuffer = Buffer.from(img.data[0].b64_json, "base64"); + await writeFile("output.png", imageBuffer); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const imagesResponse = await client.images.generate({ prompt: 'A + cute baby sea otter' }); + + + console.log(imagesResponse); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\timagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{\n\t\tPrompt: \"A cute baby sea otter\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", imagesResponse)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.images.ImageGenerateParams; + import com.openai.models.images.ImagesResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ImageGenerateParams params = ImageGenerateParams.builder() + .prompt("A cute baby sea otter") + .build(); + ImagesResponse imagesResponse = client.images().generate(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + images_response = openai.images.generate(prompt: "A cute baby + sea otter") + + + puts(images_response) + response: | + { + "created": 1713833628, + "data": [ + { + "b64_json": "..." + } + ], + "usage": { + "total_tokens": 100, + "input_tokens": 50, + "output_tokens": 50, + "input_tokens_details": { + "text_tokens": 10, + "image_tokens": 40 + } + } + } + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/images/generations \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-image-1.5", + "prompt": "A cute baby sea otter", + "n": 1, + "size": "1024x1024", + "stream": true + }' \ + --no-buffer + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for image in client.images.generate( + prompt="A cute baby sea otter", + ): + print(image) + javascript: | + import OpenAI from "openai"; + + const client = new OpenAI(); + + const stream = await client.images.generate({ + model: "gpt-image-1.5", + prompt: "A cute baby sea otter", + n: 1, + size: "1024x1024", + stream: true, + }); + + for await (const event of stream) { + console.log(event); + } + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const imagesResponse = await client.images.generate({ prompt: 'A + cute baby sea otter' }); + + + console.log(imagesResponse); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\timagesResponse, err := client.Images.Generate(context.TODO(), openai.ImageGenerateParams{\n\t\tPrompt: \"A cute baby sea otter\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", imagesResponse)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.images.ImageGenerateParams; + import com.openai.models.images.ImagesResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ImageGenerateParams params = ImageGenerateParams.builder() + .prompt("A cute baby sea otter") + .build(); + ImagesResponse imagesResponse = client.images().generate(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + images_response = openai.images.generate(prompt: "A cute baby + sea otter") + + + puts(images_response) + response: > + event: image_generation.partial_image + + data: + {"type":"image_generation.partial_image","b64_json":"...","partial_image_index":0} + + + event: image_generation.completed + + data: + {"type":"image_generation.completed","b64_json":"...","usage":{"total_tokens":100,"input_tokens":50,"output_tokens":50,"input_tokens_details":{"text_tokens":10,"image_tokens":40}}} + /images/variations: + post: + operationId: createImageVariation + tags: + - Images + summary: >- + Creates a variation of a given image. This endpoint only supports + `dall-e-2`. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateImageVariationRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ImagesResponse' + x-oaiMeta: + name: Create image variation + group: images + examples: + request: + curl: | + curl https://api.openai.com/v1/images/variations \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F image="@otter.png" \ + -F n=2 \ + -F size="1024x1024" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + images_response = client.images.create_variation( + image=b"Example data", + ) + print(images_response.created) + javascript: |- + import fs from "fs"; + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const image = await openai.images.createVariation({ + image: fs.createReadStream("otter.png"), + }); + + console.log(image.data); + } + main(); + csharp: > + using System; + + + using OpenAI.Images; + + + ImageClient client = new( + model: "dall-e-2", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + GeneratedImage image = + client.GenerateImageVariation(imageFilePath: "otter.png"); + + + Console.WriteLine(image.ImageUri); + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const imagesResponse = await client.images.createVariation({ + image: fs.createReadStream('otter.png'), + }); + + console.log(imagesResponse.created); + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\timagesResponse, err := client.Images.NewVariation(context.TODO(), openai.ImageNewVariationParams{\n\t\tImage: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", imagesResponse.Created)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.images.ImageCreateVariationParams; + import com.openai.models.images.ImagesResponse; + import java.io.ByteArrayInputStream; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ImageCreateVariationParams params = ImageCreateVariationParams.builder() + .image(new ByteArrayInputStream("Example data".getBytes())) + .build(); + ImagesResponse imagesResponse = client.images().createVariation(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + images_response = openai.images.create_variation(image: + StringIO.new("Example data")) + + + puts(images_response) + response: | + { + "created": 1589478378, + "data": [ + { + "url": "https://..." + }, + { + "url": "https://..." + } + ] + } + /models: + get: + operationId: listModels + tags: + - Models + summary: >- + Lists the currently available models, and provides basic information + about each one such as the owner and availability. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListModelsResponse' + x-oaiMeta: + name: List models + group: models + examples: + request: + curl: | + curl https://api.openai.com/v1/models \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.models.list() + page = page.data[0] + print(page.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const list = await openai.models.list(); + + for await (const model of list) { + console.log(model); + } + } + main(); + csharp: | + using System; + + using OpenAI.Models; + + OpenAIModelClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + foreach (var model in client.GetModels().Value) + { + Console.WriteLine(model.Id); + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + // Automatically fetches more pages as needed. + for await (const model of client.models.list()) { + console.log(model.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Models.List(context.TODO())\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.models.ModelListPage; + import com.openai.models.models.ModelListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ModelListPage page = client.models().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.models.list + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "model-id-0", + "object": "model", + "created": 1686935002, + "owned_by": "organization-owner" + }, + { + "id": "model-id-1", + "object": "model", + "created": 1686935002, + "owned_by": "organization-owner", + }, + { + "id": "model-id-2", + "object": "model", + "created": 1686935002, + "owned_by": "openai" + }, + ] + } + /models/{model}: + get: + operationId: retrieveModel + tags: + - Models + summary: >- + Retrieves a model instance, providing basic information about the model + such as the owner and permissioning. + parameters: + - in: path + name: model + required: true + schema: + type: string + example: gpt-4o-mini + description: The ID of the model to use for this request + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Model' + x-oaiMeta: + name: Retrieve model + group: models + examples: + request: + curl: | + curl https://api.openai.com/v1/models/VAR_chat_model_id \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + model = client.models.retrieve( + "gpt-4o-mini", + ) + print(model.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const model = await openai.models.retrieve("VAR_chat_model_id"); + + console.log(model); + } + + main(); + csharp: | + using System; + using System.ClientModel; + + using OpenAI.Models; + + OpenAIModelClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + ClientResult model = client.GetModel("babbage-002"); + Console.WriteLine(model.Value.Id); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const model = await client.models.retrieve('gpt-4o-mini'); + + console.log(model.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tmodel, err := client.Models.Get(context.TODO(), \"gpt-4o-mini\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", model.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.models.Model; + import com.openai.models.models.ModelRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Model model = client.models().retrieve("gpt-4o-mini"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + model = openai.models.retrieve("gpt-4o-mini") + + puts(model) + response: | + { + "id": "VAR_chat_model_id", + "object": "model", + "created": 1686935002, + "owned_by": "openai" + } + delete: + operationId: deleteModel + tags: + - Models + summary: >- + Delete a fine-tuned model. You must have the Owner role in your + organization to delete a model. + parameters: + - in: path + name: model + required: true + schema: + type: string + example: ft:gpt-4o-mini:acemeco:suffix:abc123 + description: The model to delete + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteModelResponse' + x-oaiMeta: + name: Delete a fine-tuned model + group: models + examples: + request: + curl: > + curl + https://api.openai.com/v1/models/ft:gpt-4o-mini:acemeco:suffix:abc123 + \ + -X DELETE \ + -H "Authorization: Bearer $OPENAI_API_KEY" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + model_deleted = client.models.delete( + "ft:gpt-4o-mini:acemeco:suffix:abc123", + ) + print(model_deleted.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const model = await openai.models.delete("ft:gpt-4o-mini:acemeco:suffix:abc123"); + + console.log(model); + } + main(); + csharp: > + using System; + + using System.ClientModel; + + + using OpenAI.Models; + + + OpenAIModelClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + ClientResult success = + client.DeleteModel("ft:gpt-4o-mini:acemeco:suffix:abc123"); + + Console.WriteLine(success); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const modelDeleted = await + client.models.delete('ft:gpt-4o-mini:acemeco:suffix:abc123'); + + + console.log(modelDeleted.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tmodelDeleted, err := client.Models.Delete(context.TODO(), \"ft:gpt-4o-mini:acemeco:suffix:abc123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", modelDeleted.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.models.ModelDeleteParams; + import com.openai.models.models.ModelDeleted; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ModelDeleted modelDeleted = client.models().delete("ft:gpt-4o-mini:acemeco:suffix:abc123"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + model_deleted = + openai.models.delete("ft:gpt-4o-mini:acemeco:suffix:abc123") + + + puts(model_deleted) + response: | + { + "id": "ft:gpt-4o-mini:acemeco:suffix:abc123", + "object": "model", + "deleted": true + } + /moderations: + post: + operationId: createModeration + tags: + - Moderations + summary: | + Classifies if text and/or image inputs are potentially harmful. Learn + more in the [moderation guide](/docs/guides/moderation). + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateModerationRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/CreateModerationResponse' + x-oaiMeta: + name: Create moderation + group: moderations + examples: + - title: Single string + request: + curl: | + curl https://api.openai.com/v1/moderations \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "input": "I want to kill them." + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + moderation = client.moderations.create( + input="I want to kill them.", + ) + print(moderation.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const moderation = await openai.moderations.create({ input: "I want to kill them." }); + + console.log(moderation); + } + main(); + csharp: > + using System; + + using System.ClientModel; + + + using OpenAI.Moderations; + + + ModerationClient client = new( + model: "omni-moderation-latest", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + ClientResult moderation = + client.ClassifyText("I want to kill them."); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const moderation = await client.moderations.create({ input: 'I + want to kill them.' }); + + + console.log(moderation.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tmoderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{\n\t\tInput: openai.ModerationNewParamsInputUnion{\n\t\t\tOfString: openai.String(\"I want to kill them.\"),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", moderation.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.moderations.ModerationCreateParams; + import com.openai.models.moderations.ModerationCreateResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ModerationCreateParams params = ModerationCreateParams.builder() + .input("I want to kill them.") + .build(); + ModerationCreateResponse moderation = client.moderations().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + moderation = openai.moderations.create(input: "I want to kill + them.") + + + puts(moderation) + response: | + { + "id": "modr-AB8CjOTu2jiq12hp1AQPfeqFWaORR", + "model": "text-moderation-007", + "results": [ + { + "flagged": true, + "categories": { + "sexual": false, + "hate": false, + "harassment": true, + "self-harm": false, + "sexual/minors": false, + "hate/threatening": false, + "violence/graphic": false, + "self-harm/intent": false, + "self-harm/instructions": false, + "harassment/threatening": true, + "violence": true + }, + "category_scores": { + "sexual": 0.000011726012417057063, + "hate": 0.22706663608551025, + "harassment": 0.5215635299682617, + "self-harm": 2.227119921371923e-6, + "sexual/minors": 7.107352217872176e-8, + "hate/threatening": 0.023547329008579254, + "violence/graphic": 0.00003391829886822961, + "self-harm/intent": 1.646940972932498e-6, + "self-harm/instructions": 1.1198755256458526e-9, + "harassment/threatening": 0.5694745779037476, + "violence": 0.9971134662628174 + } + } + ] + } + - title: Image and text + request: + curl: | + curl https://api.openai.com/v1/moderations \ + -X POST \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "omni-moderation-latest", + "input": [ + { "type": "text", "text": "...text to classify goes here..." }, + { + "type": "image_url", + "image_url": { + "url": "https://example.com/image.png" + } + } + ] + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + moderation = client.moderations.create( + input="I want to kill them.", + ) + print(moderation.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + const moderation = await openai.moderations.create({ + model: "omni-moderation-latest", + input: [ + { type: "text", text: "...text to classify goes here..." }, + { + type: "image_url", + image_url: { + url: "https://example.com/image.png" + // can also use base64 encoded image URLs + // url: "data:image/jpeg;base64,abcdefg..." + } + } + ], + }); + + console.log(moderation); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const moderation = await client.moderations.create({ input: 'I + want to kill them.' }); + + + console.log(moderation.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tmoderation, err := client.Moderations.New(context.TODO(), openai.ModerationNewParams{\n\t\tInput: openai.ModerationNewParamsInputUnion{\n\t\t\tOfString: openai.String(\"I want to kill them.\"),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", moderation.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.moderations.ModerationCreateParams; + import com.openai.models.moderations.ModerationCreateResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ModerationCreateParams params = ModerationCreateParams.builder() + .input("I want to kill them.") + .build(); + ModerationCreateResponse moderation = client.moderations().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + moderation = openai.moderations.create(input: "I want to kill + them.") + + + puts(moderation) + response: | + { + "id": "modr-0d9740456c391e43c445bf0f010940c7", + "model": "omni-moderation-latest", + "results": [ + { + "flagged": true, + "categories": { + "harassment": true, + "harassment/threatening": true, + "sexual": false, + "hate": false, + "hate/threatening": false, + "illicit": false, + "illicit/violent": false, + "self-harm/intent": false, + "self-harm/instructions": false, + "self-harm": false, + "sexual/minors": false, + "violence": true, + "violence/graphic": true + }, + "category_scores": { + "harassment": 0.8189693396524255, + "harassment/threatening": 0.804985420696006, + "sexual": 1.573112165348997e-6, + "hate": 0.007562942636942845, + "hate/threatening": 0.004208854591835476, + "illicit": 0.030535955153511665, + "illicit/violent": 0.008925306722380033, + "self-harm/intent": 0.00023023930975076432, + "self-harm/instructions": 0.0002293869201073356, + "self-harm": 0.012598046106750154, + "sexual/minors": 2.212566909570261e-8, + "violence": 0.9999992735124786, + "violence/graphic": 0.843064871157054 + }, + "category_applied_input_types": { + "harassment": [ + "text" + ], + "harassment/threatening": [ + "text" + ], + "sexual": [ + "text", + "image" + ], + "hate": [ + "text" + ], + "hate/threatening": [ + "text" + ], + "illicit": [ + "text" + ], + "illicit/violent": [ + "text" + ], + "self-harm/intent": [ + "text", + "image" + ], + "self-harm/instructions": [ + "text", + "image" + ], + "self-harm": [ + "text", + "image" + ], + "sexual/minors": [ + "text" + ], + "violence": [ + "text", + "image" + ], + "violence/graphic": [ + "text", + "image" + ] + } + } + ] + } + /organization/admin_api_keys: + get: + summary: List organization API keys + operationId: admin-api-keys-list + description: Retrieve a paginated list of organization admin API keys. + parameters: + - in: query + name: after + required: false + schema: + type: string + nullable: true + description: >- + Return keys with IDs that come after this ID in the pagination + order. + - in: query + name: order + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + description: Order results by creation time, ascending or descending. + - in: query + name: limit + required: false + schema: + type: integer + default: 20 + description: Maximum number of keys to return. + responses: + '200': + description: A list of organization API keys. + content: + application/json: + schema: + $ref: '#/components/schemas/ApiKeyList' + x-oaiMeta: + name: List all organization and project API keys. + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/admin_api_keys?after=key_abc&limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "organization.admin_api_key", + "id": "key_abc", + "name": "Main Admin Key", + "redacted_value": "sk-admin...def", + "created_at": 1711471533, + "last_used_at": 1711471534, + "owner": { + "type": "service_account", + "object": "organization.service_account", + "id": "sa_456", + "name": "My Service Account", + "created_at": 1711471533, + "role": "member" + } + } + ], + "first_id": "key_abc", + "last_id": "key_abc", + "has_more": false + } + post: + summary: Create an organization admin API key + operationId: admin-api-keys-create + description: Create a new admin-level API key for the organization. + requestBody: + required: true + content: + application/json: + schema: + type: object + required: + - name + properties: + name: + type: string + example: New Admin Key + responses: + '200': + description: The newly created admin API key. + content: + application/json: + schema: + $ref: '#/components/schemas/AdminApiKey' + x-oaiMeta: + name: Create admin API key + group: administration + examples: + request: + curl: > + curl -X POST https://api.openai.com/v1/organization/admin_api_keys + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "New Admin Key" + }' + response: | + { + "object": "organization.admin_api_key", + "id": "key_xyz", + "name": "New Admin Key", + "redacted_value": "sk-admin...xyz", + "created_at": 1711471533, + "last_used_at": 1711471534, + "owner": { + "type": "user", + "object": "organization.user", + "id": "user_123", + "name": "John Doe", + "created_at": 1711471533, + "role": "owner" + }, + "value": "sk-admin-1234abcd" + } + /organization/admin_api_keys/{key_id}: + get: + summary: Retrieve a single organization API key + operationId: admin-api-keys-get + description: Get details for a specific organization API key by its ID. + parameters: + - in: path + name: key_id + required: true + schema: + type: string + description: The ID of the API key. + responses: + '200': + description: Details of the requested API key. + content: + application/json: + schema: + $ref: '#/components/schemas/AdminApiKey' + x-oaiMeta: + name: Retrieve admin API key + group: administration + examples: + request: + curl: > + curl https://api.openai.com/v1/organization/admin_api_keys/key_abc + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.admin_api_key", + "id": "key_abc", + "name": "Main Admin Key", + "redacted_value": "sk-admin...xyz", + "created_at": 1711471533, + "last_used_at": 1711471534, + "owner": { + "type": "user", + "object": "organization.user", + "id": "user_123", + "name": "John Doe", + "created_at": 1711471533, + "role": "owner" + } + } + delete: + summary: Delete an organization admin API key + operationId: admin-api-keys-delete + description: Delete the specified admin API key. + parameters: + - in: path + name: key_id + required: true + schema: + type: string + description: The ID of the API key to be deleted. + responses: + '200': + description: Confirmation that the API key was deleted. + content: + application/json: + schema: + type: object + properties: + id: + type: string + example: key_abc + object: + type: string + example: organization.admin_api_key.deleted + deleted: + type: boolean + example: true + x-oaiMeta: + name: Delete admin API key + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/admin_api_keys/key_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "id": "key_abc", + "object": "organization.admin_api_key.deleted", + "deleted": true + } + /organization/audit_logs: + get: + summary: List user actions and configuration changes within this organization. + operationId: list-audit-logs + tags: + - Audit Logs + parameters: + - name: effective_at + in: query + description: >- + Return only events whose `effective_at` (Unix seconds) is in this + range. + required: false + schema: + type: object + properties: + gt: + type: integer + description: >- + Return only events whose `effective_at` (Unix seconds) is + greater than this value. + gte: + type: integer + description: >- + Return only events whose `effective_at` (Unix seconds) is + greater than or equal to this value. + lt: + type: integer + description: >- + Return only events whose `effective_at` (Unix seconds) is less + than this value. + lte: + type: integer + description: >- + Return only events whose `effective_at` (Unix seconds) is less + than or equal to this value. + - name: project_ids[] + in: query + description: Return only events for these projects. + required: false + schema: + type: array + items: + type: string + - name: event_types[] + in: query + description: >- + Return only events with a `type` in one of these values. For + example, `project.created`. For all options, see the documentation + for the [audit log object](/docs/api-reference/audit-logs/object). + required: false + schema: + type: array + items: + $ref: '#/components/schemas/AuditLogEventType' + - name: actor_ids[] + in: query + description: >- + Return only events performed by these actors. Can be a user ID, a + service account ID, or an api key tracking ID. + required: false + schema: + type: array + items: + type: string + - name: actor_emails[] + in: query + description: Return only events performed by users with these emails. + required: false + schema: + type: array + items: + type: string + - name: resource_ids[] + in: query + description: >- + Return only events performed on these targets. For example, a + project ID updated. + required: false + schema: + type: array + items: + type: string + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: before + in: query + description: > + A cursor for use in pagination. `before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the + previous page of the list. + schema: + type: string + responses: + '200': + description: Audit logs listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ListAuditLogsResponse' + x-oaiMeta: + name: List audit logs + group: audit-logs + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/audit_logs \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "id": "audit_log-xxx_yyyymmdd", + "type": "project.archived", + "effective_at": 1722461446, + "actor": { + "type": "api_key", + "api_key": { + "type": "user", + "user": { + "id": "user-xxx", + "email": "user@example.com" + } + } + }, + "project.archived": { + "id": "proj_abc" + }, + }, + { + "id": "audit_log-yyy__20240101", + "type": "api_key.updated", + "effective_at": 1720804190, + "actor": { + "type": "session", + "session": { + "user": { + "id": "user-xxx", + "email": "user@example.com" + }, + "ip_address": "127.0.0.1", + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36", + "ja3": "a497151ce4338a12c4418c44d375173e", + "ja4": "q13d0313h3_55b375c5d22e_c7319ce65786", + "ip_address_details": { + "country": "US", + "city": "San Francisco", + "region": "California", + "region_code": "CA", + "asn": "1234", + "latitude": "37.77490", + "longitude": "-122.41940" + } + } + }, + "api_key.updated": { + "id": "key_xxxx", + "data": { + "scopes": ["resource_2.operation_2"] + } + }, + } + ], + "first_id": "audit_log-xxx__20240101", + "last_id": "audit_log_yyy__20240101", + "has_more": true + } + /organization/certificates: + get: + summary: List uploaded certificates for this organization. + operationId: listOrganizationCertificates + tags: + - Certificates + parameters: + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + required: false + schema: + type: string + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + responses: + '200': + description: Certificates listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ListCertificatesResponse' + x-oaiMeta: + name: List organization certificates + group: administration + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/certificates \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" + response: | + { + "object": "list", + "data": [ + { + "object": "organization.certificate", + "id": "cert_abc", + "name": "My Example Certificate", + "active": true, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + ], + "first_id": "cert_abc", + "last_id": "cert_abc", + "has_more": false + } + post: + summary: > + Upload a certificate to the organization. This does **not** + automatically activate the certificate. + + + Organizations can upload up to 50 certificates. + operationId: uploadCertificate + tags: + - Certificates + requestBody: + description: The certificate upload payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UploadCertificateRequest' + responses: + '200': + description: Certificate uploaded successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Certificate' + x-oaiMeta: + name: Upload certificate + group: administration + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/certificates \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "My Example Certificate", + "certificate": "-----BEGIN CERTIFICATE-----\\nMIIDeT...\\n-----END CERTIFICATE-----" + }' + response: | + { + "object": "certificate", + "id": "cert_abc", + "name": "My Example Certificate", + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + } + /organization/certificates/activate: + post: + summary: > + Activate certificates at the organization level. + + + You can atomically and idempotently activate up to 10 certificates at a + time. + operationId: activateOrganizationCertificates + tags: + - Certificates + requestBody: + description: The certificate activation payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ToggleCertificatesRequest' + responses: + '200': + description: Certificates activated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ListCertificatesResponse' + x-oaiMeta: + name: Activate certificates for organization + group: administration + examples: + request: + curl: > + curl https://api.openai.com/v1/organization/certificates/activate + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" \ + + -d '{ + "data": ["cert_abc", "cert_def"] + }' + response: | + { + "object": "organization.certificate.activation", + "data": [ + { + "object": "organization.certificate", + "id": "cert_abc", + "name": "My Example Certificate", + "active": true, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + { + "object": "organization.certificate", + "id": "cert_def", + "name": "My Example Certificate 2", + "active": true, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + ], + } + /organization/certificates/deactivate: + post: + summary: > + Deactivate certificates at the organization level. + + + You can atomically and idempotently deactivate up to 10 certificates at + a time. + operationId: deactivateOrganizationCertificates + tags: + - Certificates + requestBody: + description: The certificate deactivation payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ToggleCertificatesRequest' + responses: + '200': + description: Certificates deactivated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ListCertificatesResponse' + x-oaiMeta: + name: Deactivate certificates for organization + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/certificates/deactivate \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" \ + + -d '{ + "data": ["cert_abc", "cert_def"] + }' + response: | + { + "object": "organization.certificate.deactivation", + "data": [ + { + "object": "organization.certificate", + "id": "cert_abc", + "name": "My Example Certificate", + "active": false, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + { + "object": "organization.certificate", + "id": "cert_def", + "name": "My Example Certificate 2", + "active": false, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + ], + } + /organization/certificates/{certificate_id}: + get: + summary: | + Get a certificate that has been uploaded to the organization. + + You can get a certificate regardless of whether it is active or not. + operationId: getCertificate + tags: + - Certificates + parameters: + - name: certificate_id + in: path + description: Unique ID of the certificate to retrieve. + required: true + schema: + type: string + - name: include + in: query + description: >- + A list of additional fields to include in the response. Currently + the only supported value is `content` to fetch the PEM content of + the certificate. + required: false + schema: + type: array + items: + type: string + enum: + - content + responses: + '200': + description: Certificate retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Certificate' + x-oaiMeta: + name: Get certificate + group: administration + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/certificates/cert_abc?include[]=content" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" + response: | + { + "object": "certificate", + "id": "cert_abc", + "name": "My Example Certificate", + "created_at": 1234567, + "certificate_details": { + "valid_at": 1234567, + "expires_at": 12345678, + "content": "-----BEGIN CERTIFICATE-----MIIDeT...-----END CERTIFICATE-----" + } + } + post: + summary: | + Modify a certificate. Note that only the name can be modified. + operationId: modifyCertificate + tags: + - Certificates + parameters: + - name: certificate_id + in: path + description: Unique ID of the certificate to modify. + required: true + schema: + type: string + requestBody: + description: The certificate modification payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ModifyCertificateRequest' + responses: + '200': + description: Certificate modified successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Certificate' + x-oaiMeta: + name: Modify certificate + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/certificates/cert_abc \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" \ + + -d '{ + "name": "Renamed Certificate" + }' + response: | + { + "object": "certificate", + "id": "cert_abc", + "name": "Renamed Certificate", + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + } + delete: + summary: | + Delete a certificate from the organization. + + The certificate must be inactive for the organization and all projects. + operationId: deleteCertificate + tags: + - Certificates + parameters: + - name: certificate_id + in: path + description: Unique ID of the certificate to delete. + required: true + schema: + type: string + responses: + '200': + description: Certificate deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteCertificateResponse' + x-oaiMeta: + name: Delete certificate + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/certificates/cert_abc \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" + response: | + { + "object": "certificate.deleted", + "id": "cert_abc" + } + /organization/costs: + get: + summary: Get costs details for the organization. + operationId: usage-costs + tags: + - Usage + parameters: + - name: start_time + in: query + description: Start time (Unix seconds) of the query time range, inclusive. + required: true + schema: + type: integer + - name: end_time + in: query + description: End time (Unix seconds) of the query time range, exclusive. + required: false + schema: + type: integer + - name: bucket_width + in: query + description: >- + Width of each time bucket in response. Currently only `1d` is + supported, default to `1d`. + required: false + schema: + type: string + enum: + - 1d + default: 1d + - name: project_ids + in: query + description: Return only costs for these projects. + required: false + schema: + type: array + items: + type: string + - name: group_by + in: query + description: >- + Group the costs by the specified fields. Support fields include + `project_id`, `line_item` and any combination of them. + required: false + schema: + type: array + items: + type: string + enum: + - project_id + - line_item + - name: limit + in: query + description: > + A limit on the number of buckets to be returned. Limit can range + between 1 and 180, and the default is 7. + required: false + schema: + type: integer + default: 7 + - name: page + in: query + description: >- + A cursor for use in pagination. Corresponding to the `next_page` + field from the previous response. + schema: + type: string + responses: + '200': + description: Costs data retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageResponse' + x-oaiMeta: + name: Costs + group: usage-costs + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/costs?start_time=1730419200&limit=1" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" + response: | + { + "object": "page", + "data": [ + { + "object": "bucket", + "start_time": 1730419200, + "end_time": 1730505600, + "results": [ + { + "object": "organization.costs.result", + "amount": { + "value": 0.06, + "currency": "usd" + }, + "line_item": null, + "project_id": null + } + ] + } + ], + "has_more": false, + "next_page": null + } + /organization/groups: + get: + summary: Lists all groups in the organization. + operationId: list-groups + tags: + - Groups + parameters: + - name: limit + in: query + description: > + A limit on the number of groups to be returned. Limit can range + between 0 and 1000, and the default is 100. + required: false + schema: + type: integer + minimum: 0 + maximum: 1000 + default: 100 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is a group ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with group_abc, your subsequent call can + include `after=group_abc` in order to fetch the next page of the + list. + required: false + schema: + type: string + - name: order + in: query + description: Specifies the sort order of the returned groups. + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + responses: + '200': + description: Groups listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupListResource' + x-oaiMeta: + name: List groups + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/groups?limit=20&order=asc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "group", + "id": "group_01J1F8ABCDXYZ", + "name": "Support Team", + "created_at": 1711471533, + "is_scim_managed": false + } + ], + "has_more": false, + "next": null + } + post: + summary: Creates a new group in the organization. + operationId: create-group + tags: + - Groups + requestBody: + description: Parameters for the group you want to create. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateGroupBody' + responses: + '200': + description: Group created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupResponse' + x-oaiMeta: + name: Create group + group: administration + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/groups \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Support Team" + }' + response: | + { + "object": "group", + "id": "group_01J1F8ABCDXYZ", + "name": "Support Team", + "created_at": 1711471533, + "is_scim_managed": false + } + /organization/groups/{group_id}: + post: + summary: Updates a group's information. + operationId: update-group + tags: + - Groups + parameters: + - name: group_id + in: path + description: The ID of the group to update. + required: true + schema: + type: string + requestBody: + description: New attributes to set on the group. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateGroupBody' + responses: + '200': + description: Group updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupResourceWithSuccess' + x-oaiMeta: + name: Update group + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Escalations" + }' + response: | + { + "id": "group_01J1F8ABCDXYZ", + "name": "Escalations", + "created_at": 1711471533, + "is_scim_managed": false + } + delete: + summary: Deletes a group from the organization. + operationId: delete-group + tags: + - Groups + parameters: + - name: group_id + in: path + description: The ID of the group to delete. + required: true + schema: + type: string + responses: + '200': + description: Group deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupDeletedResource' + x-oaiMeta: + name: Delete group + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "group.deleted", + "id": "group_01J1F8ABCDXYZ", + "deleted": true + } + /organization/groups/{group_id}/roles: + get: + summary: >- + Lists the organization roles assigned to a group within the + organization. + operationId: list-group-role-assignments + tags: + - Group organization role assignments + parameters: + - name: group_id + in: path + description: >- + The ID of the group whose organization role assignments you want to + list. + required: true + schema: + type: string + - name: limit + in: query + description: A limit on the number of organization role assignments to return. + required: false + schema: + type: integer + minimum: 0 + maximum: 1000 + - name: after + in: query + description: >- + Cursor for pagination. Provide the value from the previous + response's `next` field to continue listing organization roles. + required: false + schema: + type: string + - name: order + in: query + description: Sort order for the returned organization roles. + required: false + schema: + type: string + enum: + - asc + - desc + responses: + '200': + description: Group organization role assignments listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleListResource' + x-oaiMeta: + name: List group organization role assignments + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/roles + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false, + "description": "Allows managing organization groups", + "created_at": 1711471533, + "updated_at": 1711472599, + "created_by": "user_abc123", + "created_by_user_obj": { + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com" + }, + "metadata": {} + } + ], + "has_more": false, + "next": null + } + post: + summary: Assigns an organization role to a group within the organization. + operationId: assign-group-role + tags: + - Group organization role assignments + parameters: + - name: group_id + in: path + description: The ID of the group that should receive the organization role. + required: true + schema: + type: string + requestBody: + description: Identifies the organization role to assign to the group. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicAssignOrganizationGroupRoleBody' + responses: + '200': + description: Organization role assigned to the group successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupRoleAssignment' + x-oaiMeta: + name: Assign organization role to group + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/roles + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role_id": "role_01J1F8ROLE01" + }' + response: | + { + "object": "group.role", + "group": { + "object": "group", + "id": "group_01J1F8ABCDXYZ", + "name": "Support Team", + "created_at": 1711471533, + "scim_managed": false + }, + "role": { + "object": "role", + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "description": "Allows managing organization groups", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false + } + } + /organization/groups/{group_id}/roles/{role_id}: + delete: + summary: Unassigns an organization role from a group within the organization. + operationId: unassign-group-role + tags: + - Group organization role assignments + parameters: + - name: group_id + in: path + description: The ID of the group to modify. + required: true + schema: + type: string + - name: role_id + in: path + description: The ID of the organization role to remove from the group. + required: true + schema: + type: string + responses: + '200': + description: Organization role unassigned from the group successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/DeletedRoleAssignmentResource' + x-oaiMeta: + name: Unassign organization role from group + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/roles/role_01J1F8ROLE01 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "group.role.deleted", + "deleted": true + } + /organization/groups/{group_id}/users: + get: + summary: Lists the users assigned to a group. + operationId: list-group-users + tags: + - Group users + parameters: + - name: group_id + in: path + description: The ID of the group to inspect. + required: true + schema: + type: string + - name: limit + in: query + description: > + A limit on the number of users to be returned. Limit can range + between 0 and 1000, and the default is 100. + required: false + schema: + type: integer + minimum: 0 + maximum: 1000 + default: 100 + - name: after + in: query + description: > + A cursor for use in pagination. Provide the ID of the last user from + the previous list response to retrieve the next page. + required: false + schema: + type: string + - name: order + in: query + description: Specifies the sort order of users in the list. + required: false + schema: + type: string + enum: + - asc + - desc + default: desc + responses: + '200': + description: Group users listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UserListResource' + x-oaiMeta: + name: List group users + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/users?limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "organization.user", + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com", + "role": "owner", + "added_at": 1711471533 + } + ], + "has_more": false, + "next": null + } + post: + summary: Adds a user to a group. + operationId: add-group-user + tags: + - Group users + parameters: + - name: group_id + in: path + description: The ID of the group to update. + required: true + schema: + type: string + requestBody: + description: Identifies the user that should be added to the group. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateGroupUserBody' + responses: + '200': + description: User added to the group successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupUserAssignment' + x-oaiMeta: + name: Add group user + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/users + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "user_id": "user_abc123" + }' + response: | + { + "object": "group.user", + "user_id": "user_abc123", + "group_id": "group_01J1F8ABCDXYZ" + } + /organization/groups/{group_id}/users/{user_id}: + delete: + summary: Removes a user from a group. + operationId: remove-group-user + tags: + - Group users + parameters: + - name: group_id + in: path + description: The ID of the group to update. + required: true + schema: + type: string + - name: user_id + in: path + description: The ID of the user to remove from the group. + required: true + schema: + type: string + responses: + '200': + description: User removed from the group successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupUserDeletedResource' + x-oaiMeta: + name: Remove group user + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/groups/group_01J1F8ABCDXYZ/users/user_abc123 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "group.user.deleted", + "deleted": true + } + /organization/invites: + get: + summary: Returns a list of invites in the organization. + operationId: list-invites + tags: + - Invites + parameters: + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + required: false + schema: + type: string + responses: + '200': + description: Invites listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/InviteListResponse' + x-oaiMeta: + name: List invites + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/invites?after=invite-abc&limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "status": "accepted", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": 1711471533 + } + ], + "first_id": "invite-abc", + "last_id": "invite-abc", + "has_more": false + } + post: + summary: >- + Create an invite for a user to the organization. The invite must be + accepted by the user before they have access to the organization. + operationId: inviteUser + tags: + - Invites + requestBody: + description: The invite request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InviteRequest' + responses: + '200': + description: User invited successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Invite' + x-oaiMeta: + name: Create invite + group: administration + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/invites \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "email": "anotheruser@example.com", + "role": "reader", + "projects": [ + { + "id": "project-xyz", + "role": "member" + }, + { + "id": "project-abc", + "role": "owner" + } + ] + }' + response: | + { + "object": "organization.invite", + "id": "invite-def", + "email": "anotheruser@example.com", + "role": "reader", + "status": "pending", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": null, + "projects": [ + { + "id": "project-xyz", + "role": "member" + }, + { + "id": "project-abc", + "role": "owner" + } + ] + } + /organization/invites/{invite_id}: + get: + summary: Retrieves an invite. + operationId: retrieve-invite + tags: + - Invites + parameters: + - in: path + name: invite_id + required: true + schema: + type: string + description: The ID of the invite to retrieve. + responses: + '200': + description: Invite retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Invite' + x-oaiMeta: + name: Retrieve invite + group: administration + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/invites/invite-abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "status": "accepted", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": 1711471533 + } + delete: + summary: >- + Delete an invite. If the invite has already been accepted, it cannot be + deleted. + operationId: delete-invite + tags: + - Invites + parameters: + - in: path + name: invite_id + required: true + schema: + type: string + description: The ID of the invite to delete. + responses: + '200': + description: Invite deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/InviteDeleteResponse' + x-oaiMeta: + name: Delete invite + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/invites/invite-abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.invite.deleted", + "id": "invite-abc", + "deleted": true + } + /organization/projects: + get: + summary: Returns a list of projects. + operationId: list-projects + tags: + - Projects + parameters: + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + required: false + schema: + type: string + - name: include_archived + in: query + schema: + type: boolean + default: false + description: >- + If `true` returns all projects including those that have been + `archived`. Archived projects are not included by default. + responses: + '200': + description: Projects listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectListResponse' + x-oaiMeta: + name: List projects + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects?after=proj_abc&limit=20&include_archived=false + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project example", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } + ], + "first_id": "proj-abc", + "last_id": "proj-xyz", + "has_more": false + } + post: + summary: >- + Create a new project in the organization. Projects can be created and + archived, but cannot be deleted. + operationId: create-project + tags: + - Projects + requestBody: + description: The project create request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectCreateRequest' + responses: + '200': + description: Project created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Project' + x-oaiMeta: + name: Create project + group: administration + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/projects \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Project ABC" + }' + response: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project ABC", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } + /organization/projects/{project_id}: + get: + summary: Retrieves a project. + operationId: retrieve-project + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + responses: + '200': + description: Project retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Project' + x-oaiMeta: + name: Retrieve project + group: administration + description: Retrieve a project. + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/projects/proj_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project example", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } + post: + summary: Modifies a project in the organization. + operationId: modify-project + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + requestBody: + description: The project update request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUpdateRequest' + responses: + '200': + description: Project updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Project' + '400': + description: Error response when updating the default project. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Modify project + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/projects/proj_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Project DEF" + }' + response: '' + /organization/projects/{project_id}/api_keys: + get: + summary: Returns a list of API keys in the project. + operationId: list-project-api-keys + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + required: false + schema: + type: string + responses: + '200': + description: Project API keys listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectApiKeyListResponse' + x-oaiMeta: + name: List project API keys + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/api_keys?after=key_abc&limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "organization.project.api_key", + "redacted_value": "sk-abc...def", + "name": "My API Key", + "created_at": 1711471533, + "last_used_at": 1711471534, + "id": "key_abc", + "owner": { + "type": "user", + "user": { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + } + } + ], + "first_id": "key_abc", + "last_id": "key_xyz", + "has_more": false + } + /organization/projects/{project_id}/api_keys/{key_id}: + get: + summary: Retrieves an API key in the project. + operationId: retrieve-project-api-key + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: key_id + in: path + description: The ID of the API key. + required: true + schema: + type: string + responses: + '200': + description: Project API key retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectApiKey' + x-oaiMeta: + name: Retrieve project API key + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.project.api_key", + "redacted_value": "sk-abc...def", + "name": "My API Key", + "created_at": 1711471533, + "last_used_at": 1711471534, + "id": "key_abc", + "owner": { + "type": "user", + "user": { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + } + } + delete: + summary: > + Deletes an API key from the project. + + + Returns confirmation of the key deletion, or an error if the key + belonged to + + a service account. + operationId: delete-project-api-key + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: key_id + in: path + description: The ID of the API key. + required: true + schema: + type: string + responses: + '200': + description: Project API key deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectApiKeyDeleteResponse' + '400': + description: Error response for various conditions. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Delete project API key + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/projects/proj_abc/api_keys/key_abc + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.project.api_key.deleted", + "id": "key_abc", + "deleted": true + } + /organization/projects/{project_id}/archive: + post: + summary: >- + Archives a project in the organization. Archived projects cannot be used + or updated. + operationId: archive-project + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + responses: + '200': + description: Project archived successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Project' + x-oaiMeta: + name: Archive project + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/projects/proj_abc/archive \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project DEF", + "created_at": 1711471533, + "archived_at": 1711471533, + "status": "archived" + } + /organization/projects/{project_id}/certificates: + get: + summary: List certificates for this project. + operationId: listProjectCertificates + tags: + - Certificates + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + required: false + schema: + type: string + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + responses: + '200': + description: Certificates listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ListCertificatesResponse' + x-oaiMeta: + name: List project certificates + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/certificates + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" + response: | + { + "object": "list", + "data": [ + { + "object": "organization.project.certificate", + "id": "cert_abc", + "name": "My Example Certificate", + "active": true, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + ], + "first_id": "cert_abc", + "last_id": "cert_abc", + "has_more": false + } + /organization/projects/{project_id}/certificates/activate: + post: + summary: > + Activate certificates at the project level. + + + You can atomically and idempotently activate up to 10 certificates at a + time. + operationId: activateProjectCertificates + tags: + - Certificates + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + requestBody: + description: The certificate activation payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ToggleCertificatesRequest' + responses: + '200': + description: Certificates activated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ListCertificatesResponse' + x-oaiMeta: + name: Activate certificates for project + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/certificates/activate + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" \ + + -d '{ + "data": ["cert_abc", "cert_def"] + }' + response: | + { + "object": "organization.project.certificate.activation", + "data": [ + { + "object": "organization.project.certificate", + "id": "cert_abc", + "name": "My Example Certificate", + "active": true, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + { + "object": "organization.project.certificate", + "id": "cert_def", + "name": "My Example Certificate 2", + "active": true, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + ], + } + /organization/projects/{project_id}/certificates/deactivate: + post: + summary: | + Deactivate certificates at the project level. You can atomically and + idempotently deactivate up to 10 certificates at a time. + operationId: deactivateProjectCertificates + tags: + - Certificates + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + requestBody: + description: The certificate deactivation payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ToggleCertificatesRequest' + responses: + '200': + description: Certificates deactivated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ListCertificatesResponse' + x-oaiMeta: + name: Deactivate certificates for project + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/certificates/deactivate + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" \ + + -d '{ + "data": ["cert_abc", "cert_def"] + }' + response: | + { + "object": "organization.project.certificate.deactivation", + "data": [ + { + "object": "organization.project.certificate", + "id": "cert_abc", + "name": "My Example Certificate", + "active": false, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + { + "object": "organization.project.certificate", + "id": "cert_def", + "name": "My Example Certificate 2", + "active": false, + "created_at": 1234567, + "certificate_details": { + "valid_at": 12345667, + "expires_at": 12345678 + } + }, + ], + } + /organization/projects/{project_id}/groups: + get: + summary: Lists the groups that have access to a project. + operationId: list-project-groups + tags: + - Project groups + parameters: + - name: project_id + in: path + description: The ID of the project to inspect. + required: true + schema: + type: string + - name: limit + in: query + description: A limit on the number of project groups to return. Defaults to 20. + required: false + schema: + type: integer + minimum: 0 + maximum: 100 + default: 20 + - name: after + in: query + description: >- + Cursor for pagination. Provide the ID of the last group from the + previous response to fetch the next page. + required: false + schema: + type: string + - name: order + in: query + description: Sort order for the returned groups. + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + responses: + '200': + description: Project groups listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectGroupListResource' + x-oaiMeta: + name: List project groups + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc123/groups?limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "project.group", + "project_id": "proj_abc123", + "group_id": "group_01J1F8ABCDXYZ", + "group_name": "Support Team", + "created_at": 1711471533 + } + ], + "has_more": false, + "next": null + } + post: + summary: Grants a group access to a project. + operationId: add-project-group + tags: + - Project groups + parameters: + - name: project_id + in: path + description: The ID of the project to update. + required: true + schema: + type: string + requestBody: + description: Identifies the group and role to assign to the project. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/InviteProjectGroupBody' + responses: + '200': + description: Group granted access to the project successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectGroup' + x-oaiMeta: + name: Add project group + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/projects/proj_abc123/groups + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "group_id": "group_01J1F8ABCDXYZ", + "role": "role_01J1F8PROJ" + }' + response: | + { + "object": "project.group", + "project_id": "proj_abc123", + "group_id": "group_01J1F8ABCDXYZ", + "group_name": "Support Team", + "created_at": 1711471533 + } + /organization/projects/{project_id}/groups/{group_id}: + delete: + summary: Revokes a group's access to a project. + operationId: remove-project-group + tags: + - Project groups + parameters: + - name: project_id + in: path + description: The ID of the project to update. + required: true + schema: + type: string + - name: group_id + in: path + description: The ID of the group to remove from the project. + required: true + schema: + type: string + responses: + '200': + description: Group removed from the project successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectGroupDeletedResource' + x-oaiMeta: + name: Remove project group + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/projects/proj_abc123/groups/group_01J1F8ABCDXYZ + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "project.group.deleted", + "deleted": true + } + /organization/projects/{project_id}/rate_limits: + get: + summary: Returns the rate limits per model for a project. + operationId: list-project-rate-limits + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: limit + in: query + description: | + A limit on the number of objects to be returned. The default is 100. + required: false + schema: + type: integer + default: 100 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + required: false + schema: + type: string + - name: before + in: query + description: > + A cursor for use in pagination. `before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, beginning with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the + previous page of the list. + required: false + schema: + type: string + responses: + '200': + description: Project rate limits listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectRateLimitListResponse' + x-oaiMeta: + name: List project rate limits + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/rate_limits?after=rl_xxx&limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "project.rate_limit", + "id": "rl-ada", + "model": "ada", + "max_requests_per_1_minute": 600, + "max_tokens_per_1_minute": 150000, + "max_images_per_1_minute": 10 + } + ], + "first_id": "rl-ada", + "last_id": "rl-ada", + "has_more": false + } + error_response: | + { + "code": 404, + "message": "The project {project_id} was not found" + } + /organization/projects/{project_id}/rate_limits/{rate_limit_id}: + post: + summary: Updates a project rate limit. + operationId: update-project-rate-limits + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: rate_limit_id + in: path + description: The ID of the rate limit. + required: true + schema: + type: string + requestBody: + description: The project rate limit update request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectRateLimitUpdateRequest' + responses: + '200': + description: Project rate limit updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectRateLimit' + '400': + description: Error response for various conditions. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Modify project rate limit + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/projects/proj_abc/rate_limits/rl_xxx + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "max_requests_per_1_minute": 500 + }' + response: | + { + "object": "project.rate_limit", + "id": "rl-ada", + "model": "ada", + "max_requests_per_1_minute": 600, + "max_tokens_per_1_minute": 150000, + "max_images_per_1_minute": 10 + } + error_response: | + { + "code": 404, + "message": "The project {project_id} was not found" + } + /organization/projects/{project_id}/service_accounts: + get: + summary: Returns a list of service accounts in the project. + operationId: list-project-service-accounts + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + required: false + schema: + type: string + responses: + '200': + description: Project service accounts listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccountListResponse' + '400': + description: Error response when project is archived. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: List project service accounts + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/service_accounts?after=custom_id&limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Service Account", + "role": "owner", + "created_at": 1711471533 + } + ], + "first_id": "svc_acct_abc", + "last_id": "svc_acct_xyz", + "has_more": false + } + post: + summary: >- + Creates a new service account in the project. This also returns an + unredacted API key for the service account. + operationId: create-project-service-account + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + requestBody: + description: The project service account create request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccountCreateRequest' + responses: + '200': + description: Project service account created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccountCreateResponse' + '400': + description: Error response when project is archived. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Create project service account + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/projects/proj_abc/service_accounts + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "name": "Production App" + }' + response: | + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Production App", + "role": "member", + "created_at": 1711471533, + "api_key": { + "object": "organization.project.service_account.api_key", + "value": "sk-abcdefghijklmnop123", + "name": "Secret Key", + "created_at": 1711471533, + "id": "key_abc" + } + } + /organization/projects/{project_id}/service_accounts/{service_account_id}: + get: + summary: Retrieves a service account in the project. + operationId: retrieve-project-service-account + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: service_account_id + in: path + description: The ID of the service account. + required: true + schema: + type: string + responses: + '200': + description: Project service account retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccount' + x-oaiMeta: + name: Retrieve project service account + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Service Account", + "role": "owner", + "created_at": 1711471533 + } + delete: + summary: > + Deletes a service account from the project. + + + Returns confirmation of service account deletion, or an error if the + project + + is archived (archived projects have no service accounts). + operationId: delete-project-service-account + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: service_account_id + in: path + description: The ID of the service account. + required: true + schema: + type: string + responses: + '200': + description: Project service account deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectServiceAccountDeleteResponse' + x-oaiMeta: + name: Delete project service account + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/projects/proj_abc/service_accounts/svc_acct_abc + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.project.service_account.deleted", + "id": "svc_acct_abc", + "deleted": true + } + /organization/projects/{project_id}/users: + get: + summary: Returns a list of users in the project. + operationId: list-project-users + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + required: false + schema: + type: string + responses: + '200': + description: Project users listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUserListResponse' + '400': + description: Error response when project is archived. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: List project users + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/users?after=user_abc&limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + ], + "first_id": "user-abc", + "last_id": "user-xyz", + "has_more": false + } + post: + summary: >- + Adds a user to the project. Users must already be members of the + organization to be added to a project. + operationId: create-project-user + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + tags: + - Projects + requestBody: + description: The project user create request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUserCreateRequest' + responses: + '200': + description: User added to project successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUser' + '400': + description: Error response for various conditions. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Create project user + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/projects/proj_abc/users \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "user_id": "user_abc", + "role": "member" + }' + response: | + { + "object": "organization.project.user", + "id": "user_abc", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + /organization/projects/{project_id}/users/{user_id}: + get: + summary: Retrieves a user in the project. + operationId: retrieve-project-user + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + responses: + '200': + description: Project user retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUser' + x-oaiMeta: + name: Retrieve project user + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + post: + summary: Modifies a user's role in the project. + operationId: modify-project-user + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + requestBody: + description: The project user update request payload. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUserUpdateRequest' + responses: + '200': + description: Project user's role updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUser' + '400': + description: Error response for various conditions. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Modify project user + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role": "owner" + }' + response: | + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + delete: + summary: > + Deletes a user from the project. + + + Returns confirmation of project user deletion, or an error if the + project is + + archived (archived projects have no users). + operationId: delete-project-user + tags: + - Projects + parameters: + - name: project_id + in: path + description: The ID of the project. + required: true + schema: + type: string + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + responses: + '200': + description: Project user deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/ProjectUserDeleteResponse' + '400': + description: Error response for various conditions. + content: + application/json: + schema: + $ref: '#/components/schemas/ErrorResponse' + x-oaiMeta: + name: Delete project user + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/projects/proj_abc/users/user_abc + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.project.user.deleted", + "id": "user_abc", + "deleted": true + } + /organization/roles: + get: + summary: Lists the roles configured for the organization. + operationId: list-roles + tags: + - Roles + parameters: + - name: limit + in: query + description: A limit on the number of roles to return. Defaults to 1000. + required: false + schema: + type: integer + minimum: 0 + maximum: 1000 + default: 1000 + - name: after + in: query + description: >- + Cursor for pagination. Provide the value from the previous + response's `next` field to continue listing roles. + required: false + schema: + type: string + - name: order + in: query + description: Sort order for the returned roles. + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + responses: + '200': + description: Roles listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/PublicRoleListResource' + x-oaiMeta: + name: List organization roles + group: administration + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/roles?limit=20 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "role", + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "description": "Allows managing organization groups", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false + } + ], + "has_more": false, + "next": null + } + post: + summary: Creates a custom role for the organization. + operationId: create-role + tags: + - Roles + requestBody: + description: Parameters for the role you want to create. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicCreateOrganizationRoleBody' + responses: + '200': + description: Role created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Role' + x-oaiMeta: + name: Create organization role + group: administration + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/organization/roles \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role_name": "API Group Manager", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "description": "Allows managing organization groups" + }' + response: | + { + "object": "role", + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "description": "Allows managing organization groups", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false + } + /organization/roles/{role_id}: + post: + summary: Updates an existing organization role. + operationId: update-role + tags: + - Roles + parameters: + - name: role_id + in: path + description: The ID of the role to update. + required: true + schema: + type: string + requestBody: + description: Fields to update on the role. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicUpdateOrganizationRoleBody' + responses: + '200': + description: Role updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Role' + x-oaiMeta: + name: Update organization role + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/roles/role_01J1F8ROLE01 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role_name": "API Group Manager", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "description": "Allows managing organization groups" + }' + response: | + { + "object": "role", + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "description": "Allows managing organization groups", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false + } + delete: + summary: Deletes a custom role from the organization. + operationId: delete-role + tags: + - Roles + parameters: + - name: role_id + in: path + description: The ID of the role to delete. + required: true + schema: + type: string + responses: + '200': + description: Role deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleDeletedResource' + x-oaiMeta: + name: Delete organization role + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/roles/role_01J1F8ROLE01 \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "role.deleted", + "id": "role_01J1F8ROLE01", + "deleted": true + } + /organization/usage/audio_speeches: + get: + summary: Get audio speeches usage details for the organization. + operationId: usage-audio-speeches + tags: + - Usage + parameters: + - name: start_time + in: query + description: Start time (Unix seconds) of the query time range, inclusive. + required: true + schema: + type: integer + - name: end_time + in: query + description: End time (Unix seconds) of the query time range, exclusive. + required: false + schema: + type: integer + - name: bucket_width + in: query + description: >- + Width of each time bucket in response. Currently `1m`, `1h` and `1d` + are supported, default to `1d`. + required: false + schema: + type: string + enum: + - 1m + - 1h + - 1d + default: 1d + - name: project_ids + in: query + description: Return only usage for these projects. + required: false + schema: + type: array + items: + type: string + - name: user_ids + in: query + description: Return only usage for these users. + required: false + schema: + type: array + items: + type: string + - name: api_key_ids + in: query + description: Return only usage for these API keys. + required: false + schema: + type: array + items: + type: string + - name: models + in: query + description: Return only usage for these models. + required: false + schema: + type: array + items: + type: string + - name: group_by + in: query + description: >- + Group the usage data by the specified fields. Support fields include + `project_id`, `user_id`, `api_key_id`, `model` or any combination of + them. + required: false + schema: + type: array + items: + type: string + enum: + - project_id + - user_id + - api_key_id + - model + - name: limit + in: query + description: | + Specifies the number of buckets to return. + - `bucket_width=1d`: default: 7, max: 31 + - `bucket_width=1h`: default: 24, max: 168 + - `bucket_width=1m`: default: 60, max: 1440 + required: false + schema: + type: integer + - name: page + in: query + description: >- + A cursor for use in pagination. Corresponding to the `next_page` + field from the previous response. + schema: + type: string + responses: + '200': + description: Usage data retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageResponse' + x-oaiMeta: + name: Audio speeches + group: usage-audio-speeches + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/usage/audio_speeches?start_time=1730419200&limit=1" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" + response: | + { + "object": "page", + "data": [ + { + "object": "bucket", + "start_time": 1730419200, + "end_time": 1730505600, + "results": [ + { + "object": "organization.usage.audio_speeches.result", + "characters": 45, + "num_model_requests": 1, + "project_id": null, + "user_id": null, + "api_key_id": null, + "model": null + } + ] + } + ], + "has_more": false, + "next_page": null + } + /organization/usage/audio_transcriptions: + get: + summary: Get audio transcriptions usage details for the organization. + operationId: usage-audio-transcriptions + tags: + - Usage + parameters: + - name: start_time + in: query + description: Start time (Unix seconds) of the query time range, inclusive. + required: true + schema: + type: integer + - name: end_time + in: query + description: End time (Unix seconds) of the query time range, exclusive. + required: false + schema: + type: integer + - name: bucket_width + in: query + description: >- + Width of each time bucket in response. Currently `1m`, `1h` and `1d` + are supported, default to `1d`. + required: false + schema: + type: string + enum: + - 1m + - 1h + - 1d + default: 1d + - name: project_ids + in: query + description: Return only usage for these projects. + required: false + schema: + type: array + items: + type: string + - name: user_ids + in: query + description: Return only usage for these users. + required: false + schema: + type: array + items: + type: string + - name: api_key_ids + in: query + description: Return only usage for these API keys. + required: false + schema: + type: array + items: + type: string + - name: models + in: query + description: Return only usage for these models. + required: false + schema: + type: array + items: + type: string + - name: group_by + in: query + description: >- + Group the usage data by the specified fields. Support fields include + `project_id`, `user_id`, `api_key_id`, `model` or any combination of + them. + required: false + schema: + type: array + items: + type: string + enum: + - project_id + - user_id + - api_key_id + - model + - name: limit + in: query + description: | + Specifies the number of buckets to return. + - `bucket_width=1d`: default: 7, max: 31 + - `bucket_width=1h`: default: 24, max: 168 + - `bucket_width=1m`: default: 60, max: 1440 + required: false + schema: + type: integer + - name: page + in: query + description: >- + A cursor for use in pagination. Corresponding to the `next_page` + field from the previous response. + schema: + type: string + responses: + '200': + description: Usage data retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageResponse' + x-oaiMeta: + name: Audio transcriptions + group: usage-audio-transcriptions + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/usage/audio_transcriptions?start_time=1730419200&limit=1" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" + response: | + { + "object": "page", + "data": [ + { + "object": "bucket", + "start_time": 1730419200, + "end_time": 1730505600, + "results": [ + { + "object": "organization.usage.audio_transcriptions.result", + "seconds": 20, + "num_model_requests": 1, + "project_id": null, + "user_id": null, + "api_key_id": null, + "model": null + } + ] + } + ], + "has_more": false, + "next_page": null + } + /organization/usage/code_interpreter_sessions: + get: + summary: Get code interpreter sessions usage details for the organization. + operationId: usage-code-interpreter-sessions + tags: + - Usage + parameters: + - name: start_time + in: query + description: Start time (Unix seconds) of the query time range, inclusive. + required: true + schema: + type: integer + - name: end_time + in: query + description: End time (Unix seconds) of the query time range, exclusive. + required: false + schema: + type: integer + - name: bucket_width + in: query + description: >- + Width of each time bucket in response. Currently `1m`, `1h` and `1d` + are supported, default to `1d`. + required: false + schema: + type: string + enum: + - 1m + - 1h + - 1d + default: 1d + - name: project_ids + in: query + description: Return only usage for these projects. + required: false + schema: + type: array + items: + type: string + - name: group_by + in: query + description: >- + Group the usage data by the specified fields. Support fields include + `project_id`. + required: false + schema: + type: array + items: + type: string + enum: + - project_id + - name: limit + in: query + description: | + Specifies the number of buckets to return. + - `bucket_width=1d`: default: 7, max: 31 + - `bucket_width=1h`: default: 24, max: 168 + - `bucket_width=1m`: default: 60, max: 1440 + required: false + schema: + type: integer + - name: page + in: query + description: >- + A cursor for use in pagination. Corresponding to the `next_page` + field from the previous response. + schema: + type: string + responses: + '200': + description: Usage data retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageResponse' + x-oaiMeta: + name: Code interpreter sessions + group: usage-code-interpreter-sessions + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/usage/code_interpreter_sessions?start_time=1730419200&limit=1" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" + response: | + { + "object": "page", + "data": [ + { + "object": "bucket", + "start_time": 1730419200, + "end_time": 1730505600, + "results": [ + { + "object": "organization.usage.code_interpreter_sessions.result", + "num_sessions": 1, + "project_id": null + } + ] + } + ], + "has_more": false, + "next_page": null + } + /organization/usage/completions: + get: + summary: Get completions usage details for the organization. + operationId: usage-completions + tags: + - Usage + parameters: + - name: start_time + in: query + description: Start time (Unix seconds) of the query time range, inclusive. + required: true + schema: + type: integer + - name: end_time + in: query + description: End time (Unix seconds) of the query time range, exclusive. + required: false + schema: + type: integer + - name: bucket_width + in: query + description: >- + Width of each time bucket in response. Currently `1m`, `1h` and `1d` + are supported, default to `1d`. + required: false + schema: + type: string + enum: + - 1m + - 1h + - 1d + default: 1d + - name: project_ids + in: query + description: Return only usage for these projects. + required: false + schema: + type: array + items: + type: string + - name: user_ids + in: query + description: Return only usage for these users. + required: false + schema: + type: array + items: + type: string + - name: api_key_ids + in: query + description: Return only usage for these API keys. + required: false + schema: + type: array + items: + type: string + - name: models + in: query + description: Return only usage for these models. + required: false + schema: + type: array + items: + type: string + - name: batch + in: query + description: > + If `true`, return batch jobs only. If `false`, return non-batch jobs + only. By default, return both. + required: false + schema: + type: boolean + - name: group_by + in: query + description: >- + Group the usage data by the specified fields. Support fields include + `project_id`, `user_id`, `api_key_id`, `model`, `batch`, + `service_tier` or any combination of them. + required: false + schema: + type: array + items: + type: string + enum: + - project_id + - user_id + - api_key_id + - model + - batch + - service_tier + - name: limit + in: query + description: | + Specifies the number of buckets to return. + - `bucket_width=1d`: default: 7, max: 31 + - `bucket_width=1h`: default: 24, max: 168 + - `bucket_width=1m`: default: 60, max: 1440 + required: false + schema: + type: integer + - name: page + in: query + description: >- + A cursor for use in pagination. Corresponding to the `next_page` + field from the previous response. + schema: + type: string + responses: + '200': + description: Usage data retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageResponse' + x-oaiMeta: + name: Completions + group: usage-completions + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/usage/completions?start_time=1730419200&limit=1" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" + response: | + { + "object": "page", + "data": [ + { + "object": "bucket", + "start_time": 1730419200, + "end_time": 1730505600, + "results": [ + { + "object": "organization.usage.completions.result", + "input_tokens": 1000, + "output_tokens": 500, + "input_cached_tokens": 800, + "input_audio_tokens": 0, + "output_audio_tokens": 0, + "num_model_requests": 5, + "project_id": null, + "user_id": null, + "api_key_id": null, + "model": null, + "batch": null, + "service_tier": null + } + ] + } + ], + "has_more": true, + "next_page": "page_AAAAAGdGxdEiJdKOAAAAAGcqsYA=" + } + /organization/usage/embeddings: + get: + summary: Get embeddings usage details for the organization. + operationId: usage-embeddings + tags: + - Usage + parameters: + - name: start_time + in: query + description: Start time (Unix seconds) of the query time range, inclusive. + required: true + schema: + type: integer + - name: end_time + in: query + description: End time (Unix seconds) of the query time range, exclusive. + required: false + schema: + type: integer + - name: bucket_width + in: query + description: >- + Width of each time bucket in response. Currently `1m`, `1h` and `1d` + are supported, default to `1d`. + required: false + schema: + type: string + enum: + - 1m + - 1h + - 1d + default: 1d + - name: project_ids + in: query + description: Return only usage for these projects. + required: false + schema: + type: array + items: + type: string + - name: user_ids + in: query + description: Return only usage for these users. + required: false + schema: + type: array + items: + type: string + - name: api_key_ids + in: query + description: Return only usage for these API keys. + required: false + schema: + type: array + items: + type: string + - name: models + in: query + description: Return only usage for these models. + required: false + schema: + type: array + items: + type: string + - name: group_by + in: query + description: >- + Group the usage data by the specified fields. Support fields include + `project_id`, `user_id`, `api_key_id`, `model` or any combination of + them. + required: false + schema: + type: array + items: + type: string + enum: + - project_id + - user_id + - api_key_id + - model + - name: limit + in: query + description: | + Specifies the number of buckets to return. + - `bucket_width=1d`: default: 7, max: 31 + - `bucket_width=1h`: default: 24, max: 168 + - `bucket_width=1m`: default: 60, max: 1440 + required: false + schema: + type: integer + - name: page + in: query + description: >- + A cursor for use in pagination. Corresponding to the `next_page` + field from the previous response. + schema: + type: string + responses: + '200': + description: Usage data retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageResponse' + x-oaiMeta: + name: Embeddings + group: usage-embeddings + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/usage/embeddings?start_time=1730419200&limit=1" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" + response: | + { + "object": "page", + "data": [ + { + "object": "bucket", + "start_time": 1730419200, + "end_time": 1730505600, + "results": [ + { + "object": "organization.usage.embeddings.result", + "input_tokens": 16, + "num_model_requests": 2, + "project_id": null, + "user_id": null, + "api_key_id": null, + "model": null + } + ] + } + ], + "has_more": false, + "next_page": null + } + /organization/usage/images: + get: + summary: Get images usage details for the organization. + operationId: usage-images + tags: + - Usage + parameters: + - name: start_time + in: query + description: Start time (Unix seconds) of the query time range, inclusive. + required: true + schema: + type: integer + - name: end_time + in: query + description: End time (Unix seconds) of the query time range, exclusive. + required: false + schema: + type: integer + - name: bucket_width + in: query + description: >- + Width of each time bucket in response. Currently `1m`, `1h` and `1d` + are supported, default to `1d`. + required: false + schema: + type: string + enum: + - 1m + - 1h + - 1d + default: 1d + - name: sources + in: query + description: >- + Return only usages for these sources. Possible values are + `image.generation`, `image.edit`, `image.variation` or any + combination of them. + required: false + schema: + type: array + items: + type: string + enum: + - image.generation + - image.edit + - image.variation + - name: sizes + in: query + description: >- + Return only usages for these image sizes. Possible values are + `256x256`, `512x512`, `1024x1024`, `1792x1792`, `1024x1792` or any + combination of them. + required: false + schema: + type: array + items: + type: string + enum: + - 256x256 + - 512x512 + - 1024x1024 + - 1792x1792 + - 1024x1792 + - name: project_ids + in: query + description: Return only usage for these projects. + required: false + schema: + type: array + items: + type: string + - name: user_ids + in: query + description: Return only usage for these users. + required: false + schema: + type: array + items: + type: string + - name: api_key_ids + in: query + description: Return only usage for these API keys. + required: false + schema: + type: array + items: + type: string + - name: models + in: query + description: Return only usage for these models. + required: false + schema: + type: array + items: + type: string + - name: group_by + in: query + description: >- + Group the usage data by the specified fields. Support fields include + `project_id`, `user_id`, `api_key_id`, `model`, `size`, `source` or + any combination of them. + required: false + schema: + type: array + items: + type: string + enum: + - project_id + - user_id + - api_key_id + - model + - size + - source + - name: limit + in: query + description: | + Specifies the number of buckets to return. + - `bucket_width=1d`: default: 7, max: 31 + - `bucket_width=1h`: default: 24, max: 168 + - `bucket_width=1m`: default: 60, max: 1440 + required: false + schema: + type: integer + - name: page + in: query + description: >- + A cursor for use in pagination. Corresponding to the `next_page` + field from the previous response. + schema: + type: string + responses: + '200': + description: Usage data retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageResponse' + x-oaiMeta: + name: Images + group: usage-images + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/usage/images?start_time=1730419200&limit=1" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" + response: | + { + "object": "page", + "data": [ + { + "object": "bucket", + "start_time": 1730419200, + "end_time": 1730505600, + "results": [ + { + "object": "organization.usage.images.result", + "images": 2, + "num_model_requests": 2, + "size": null, + "source": null, + "project_id": null, + "user_id": null, + "api_key_id": null, + "model": null + } + ] + } + ], + "has_more": false, + "next_page": null + } + /organization/usage/moderations: + get: + summary: Get moderations usage details for the organization. + operationId: usage-moderations + tags: + - Usage + parameters: + - name: start_time + in: query + description: Start time (Unix seconds) of the query time range, inclusive. + required: true + schema: + type: integer + - name: end_time + in: query + description: End time (Unix seconds) of the query time range, exclusive. + required: false + schema: + type: integer + - name: bucket_width + in: query + description: >- + Width of each time bucket in response. Currently `1m`, `1h` and `1d` + are supported, default to `1d`. + required: false + schema: + type: string + enum: + - 1m + - 1h + - 1d + default: 1d + - name: project_ids + in: query + description: Return only usage for these projects. + required: false + schema: + type: array + items: + type: string + - name: user_ids + in: query + description: Return only usage for these users. + required: false + schema: + type: array + items: + type: string + - name: api_key_ids + in: query + description: Return only usage for these API keys. + required: false + schema: + type: array + items: + type: string + - name: models + in: query + description: Return only usage for these models. + required: false + schema: + type: array + items: + type: string + - name: group_by + in: query + description: >- + Group the usage data by the specified fields. Support fields include + `project_id`, `user_id`, `api_key_id`, `model` or any combination of + them. + required: false + schema: + type: array + items: + type: string + enum: + - project_id + - user_id + - api_key_id + - model + - name: limit + in: query + description: | + Specifies the number of buckets to return. + - `bucket_width=1d`: default: 7, max: 31 + - `bucket_width=1h`: default: 24, max: 168 + - `bucket_width=1m`: default: 60, max: 1440 + required: false + schema: + type: integer + - name: page + in: query + description: >- + A cursor for use in pagination. Corresponding to the `next_page` + field from the previous response. + schema: + type: string + responses: + '200': + description: Usage data retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageResponse' + x-oaiMeta: + name: Moderations + group: usage-moderations + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/usage/moderations?start_time=1730419200&limit=1" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" + response: | + { + "object": "page", + "data": [ + { + "object": "bucket", + "start_time": 1730419200, + "end_time": 1730505600, + "results": [ + { + "object": "organization.usage.moderations.result", + "input_tokens": 16, + "num_model_requests": 2, + "project_id": null, + "user_id": null, + "api_key_id": null, + "model": null + } + ] + } + ], + "has_more": false, + "next_page": null + } + /organization/usage/vector_stores: + get: + summary: Get vector stores usage details for the organization. + operationId: usage-vector-stores + tags: + - Usage + parameters: + - name: start_time + in: query + description: Start time (Unix seconds) of the query time range, inclusive. + required: true + schema: + type: integer + - name: end_time + in: query + description: End time (Unix seconds) of the query time range, exclusive. + required: false + schema: + type: integer + - name: bucket_width + in: query + description: >- + Width of each time bucket in response. Currently `1m`, `1h` and `1d` + are supported, default to `1d`. + required: false + schema: + type: string + enum: + - 1m + - 1h + - 1d + default: 1d + - name: project_ids + in: query + description: Return only usage for these projects. + required: false + schema: + type: array + items: + type: string + - name: group_by + in: query + description: >- + Group the usage data by the specified fields. Support fields include + `project_id`. + required: false + schema: + type: array + items: + type: string + enum: + - project_id + - name: limit + in: query + description: | + Specifies the number of buckets to return. + - `bucket_width=1d`: default: 7, max: 31 + - `bucket_width=1h`: default: 24, max: 168 + - `bucket_width=1m`: default: 60, max: 1440 + required: false + schema: + type: integer + - name: page + in: query + description: >- + A cursor for use in pagination. Corresponding to the `next_page` + field from the previous response. + schema: + type: string + responses: + '200': + description: Usage data retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UsageResponse' + x-oaiMeta: + name: Vector stores + group: usage-vector-stores + examples: + request: + curl: > + curl + "https://api.openai.com/v1/organization/usage/vector_stores?start_time=1730419200&limit=1" + \ + + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + + -H "Content-Type: application/json" + response: | + { + "object": "page", + "data": [ + { + "object": "bucket", + "start_time": 1730419200, + "end_time": 1730505600, + "results": [ + { + "object": "organization.usage.vector_stores.result", + "usage_bytes": 1024, + "project_id": null + } + ] + } + ], + "has_more": false, + "next_page": null + } + /organization/users: + get: + summary: Lists all of the users in the organization. + operationId: list-users + tags: + - Users + parameters: + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + required: false + schema: + type: string + - name: emails + in: query + description: Filter by the email address of users. + required: false + schema: + type: array + items: + type: string + responses: + '200': + description: Users listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UserListResponse' + x-oaiMeta: + name: List users + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/users?after=user_abc&limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + ], + "first_id": "user-abc", + "last_id": "user-xyz", + "has_more": false + } + /organization/users/{user_id}: + get: + summary: Retrieves a user by their identifier. + operationId: retrieve-user + tags: + - Users + parameters: + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + responses: + '200': + description: User retrieved successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/User' + x-oaiMeta: + name: Retrieve user + group: administration + examples: + request: + curl: | + curl https://api.openai.com/v1/organization/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + post: + summary: Modifies a user's role in the organization. + operationId: modify-user + tags: + - Users + parameters: + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + requestBody: + description: The new user role to modify. This must be one of `owner` or `member`. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UserRoleUpdateRequest' + responses: + '200': + description: User role updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/User' + x-oaiMeta: + name: Modify user + group: administration + examples: + request: + curl: > + curl -X POST https://api.openai.com/v1/organization/users/user_abc + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role": "owner" + }' + response: | + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + delete: + summary: Deletes a user from the organization. + operationId: delete-user + tags: + - Users + parameters: + - name: user_id + in: path + description: The ID of the user. + required: true + schema: + type: string + responses: + '200': + description: User deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UserDeleteResponse' + x-oaiMeta: + name: Delete user + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/users/user_abc \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "organization.user.deleted", + "id": "user_abc", + "deleted": true + } + /organization/users/{user_id}/roles: + get: + summary: Lists the organization roles assigned to a user within the organization. + operationId: list-user-role-assignments + tags: + - User organization role assignments + parameters: + - name: user_id + in: path + description: The ID of the user to inspect. + required: true + schema: + type: string + - name: limit + in: query + description: A limit on the number of organization role assignments to return. + required: false + schema: + type: integer + minimum: 0 + maximum: 1000 + - name: after + in: query + description: >- + Cursor for pagination. Provide the value from the previous + response's `next` field to continue listing organization roles. + required: false + schema: + type: string + - name: order + in: query + description: Sort order for the returned organization roles. + required: false + schema: + type: string + enum: + - asc + - desc + responses: + '200': + description: User organization role assignments listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleListResource' + x-oaiMeta: + name: List user organization role assignments + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/organization/users/user_abc123/roles \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false, + "description": "Allows managing organization groups", + "created_at": 1711471533, + "updated_at": 1711472599, + "created_by": "user_abc123", + "created_by_user_obj": { + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com" + }, + "metadata": {} + } + ], + "has_more": false, + "next": null + } + post: + summary: Assigns an organization role to a user within the organization. + operationId: assign-user-role + tags: + - User organization role assignments + parameters: + - name: user_id + in: path + description: The ID of the user that should receive the organization role. + required: true + schema: + type: string + requestBody: + description: Identifies the organization role to assign to the user. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicAssignOrganizationGroupRoleBody' + responses: + '200': + description: Organization role assigned to the user successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UserRoleAssignment' + x-oaiMeta: + name: Assign organization role to user + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/organization/users/user_abc123/roles \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role_id": "role_01J1F8ROLE01" + }' + response: | + { + "object": "user.role", + "user": { + "object": "organization.user", + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com", + "role": "owner", + "added_at": 1711470000 + }, + "role": { + "object": "role", + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "description": "Allows managing organization groups", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false + } + } + /organization/users/{user_id}/roles/{role_id}: + delete: + summary: Unassigns an organization role from a user within the organization. + operationId: unassign-user-role + tags: + - User organization role assignments + parameters: + - name: user_id + in: path + description: The ID of the user to modify. + required: true + schema: + type: string + - name: role_id + in: path + description: The ID of the organization role to remove from the user. + required: true + schema: + type: string + responses: + '200': + description: Organization role unassigned from the user successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/DeletedRoleAssignmentResource' + x-oaiMeta: + name: Unassign organization role from user + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/organization/users/user_abc123/roles/role_01J1F8ROLE01 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "user.role.deleted", + "deleted": true + } + /projects/{project_id}/groups/{group_id}/roles: + get: + summary: Lists the project roles assigned to a group within a project. + operationId: list-project-group-role-assignments + tags: + - Project group role assignments + parameters: + - name: project_id + in: path + description: The ID of the project to inspect. + required: true + schema: + type: string + - name: group_id + in: path + description: The ID of the group to inspect. + required: true + schema: + type: string + - name: limit + in: query + description: A limit on the number of project role assignments to return. + required: false + schema: + type: integer + minimum: 0 + maximum: 1000 + - name: after + in: query + description: >- + Cursor for pagination. Provide the value from the previous + response's `next` field to continue listing project roles. + required: false + schema: + type: string + - name: order + in: query + description: Sort order for the returned project roles. + required: false + schema: + type: string + enum: + - asc + - desc + responses: + '200': + description: Project group role assignments listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleListResource' + x-oaiMeta: + name: List project group role assignments + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/projects/proj_abc123/groups/group_01J1F8ABCDXYZ/roles + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "id": "role_01J1F8PROJ", + "name": "API Project Key Manager", + "permissions": [ + "api.organization.projects.api_keys.read", + "api.organization.projects.api_keys.write" + ], + "resource_type": "api.project", + "predefined_role": false, + "description": "Allows managing API keys for the project", + "created_at": 1711471533, + "updated_at": 1711472599, + "created_by": "user_abc123", + "created_by_user_obj": { + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com" + }, + "metadata": {} + } + ], + "has_more": false, + "next": null + } + post: + summary: Assigns a project role to a group within a project. + operationId: assign-project-group-role + tags: + - Project group role assignments + parameters: + - name: project_id + in: path + description: The ID of the project to update. + required: true + schema: + type: string + - name: group_id + in: path + description: The ID of the group that should receive the project role. + required: true + schema: + type: string + requestBody: + description: Identifies the project role to assign to the group. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicAssignOrganizationGroupRoleBody' + responses: + '200': + description: Project role assigned to the group successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/GroupRoleAssignment' + x-oaiMeta: + name: Assign project role to group + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/projects/proj_abc123/groups/group_01J1F8ABCDXYZ/roles + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role_id": "role_01J1F8PROJ" + }' + response: | + { + "object": "group.role", + "group": { + "object": "group", + "id": "group_01J1F8ABCDXYZ", + "name": "Support Team", + "created_at": 1711471533, + "scim_managed": false + }, + "role": { + "object": "role", + "id": "role_01J1F8PROJ", + "name": "API Project Key Manager", + "description": "Allows managing API keys for the project", + "permissions": [ + "api.organization.projects.api_keys.read", + "api.organization.projects.api_keys.write" + ], + "resource_type": "api.project", + "predefined_role": false + } + } + /projects/{project_id}/groups/{group_id}/roles/{role_id}: + delete: + summary: Unassigns a project role from a group within a project. + operationId: unassign-project-group-role + tags: + - Project group role assignments + parameters: + - name: project_id + in: path + description: The ID of the project to modify. + required: true + schema: + type: string + - name: group_id + in: path + description: The ID of the group whose project role assignment should be removed. + required: true + schema: + type: string + - name: role_id + in: path + description: The ID of the project role to remove from the group. + required: true + schema: + type: string + responses: + '200': + description: Project role unassigned from the group successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/DeletedRoleAssignmentResource' + x-oaiMeta: + name: Unassign project role from group + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/projects/proj_abc123/groups/group_01J1F8ABCDXYZ/roles/role_01J1F8PROJ + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "group.role.deleted", + "deleted": true + } + /projects/{project_id}/roles: + get: + summary: Lists the roles configured for a project. + operationId: list-project-roles + tags: + - Roles + parameters: + - name: project_id + in: path + description: The ID of the project to inspect. + required: true + schema: + type: string + - name: limit + in: query + description: A limit on the number of roles to return. Defaults to 1000. + required: false + schema: + type: integer + minimum: 0 + maximum: 1000 + default: 1000 + - name: after + in: query + description: >- + Cursor for pagination. Provide the value from the previous + response's `next` field to continue listing roles. + required: false + schema: + type: string + - name: order + in: query + description: Sort order for the returned roles. + required: false + schema: + type: string + enum: + - asc + - desc + default: asc + responses: + '200': + description: Project roles listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/PublicRoleListResource' + x-oaiMeta: + name: List project roles + group: administration + examples: + request: + curl: > + curl https://api.openai.com/v1/projects/proj_abc123/roles?limit=20 + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "object": "role", + "id": "role_01J1F8PROJ", + "name": "API Project Key Manager", + "description": "Allows managing API keys for the project", + "permissions": [ + "api.organization.projects.api_keys.read", + "api.organization.projects.api_keys.write" + ], + "resource_type": "api.project", + "predefined_role": false + } + ], + "has_more": false, + "next": null + } + post: + summary: Creates a custom role for a project. + operationId: create-project-role + tags: + - Roles + parameters: + - name: project_id + in: path + description: The ID of the project to update. + required: true + schema: + type: string + requestBody: + description: Parameters for the project role you want to create. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicCreateOrganizationRoleBody' + responses: + '200': + description: Project role created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Role' + x-oaiMeta: + name: Create project role + group: administration + examples: + request: + curl: > + curl -X POST https://api.openai.com/v1/projects/proj_abc123/roles + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role_name": "API Project Key Manager", + "permissions": [ + "api.organization.projects.api_keys.read", + "api.organization.projects.api_keys.write" + ], + "description": "Allows managing API keys for the project" + }' + response: | + { + "object": "role", + "id": "role_01J1F8PROJ", + "name": "API Project Key Manager", + "description": "Allows managing API keys for the project", + "permissions": [ + "api.organization.projects.api_keys.read", + "api.organization.projects.api_keys.write" + ], + "resource_type": "api.project", + "predefined_role": false + } + /projects/{project_id}/roles/{role_id}: + post: + summary: Updates an existing project role. + operationId: update-project-role + tags: + - Roles + parameters: + - name: project_id + in: path + description: The ID of the project to update. + required: true + schema: + type: string + - name: role_id + in: path + description: The ID of the role to update. + required: true + schema: + type: string + requestBody: + description: Fields to update on the project role. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicUpdateOrganizationRoleBody' + responses: + '200': + description: Project role updated successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/Role' + x-oaiMeta: + name: Update project role + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/projects/proj_abc123/roles/role_01J1F8PROJ + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role_name": "API Project Key Manager", + "permissions": [ + "api.organization.projects.api_keys.read", + "api.organization.projects.api_keys.write" + ], + "description": "Allows managing API keys for the project" + }' + response: | + { + "object": "role", + "id": "role_01J1F8PROJ", + "name": "API Project Key Manager", + "description": "Allows managing API keys for the project", + "permissions": [ + "api.organization.projects.api_keys.read", + "api.organization.projects.api_keys.write" + ], + "resource_type": "api.project", + "predefined_role": false + } + delete: + summary: Deletes a custom role from a project. + operationId: delete-project-role + tags: + - Roles + parameters: + - name: project_id + in: path + description: The ID of the project to update. + required: true + schema: + type: string + - name: role_id + in: path + description: The ID of the role to delete. + required: true + schema: + type: string + responses: + '200': + description: Project role deleted successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleDeletedResource' + x-oaiMeta: + name: Delete project role + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/projects/proj_abc123/roles/role_01J1F8PROJ + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "role.deleted", + "id": "role_01J1F8PROJ", + "deleted": true + } + /projects/{project_id}/users/{user_id}/roles: + get: + summary: Lists the project roles assigned to a user within a project. + operationId: list-project-user-role-assignments + tags: + - Project user role assignments + parameters: + - name: project_id + in: path + description: The ID of the project to inspect. + required: true + schema: + type: string + - name: user_id + in: path + description: The ID of the user to inspect. + required: true + schema: + type: string + - name: limit + in: query + description: A limit on the number of project role assignments to return. + required: false + schema: + type: integer + minimum: 0 + maximum: 1000 + - name: after + in: query + description: >- + Cursor for pagination. Provide the value from the previous + response's `next` field to continue listing project roles. + required: false + schema: + type: string + - name: order + in: query + description: Sort order for the returned project roles. + required: false + schema: + type: string + enum: + - asc + - desc + responses: + '200': + description: Project user role assignments listed successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/RoleListResource' + x-oaiMeta: + name: List project user role assignments + group: administration + examples: + request: + curl: > + curl + https://api.openai.com/v1/projects/proj_abc123/users/user_abc123/roles + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "list", + "data": [ + { + "id": "role_01J1F8PROJ", + "name": "API Project Key Manager", + "permissions": [ + "api.organization.projects.api_keys.read", + "api.organization.projects.api_keys.write" + ], + "resource_type": "api.project", + "predefined_role": false, + "description": "Allows managing API keys for the project", + "created_at": 1711471533, + "updated_at": 1711472599, + "created_by": "user_abc123", + "created_by_user_obj": { + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com" + }, + "metadata": {} + } + ], + "has_more": false, + "next": null + } + post: + summary: Assigns a project role to a user within a project. + operationId: assign-project-user-role + tags: + - Project user role assignments + parameters: + - name: project_id + in: path + description: The ID of the project to update. + required: true + schema: + type: string + - name: user_id + in: path + description: The ID of the user that should receive the project role. + required: true + schema: + type: string + requestBody: + description: Identifies the project role to assign to the user. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/PublicAssignOrganizationGroupRoleBody' + responses: + '200': + description: Project role assigned to the user successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/UserRoleAssignment' + x-oaiMeta: + name: Assign project role to user + group: administration + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/projects/proj_abc123/users/user_abc123/roles + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "role_id": "role_01J1F8PROJ" + }' + response: | + { + "object": "user.role", + "user": { + "object": "organization.user", + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com", + "role": "owner", + "added_at": 1711470000 + }, + "role": { + "object": "role", + "id": "role_01J1F8PROJ", + "name": "API Project Key Manager", + "description": "Allows managing API keys for the project", + "permissions": [ + "api.organization.projects.api_keys.read", + "api.organization.projects.api_keys.write" + ], + "resource_type": "api.project", + "predefined_role": false + } + } + /projects/{project_id}/users/{user_id}/roles/{role_id}: + delete: + summary: Unassigns a project role from a user within a project. + operationId: unassign-project-user-role + tags: + - Project user role assignments + parameters: + - name: project_id + in: path + description: The ID of the project to modify. + required: true + schema: + type: string + - name: user_id + in: path + description: The ID of the user whose project role assignment should be removed. + required: true + schema: + type: string + - name: role_id + in: path + description: The ID of the project role to remove from the user. + required: true + schema: + type: string + responses: + '200': + description: Project role unassigned from the user successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/DeletedRoleAssignmentResource' + x-oaiMeta: + name: Unassign project role from user + group: administration + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/projects/proj_abc123/users/user_abc123/roles/role_01J1F8PROJ + \ + -H "Authorization: Bearer $OPENAI_ADMIN_KEY" \ + -H "Content-Type: application/json" + response: | + { + "object": "user.role.deleted", + "deleted": true + } + /realtime/calls: + post: + summary: >- + Create a new Realtime API call over WebRTC and receive the SDP answer + needed + + to complete the peer connection. + operationId: create-realtime-call + tags: + - Realtime + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/RealtimeCallCreateRequest' + encoding: + sdp: + contentType: application/sdp + session: + contentType: application/json + application/sdp: + schema: + type: string + description: >- + WebRTC SDP offer. Use this variant when you have previously + created an + + ephemeral **session token** and are authenticating the request + with it. + + Realtime session parameters will be retrieved from the session + token. + responses: + '201': + description: Realtime call created successfully. + headers: + Location: + description: >- + Relative URL containing the call ID for subsequent control + requests. + schema: + type: string + content: + application/sdp: + schema: + type: string + description: SDP answer produced by OpenAI for the peer connection. + x-oaiMeta: + name: Create call + group: realtime + returns: >- + Returns `201 Created` with the SDP answer in the response body. The + + `Location` response header includes the call ID for follow-up + requests, + + e.g., establishing a monitoring WebSocket or hanging up the call. + examples: + request: + curl: |- + curl -X POST https://api.openai.com/v1/realtime/calls \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F "sdp=- + v=0 + + o=- 4227147428 1719357865 IN IP4 127.0.0.1 + + s=- + + c=IN IP4 0.0.0.0 + + t=0 0 + + a=group:BUNDLE 0 1 + + a=msid-semantic:WMS * + + a=fingerprint:sha-256 + CA:92:52:51:B4:91:3B:34:DD:9C:0B:FB:76:19:7E:3B:F1:21:0F:32:2C:38:01:72:5D:3F:78:C7:5F:8B:C7:36 + + m=audio 9 UDP/TLS/RTP/SAVPF 111 0 8 + + a=mid:0 + + a=ice-ufrag:kZ2qkHXX/u11 + + a=ice-pwd:uoD16Di5OGx3VbqgA3ymjEQV2kwiOjw6 + + a=setup:active + + a=rtcp-mux + + a=rtpmap:111 opus/48000/2 + + a=candidate:993865896 1 udp 2130706431 4.155.146.196 3478 typ host + ufrag kZ2qkHXX/u11 + + a=candidate:1432411780 1 tcp 1671430143 4.155.146.196 443 typ host + tcptype passive ufrag kZ2qkHXX/u11 + + m=application 9 UDP/DTLS/SCTP webrtc-datachannel + + a=mid:1 + + a=sctp-port:5000 + /realtime/calls/{call_id}/accept: + post: + summary: |- + Accept an incoming SIP call and configure the realtime session that will + handle it. + operationId: accept-realtime-call + tags: + - Realtime + parameters: + - in: path + name: call_id + required: true + schema: + type: string + description: >- + The identifier for the call provided in the + + [`realtime.call.incoming`](/docs/api-reference/webhook-events/realtime/call/incoming) + + webhook. + requestBody: + required: true + description: >- + Session configuration to apply before the caller is bridged to the + model. + content: + application/json: + schema: + $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' + responses: + '200': + description: Call accepted successfully. + x-oaiMeta: + name: Accept call + group: realtime-calls + returns: >- + Returns `200 OK` once OpenAI starts ringing the SIP leg with the + supplied + + session configuration. + examples: + request: + curl: >- + curl -X POST + https://api.openai.com/v1/realtime/calls/$CALL_ID/accept \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "type": "realtime", + "model": "gpt-realtime", + "instructions": "You are Alex, a friendly concierge for Example Corp.", + }' + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + await client.realtime.calls.accept('call_id', { type: 'realtime' + }); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + client.realtime.calls.accept( + call_id="call_id", + type="realtime", + ) + go: "package main\n\nimport (\n\t\"context\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/realtime\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\terr := client.Realtime.Calls.Accept(\n\t\tcontext.TODO(),\n\t\t\"call_id\",\n\t\trealtime.CallAcceptParams{\n\t\t\tRealtimeSessionCreateRequest: realtime.RealtimeSessionCreateRequestParam{},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.realtime.RealtimeSessionCreateRequest; + import com.openai.models.realtime.calls.CallAcceptParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + CallAcceptParams params = CallAcceptParams.builder() + .callId("call_id") + .realtimeSessionCreateRequest(RealtimeSessionCreateRequest.builder().build()) + .build(); + client.realtime().calls().accept(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + result = openai.realtime.calls.accept("call_id", type: :realtime) + + puts(result) + response: '' + /realtime/calls/{call_id}/hangup: + post: + summary: |- + End an active Realtime API call, whether it was initiated over SIP or + WebRTC. + operationId: hangup-realtime-call + tags: + - Realtime + parameters: + - in: path + name: call_id + required: true + schema: + type: string + description: >- + The identifier for the call. For SIP calls, use the value provided + in the + + [`realtime.call.incoming`](/docs/api-reference/webhook-events/realtime/call/incoming) + + webhook. For WebRTC sessions, reuse the call ID returned in the + `Location` + + header when creating the call with + + [`POST + /v1/realtime/calls`](/docs/api-reference/realtime/create-call). + responses: + '200': + description: Call hangup initiated successfully. + x-oaiMeta: + name: Hang up call + group: realtime-calls + returns: Returns `200 OK` when OpenAI begins terminating the realtime call. + examples: + request: + curl: >- + curl -X POST + https://api.openai.com/v1/realtime/calls/$CALL_ID/hangup \ + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + await client.realtime.calls.hangup('call_id'); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + client.realtime.calls.hangup( + "call_id", + ) + go: "package main\n\nimport (\n\t\"context\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\terr := client.Realtime.Calls.Hangup(context.TODO(), \"call_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.realtime.calls.CallHangupParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + client.realtime().calls().hangup("call_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + result = openai.realtime.calls.hangup("call_id") + + puts(result) + response: '' + /realtime/calls/{call_id}/refer: + post: + summary: >- + Transfer an active SIP call to a new destination using the SIP REFER + verb. + operationId: refer-realtime-call + tags: + - Realtime + parameters: + - in: path + name: call_id + required: true + schema: + type: string + description: >- + The identifier for the call provided in the + + [`realtime.call.incoming`](/docs/api-reference/webhook-events/realtime/call/incoming) + + webhook. + requestBody: + required: true + description: Destination URI for the REFER request. + content: + application/json: + schema: + $ref: '#/components/schemas/RealtimeCallReferRequest' + responses: + '200': + description: Call referred successfully. + x-oaiMeta: + name: Refer call + group: realtime-calls + returns: Returns `200 OK` once the REFER is handed off to your SIP provider. + examples: + request: + curl: >- + curl -X POST + https://api.openai.com/v1/realtime/calls/$CALL_ID/refer \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"target_uri": "tel:+14155550123"}' + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + await client.realtime.calls.refer('call_id', { target_uri: + 'tel:+14155550123' }); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + client.realtime.calls.refer( + call_id="call_id", + target_uri="tel:+14155550123", + ) + go: "package main\n\nimport (\n\t\"context\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/realtime\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\terr := client.Realtime.Calls.Refer(\n\t\tcontext.TODO(),\n\t\t\"call_id\",\n\t\trealtime.CallReferParams{\n\t\t\tTargetUri: \"tel:+14155550123\",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.realtime.calls.CallReferParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + CallReferParams params = CallReferParams.builder() + .callId("call_id") + .targetUri("tel:+14155550123") + .build(); + client.realtime().calls().refer(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + result = openai.realtime.calls.refer("call_id", target_uri: + "tel:+14155550123") + + + puts(result) + response: '' + /realtime/calls/{call_id}/reject: + post: + summary: >- + Decline an incoming SIP call by returning a SIP status code to the + caller. + operationId: reject-realtime-call + tags: + - Realtime + parameters: + - in: path + name: call_id + required: true + schema: + type: string + description: >- + The identifier for the call provided in the + + [`realtime.call.incoming`](/docs/api-reference/webhook-events/realtime/call/incoming) + + webhook. + requestBody: + required: false + description: >- + Provide an optional SIP status code. When omitted the API responds + with + + `603 Decline`. + content: + application/json: + schema: + $ref: '#/components/schemas/RealtimeCallRejectRequest' + responses: + '200': + description: Call rejected successfully. + x-oaiMeta: + name: Reject call + group: realtime-calls + returns: Returns `200 OK` after OpenAI sends the SIP status code to the caller. + examples: + request: + curl: >- + curl -X POST + https://api.openai.com/v1/realtime/calls/$CALL_ID/reject \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"status_code": 486}' + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + await client.realtime.calls.reject('call_id'); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + client.realtime.calls.reject( + call_id="call_id", + ) + go: "package main\n\nimport (\n\t\"context\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/realtime\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\terr := client.Realtime.Calls.Reject(\n\t\tcontext.TODO(),\n\t\t\"call_id\",\n\t\trealtime.CallRejectParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.realtime.calls.CallRejectParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + client.realtime().calls().reject("call_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + result = openai.realtime.calls.reject("call_id") + + puts(result) + response: '' + /realtime/client_secrets: + post: + summary: > + Create a Realtime client secret with an associated session + configuration. + + + Client secrets are short-lived tokens that can be passed to a client + app, + + such as a web frontend or mobile client, which grants access to the + Realtime API without + + leaking your main API key. You can configure a custom TTL for each + client secret. + + + You can also attach session configuration options to the client secret, + which will be + + applied to any sessions created using that client secret, but these can + also be overridden + + by the client connection. + + + [Learn more about authentication with client secrets over + WebRTC](/docs/guides/realtime-webrtc). + + + Returns the created client secret and the effective session object. The + client secret is a string that looks like `ek_1234`. + operationId: create-realtime-client-secret + tags: + - Realtime + requestBody: + description: Create a client secret with the given session configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RealtimeCreateClientSecretRequest' + responses: + '200': + description: Client secret created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/RealtimeCreateClientSecretResponse' + x-oaiMeta: + name: Create client secret + group: realtime + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/realtime/client_secrets \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "expires_after": { + "anchor": "created_at", + "seconds": 600 + }, + "session": { + "type": "realtime", + "model": "gpt-realtime", + "instructions": "You are a friendly assistant." + } + }' + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const clientSecret = await client.realtime.clientSecrets.create(); + + console.log(clientSecret.expires_at); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + client_secret = client.realtime.client_secrets.create() + print(client_secret.expires_at) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/realtime\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tclientSecret, err := client.Realtime.ClientSecrets.New(context.TODO(), realtime.ClientSecretNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", clientSecret.ExpiresAt)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.realtime.clientsecrets.ClientSecretCreateParams; + + import + com.openai.models.realtime.clientsecrets.ClientSecretCreateResponse; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ClientSecretCreateResponse clientSecret = client.realtime().clientSecrets().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + client_secret = openai.realtime.client_secrets.create + + puts(client_secret) + response: | + { + "value": "ek_68af296e8e408191a1120ab6383263c2", + "expires_at": 1756310470, + "session": { + "type": "realtime", + "object": "realtime.session", + "id": "sess_C9CiUVUzUzYIssh3ELY1d", + "model": "gpt-realtime", + "output_modalities": [ + "audio" + ], + "instructions": "You are a friendly assistant.", + "tools": [], + "tool_choice": "auto", + "max_output_tokens": "inf", + "tracing": null, + "truncation": "auto", + "prompt": null, + "expires_at": 0, + "audio": { + "input": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "transcription": null, + "noise_reduction": null, + "turn_detection": { + "type": "server_vad", + } + }, + "output": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "voice": "alloy", + "speed": 1.0 + } + }, + "include": null + } + } + /realtime/sessions: + post: + summary: > + Create an ephemeral API token for use in client-side applications with + the + + Realtime API. Can be configured with the same session parameters as the + + `session.update` client event. + + + It responds with a session object, plus a `client_secret` key which + contains + + a usable ephemeral API token that can be used to authenticate browser + clients + + for the Realtime API. + + + Returns the created Realtime session object, plus an ephemeral key. + operationId: create-realtime-session + tags: + - Realtime + requestBody: + description: Create an ephemeral API key with the given session configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RealtimeSessionCreateRequest' + responses: + '200': + description: Session created successfully. + content: + application/json: + schema: + $ref: '#/components/schemas/RealtimeSessionCreateResponse' + x-oaiMeta: + name: Create session + group: realtime + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/realtime/sessions \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "model": "gpt-realtime", + "modalities": ["audio", "text"], + "instructions": "You are a friendly assistant." + }' + response: | + { + "id": "sess_001", + "object": "realtime.session", + "model": "gpt-realtime-2025-08-25", + "modalities": ["audio", "text"], + "instructions": "You are a friendly assistant.", + "voice": "alloy", + "input_audio_format": "pcm16", + "output_audio_format": "pcm16", + "input_audio_transcription": { + "model": "whisper-1" + }, + "turn_detection": null, + "tools": [], + "tool_choice": "none", + "temperature": 0.7, + "max_response_output_tokens": 200, + "speed": 1.1, + "tracing": "auto", + "client_secret": { + "value": "ek_abc123", + "expires_at": 1234567890 + } + } + /realtime/transcription_sessions: + post: + summary: > + Create an ephemeral API token for use in client-side applications with + the + + Realtime API specifically for realtime transcriptions. + + Can be configured with the same session parameters as the + `transcription_session.update` client event. + + + It responds with a session object, plus a `client_secret` key which + contains + + a usable ephemeral API token that can be used to authenticate browser + clients + + for the Realtime API. + + + Returns the created Realtime transcription session object, plus an + ephemeral key. + operationId: create-realtime-transcription-session + tags: + - Realtime + requestBody: + description: Create an ephemeral API key with the given session configuration. + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequest' + responses: + '200': + description: Session created successfully. + content: + application/json: + schema: + $ref: >- + #/components/schemas/RealtimeTranscriptionSessionCreateResponse + x-oaiMeta: + name: Create transcription session + group: realtime + examples: + request: + curl: > + curl -X POST + https://api.openai.com/v1/realtime/transcription_sessions \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{}' + response: | + { + "id": "sess_BBwZc7cFV3XizEyKGDCGL", + "object": "realtime.transcription_session", + "modalities": ["audio", "text"], + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 200 + }, + "input_audio_format": "pcm16", + "input_audio_transcription": { + "model": "gpt-4o-transcribe", + "language": null, + "prompt": "" + }, + "client_secret": null + } + /responses: + post: + operationId: createResponse + tags: + - Responses + summary: > + Creates a model response. Provide [text](/docs/guides/text) or + + [image](/docs/guides/images) inputs to generate + [text](/docs/guides/text) + + or [JSON](/docs/guides/structured-outputs) outputs. Have the model call + + your own [custom code](/docs/guides/function-calling) or use built-in + + [tools](/docs/guides/tools) like [web + search](/docs/guides/tools-web-search) + + or [file search](/docs/guides/tools-file-search) to use your own data + + as input for the model's response. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateResponse' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Response' + text/event-stream: + schema: + $ref: '#/components/schemas/ResponseStreamEvent' + x-oaiMeta: + name: Create a model response + group: responses + path: create + examples: + - title: Text input + request: + curl: | + curl https://api.openai.com/v1/responses \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.4", + "input": "Tell me a three sentence bedtime story about a unicorn." + }' + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const response = await openai.responses.create({ + model: "gpt-5.4", + input: "Tell me a three sentence bedtime story about a unicorn." + }); + + console.log(response); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for response in client.responses.create(): + print(response) + csharp: > + using System; + + using OpenAI.Responses; + + + OpenAIResponseClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + OpenAIResponse response = client.CreateResponse("Tell me a three + sentence bedtime story about a unicorn."); + + + Console.WriteLine(response.GetOutputText()); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.responses.create(); + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.responses.create + + puts(response) + response: | + { + "id": "resp_67ccd2bed1ec8190b14f964abc0542670bb6a6b452d3795b", + "object": "response", + "created_at": 1741476542, + "status": "completed", + "completed_at": 1741476543, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-5.4", + "output": [ + { + "type": "message", + "id": "msg_67ccd2bf17f0819081ff3bb2cf6508e60bb6a6b452d3795b", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "In a peaceful grove beneath a silver moon, a unicorn named Lumina discovered a hidden pool that reflected the stars. As she dipped her horn into the water, the pool began to shimmer, revealing a pathway to a magical realm of endless night skies. Filled with wonder, Lumina whispered a wish for all who dream to find their own hidden magic, and as she glanced back, her hoofprints sparkled like stardust.", + "annotations": [] + } + ] + } + ], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "store": true, + "temperature": 1.0, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1.0, + "truncation": "disabled", + "usage": { + "input_tokens": 36, + "input_tokens_details": { + "cached_tokens": 0 + }, + "output_tokens": 87, + "output_tokens_details": { + "reasoning_tokens": 0 + }, + "total_tokens": 123 + }, + "user": null, + "metadata": {} + } + - title: Image input + request: + curl: | + curl https://api.openai.com/v1/responses \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.4", + "input": [ + { + "role": "user", + "content": [ + {"type": "input_text", "text": "what is in this image?"}, + { + "type": "input_image", + "image_url": "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg" + } + ] + } + ] + }' + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const response = await openai.responses.create({ + model: "gpt-5.4", + input: [ + { + role: "user", + content: [ + { type: "input_text", text: "what is in this image?" }, + { + type: "input_image", + image_url: + "https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg", + }, + ], + }, + ], + }); + + console.log(response); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for response in client.responses.create(): + print(response) + csharp: | + using System; + using System.Collections.Generic; + + using OpenAI.Responses; + + OpenAIResponseClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + List inputItems = + [ + ResponseItem.CreateUserMessageItem( + [ + ResponseContentPart.CreateInputTextPart("What is in this image?"), + ResponseContentPart.CreateInputImagePart(new Uri("https://upload.wikimedia.org/wikipedia/commons/thumb/d/dd/Gfp-wisconsin-madison-the-nature-boardwalk.jpg/2560px-Gfp-wisconsin-madison-the-nature-boardwalk.jpg")) + ] + ) + ]; + + OpenAIResponse response = client.CreateResponse(inputItems); + + Console.WriteLine(response.GetOutputText()); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.responses.create(); + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.responses.create + + puts(response) + response: | + { + "id": "resp_67ccd3a9da748190baa7f1570fe91ac604becb25c45c1d41", + "object": "response", + "created_at": 1741476777, + "status": "completed", + "completed_at": 1741476778, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-5.4", + "output": [ + { + "type": "message", + "id": "msg_67ccd3acc8d48190a77525dc6de64b4104becb25c45c1d41", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "The image depicts a scenic landscape with a wooden boardwalk or pathway leading through lush, green grass under a blue sky with some clouds. The setting suggests a peaceful natural area, possibly a park or nature reserve. There are trees and shrubs in the background.", + "annotations": [] + } + ] + } + ], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "store": true, + "temperature": 1.0, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1.0, + "truncation": "disabled", + "usage": { + "input_tokens": 328, + "input_tokens_details": { + "cached_tokens": 0 + }, + "output_tokens": 52, + "output_tokens_details": { + "reasoning_tokens": 0 + }, + "total_tokens": 380 + }, + "user": null, + "metadata": {} + } + - title: File input + request: + curl: | + curl https://api.openai.com/v1/responses \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.4", + "input": [ + { + "role": "user", + "content": [ + {"type": "input_text", "text": "what is in this file?"}, + { + "type": "input_file", + "file_url": "https://www.berkshirehathaway.com/letters/2024ltr.pdf" + } + ] + } + ] + }' + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const response = await openai.responses.create({ + model: "gpt-5.4", + input: [ + { + role: "user", + content: [ + { type: "input_text", text: "what is in this file?" }, + { + type: "input_file", + file_url: "https://www.berkshirehathaway.com/letters/2024ltr.pdf", + }, + ], + }, + ], + }); + + console.log(response); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for response in client.responses.create(): + print(response) + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.responses.create(); + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.responses.create + + puts(response) + response: | + { + "id": "resp_686eef60237881a2bd1180bb8b13de430e34c516d176ff86", + "object": "response", + "created_at": 1752100704, + "status": "completed", + "completed_at": 1752100705, + "background": false, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "max_tool_calls": null, + "model": "gpt-5.4", + "output": [ + { + "id": "msg_686eef60d3e081a29283bdcbc4322fd90e34c516d176ff86", + "type": "message", + "status": "completed", + "content": [ + { + "type": "output_text", + "annotations": [], + "logprobs": [], + "text": "The file seems to contain excerpts from a letter to the shareholders of Berkshire Hathaway Inc., likely written by Warren Buffett. It covers several topics:\n\n1. **Communication Philosophy**: Buffett emphasizes the importance of transparency and candidness in reporting mistakes and successes to shareholders.\n\n2. **Mistakes and Learnings**: The letter acknowledges past mistakes in business assessments and management hires, highlighting the importance of correcting errors promptly.\n\n3. **CEO Succession**: Mention of Greg Abel stepping in as the new CEO and continuing the tradition of honest communication.\n\n4. **Pete Liegl Story**: A detailed account of acquiring Forest River and the relationship with its founder, highlighting trust and effective business decisions.\n\n5. **2024 Performance**: Overview of business performance, particularly in insurance and investment activities, with a focus on GEICO's improvement.\n\n6. **Tax Contributions**: Discussion of significant tax payments to the U.S. Treasury, credited to shareholders' reinvestments.\n\n7. **Investment Strategy**: A breakdown of Berkshire\u2019s investments in both controlled subsidiaries and marketable equities, along with a focus on long-term holding strategies.\n\n8. **American Capitalism**: Reflections on America\u2019s economic development and Berkshire\u2019s role within it.\n\n9. **Property-Casualty Insurance**: Insights into the P/C insurance business model and its challenges and benefits.\n\n10. **Japanese Investments**: Information about Berkshire\u2019s investments in Japanese companies and future plans.\n\n11. **Annual Meeting**: Details about the upcoming annual gathering in Omaha, including schedule changes and new book releases.\n\n12. **Personal Anecdotes**: Light-hearted stories about family and interactions, conveying Buffett's personable approach.\n\n13. **Financial Performance Data**: Tables comparing Berkshire\u2019s annual performance to the S&P 500, showing impressive long-term gains.\n\nOverall, the letter reinforces Berkshire Hathaway's commitment to transparency, investment in both its businesses and the wider economy, and emphasizes strong leadership and prudent financial management." + } + ], + "role": "assistant" + } + ], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "service_tier": "default", + "store": true, + "temperature": 1.0, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_logprobs": 0, + "top_p": 1.0, + "truncation": "disabled", + "usage": { + "input_tokens": 8438, + "input_tokens_details": { + "cached_tokens": 0 + }, + "output_tokens": 398, + "output_tokens_details": { + "reasoning_tokens": 0 + }, + "total_tokens": 8836 + }, + "user": null, + "metadata": {} + } + - title: Web search + request: + curl: | + curl https://api.openai.com/v1/responses \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.4", + "tools": [{ "type": "web_search_preview" }], + "input": "What was a positive news story from today?" + }' + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const response = await openai.responses.create({ + model: "gpt-5.4", + tools: [{ type: "web_search_preview" }], + input: "What was a positive news story from today?", + }); + + console.log(response); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for response in client.responses.create(): + print(response) + csharp: > + using System; + + + using OpenAI.Responses; + + + OpenAIResponseClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + string userInputText = "What was a positive news story from + today?"; + + + ResponseCreationOptions options = new() + + { + Tools = + { + ResponseTool.CreateWebSearchTool() + }, + }; + + + OpenAIResponse response = client.CreateResponse(userInputText, + options); + + + Console.WriteLine(response.GetOutputText()); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.responses.create(); + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.responses.create + + puts(response) + response: | + { + "id": "resp_67ccf18ef5fc8190b16dbee19bc54e5f087bb177ab789d5c", + "object": "response", + "created_at": 1741484430, + "status": "completed", + "completed_at": 1741484431, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-5.4", + "output": [ + { + "type": "web_search_call", + "id": "ws_67ccf18f64008190a39b619f4c8455ef087bb177ab789d5c", + "status": "completed" + }, + { + "type": "message", + "id": "msg_67ccf190ca3881909d433c50b1f6357e087bb177ab789d5c", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "As of today, March 9, 2025, one notable positive news story...", + "annotations": [ + { + "type": "url_citation", + "start_index": 442, + "end_index": 557, + "url": "https://.../?utm_source=chatgpt.com", + "title": "..." + }, + { + "type": "url_citation", + "start_index": 962, + "end_index": 1077, + "url": "https://.../?utm_source=chatgpt.com", + "title": "..." + }, + { + "type": "url_citation", + "start_index": 1336, + "end_index": 1451, + "url": "https://.../?utm_source=chatgpt.com", + "title": "..." + } + ] + } + ] + } + ], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "store": true, + "temperature": 1.0, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [ + { + "type": "web_search_preview", + "domains": [], + "search_context_size": "medium", + "user_location": { + "type": "approximate", + "city": null, + "country": "US", + "region": null, + "timezone": null + } + } + ], + "top_p": 1.0, + "truncation": "disabled", + "usage": { + "input_tokens": 328, + "input_tokens_details": { + "cached_tokens": 0 + }, + "output_tokens": 356, + "output_tokens_details": { + "reasoning_tokens": 0 + }, + "total_tokens": 684 + }, + "user": null, + "metadata": {} + } + - title: File search + request: + curl: | + curl https://api.openai.com/v1/responses \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.4", + "tools": [{ + "type": "file_search", + "vector_store_ids": ["vs_1234567890"], + "max_num_results": 20 + }], + "input": "What are the attributes of an ancient brown dragon?" + }' + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const response = await openai.responses.create({ + model: "gpt-5.4", + tools: [{ + type: "file_search", + vector_store_ids: ["vs_1234567890"], + max_num_results: 20 + }], + input: "What are the attributes of an ancient brown dragon?", + }); + + console.log(response); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for response in client.responses.create(): + print(response) + csharp: > + using System; + + + using OpenAI.Responses; + + + OpenAIResponseClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + string userInputText = "What are the attributes of an ancient + brown dragon?"; + + + ResponseCreationOptions options = new() + + { + Tools = + { + ResponseTool.CreateFileSearchTool( + vectorStoreIds: ["vs_1234567890"], + maxResultCount: 20 + ) + }, + }; + + + OpenAIResponse response = client.CreateResponse(userInputText, + options); + + + Console.WriteLine(response.GetOutputText()); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.responses.create(); + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.responses.create + + puts(response) + response: | + { + "id": "resp_67ccf4c55fc48190b71bd0463ad3306d09504fb6872380d7", + "object": "response", + "created_at": 1741485253, + "status": "completed", + "completed_at": 1741485254, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-5.4", + "output": [ + { + "type": "file_search_call", + "id": "fs_67ccf4c63cd08190887ef6464ba5681609504fb6872380d7", + "status": "completed", + "queries": [ + "attributes of an ancient brown dragon" + ], + "results": null + }, + { + "type": "message", + "id": "msg_67ccf4c93e5c81909d595b369351a9d309504fb6872380d7", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "The attributes of an ancient brown dragon include...", + "annotations": [ + { + "type": "file_citation", + "index": 320, + "file_id": "file-4wDz5b167pAf72nx1h9eiN", + "filename": "dragons.pdf" + }, + { + "type": "file_citation", + "index": 576, + "file_id": "file-4wDz5b167pAf72nx1h9eiN", + "filename": "dragons.pdf" + }, + { + "type": "file_citation", + "index": 815, + "file_id": "file-4wDz5b167pAf72nx1h9eiN", + "filename": "dragons.pdf" + }, + { + "type": "file_citation", + "index": 815, + "file_id": "file-4wDz5b167pAf72nx1h9eiN", + "filename": "dragons.pdf" + }, + { + "type": "file_citation", + "index": 1030, + "file_id": "file-4wDz5b167pAf72nx1h9eiN", + "filename": "dragons.pdf" + }, + { + "type": "file_citation", + "index": 1030, + "file_id": "file-4wDz5b167pAf72nx1h9eiN", + "filename": "dragons.pdf" + }, + { + "type": "file_citation", + "index": 1156, + "file_id": "file-4wDz5b167pAf72nx1h9eiN", + "filename": "dragons.pdf" + }, + { + "type": "file_citation", + "index": 1225, + "file_id": "file-4wDz5b167pAf72nx1h9eiN", + "filename": "dragons.pdf" + } + ] + } + ] + } + ], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "store": true, + "temperature": 1.0, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [ + { + "type": "file_search", + "filters": null, + "max_num_results": 20, + "ranking_options": { + "ranker": "auto", + "score_threshold": 0.0 + }, + "vector_store_ids": [ + "vs_1234567890" + ] + } + ], + "top_p": 1.0, + "truncation": "disabled", + "usage": { + "input_tokens": 18307, + "input_tokens_details": { + "cached_tokens": 0 + }, + "output_tokens": 348, + "output_tokens_details": { + "reasoning_tokens": 0 + }, + "total_tokens": 18655 + }, + "user": null, + "metadata": {} + } + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/responses \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.4", + "instructions": "You are a helpful assistant.", + "input": "Hello!", + "stream": true + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for response in client.responses.create(): + print(response) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const response = await openai.responses.create({ + model: "gpt-5.4", + instructions: "You are a helpful assistant.", + input: "Hello!", + stream: true, + }); + + for await (const event of response) { + console.log(event); + } + csharp: > + using System; + + using System.ClientModel; + + using System.Threading.Tasks; + + + using OpenAI.Responses; + + + OpenAIResponseClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + string userInputText = "Hello!"; + + + ResponseCreationOptions options = new() + + { + Instructions = "You are a helpful assistant.", + }; + + + AsyncCollectionResult responseUpdates = + client.CreateResponseStreamingAsync(userInputText, options); + + + await foreach (StreamingResponseUpdate responseUpdate in + responseUpdates) + + { + if (responseUpdate is StreamingResponseOutputTextDeltaUpdate outputTextDeltaUpdate) + { + Console.Write(outputTextDeltaUpdate.Delta); + } + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.responses.create(); + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.responses.create + + puts(response) + response: > + event: response.created + + data: + {"type":"response.created","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"in_progress","error":null,"incomplete_details":null,"instructions":"You + are a helpful + assistant.","max_output_tokens":null,"model":"gpt-5.4","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}} + + + event: response.in_progress + + data: + {"type":"response.in_progress","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"in_progress","error":null,"incomplete_details":null,"instructions":"You + are a helpful + assistant.","max_output_tokens":null,"model":"gpt-5.4","output":[],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":null,"user":null,"metadata":{}}} + + + event: response.output_item.added + + data: + {"type":"response.output_item.added","output_index":0,"item":{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"in_progress","role":"assistant","content":[]}} + + + event: response.content_part.added + + data: + {"type":"response.content_part.added","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"part":{"type":"output_text","text":"","annotations":[]}} + + + event: response.output_text.delta + + data: + {"type":"response.output_text.delta","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"delta":"Hi"} + + + ... + + + event: response.output_text.done + + data: + {"type":"response.output_text.done","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"text":"Hi + there! How can I assist you today?"} + + + event: response.content_part.done + + data: + {"type":"response.content_part.done","item_id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","output_index":0,"content_index":0,"part":{"type":"output_text","text":"Hi + there! How can I assist you today?","annotations":[]}} + + + event: response.output_item.done + + data: + {"type":"response.output_item.done","output_index":0,"item":{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Hi + there! How can I assist you today?","annotations":[]}]}} + + + event: response.completed + + data: + {"type":"response.completed","response":{"id":"resp_67c9fdcecf488190bdd9a0409de3a1ec07b8b0ad4e5eb654","object":"response","created_at":1741290958,"status":"completed","error":null,"incomplete_details":null,"instructions":"You + are a helpful + assistant.","max_output_tokens":null,"model":"gpt-5.4","output":[{"id":"msg_67c9fdcf37fc8190ba82116e33fb28c507b8b0ad4e5eb654","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"Hi + there! How can I assist you + today?","annotations":[]}]}],"parallel_tool_calls":true,"previous_response_id":null,"reasoning":{"effort":null,"summary":null},"store":true,"temperature":1.0,"text":{"format":{"type":"text"}},"tool_choice":"auto","tools":[],"top_p":1.0,"truncation":"disabled","usage":{"input_tokens":37,"output_tokens":11,"output_tokens_details":{"reasoning_tokens":0},"total_tokens":48},"user":null,"metadata":{}}} + - title: Functions + request: + curl: | + curl https://api.openai.com/v1/responses \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.4", + "input": "What is the weather like in Boston today?", + "tools": [ + { + "type": "function", + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"] + } + }, + "required": ["location", "unit"] + } + } + ], + "tool_choice": "auto" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for response in client.responses.create(): + print(response) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const tools = [ + { + type: "function", + name: "get_current_weather", + description: "Get the current weather in a given location", + parameters: { + type: "object", + properties: { + location: { + type: "string", + description: "The city and state, e.g. San Francisco, CA", + }, + unit: { type: "string", enum: ["celsius", "fahrenheit"] }, + }, + required: ["location", "unit"], + }, + }, + ]; + + const response = await openai.responses.create({ + model: "gpt-5.4", + tools: tools, + input: "What is the weather like in Boston today?", + tool_choice: "auto", + }); + + console.log(response); + csharp: > + using System; + + using OpenAI.Responses; + + + OpenAIResponseClient client = new( + model: "gpt-5.4", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + ResponseTool getCurrentWeatherFunctionTool = + ResponseTool.CreateFunctionTool( + functionName: "get_current_weather", + functionDescription: "Get the current weather in a given location", + functionParameters: BinaryData.FromString(""" + { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]} + }, + "required": ["location", "unit"] + } + """ + ) + ); + + + string userInputText = "What is the weather like in Boston + today?"; + + + ResponseCreationOptions options = new() + + { + Tools = + { + getCurrentWeatherFunctionTool + }, + ToolChoice = ResponseToolChoice.CreateAutoChoice(), + }; + + + OpenAIResponse response = client.CreateResponse(userInputText, + options); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.responses.create(); + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.responses.create + + puts(response) + response: | + { + "id": "resp_67ca09c5efe0819096d0511c92b8c890096610f474011cc0", + "object": "response", + "created_at": 1741294021, + "status": "completed", + "completed_at": 1741294022, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-5.4", + "output": [ + { + "type": "function_call", + "id": "fc_67ca09c6bedc8190a7abfec07b1a1332096610f474011cc0", + "call_id": "call_unLAR8MvFNptuiZK6K6HCy5k", + "name": "get_current_weather", + "arguments": "{\"location\":\"Boston, MA\",\"unit\":\"celsius\"}", + "status": "completed" + } + ], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "store": true, + "temperature": 1.0, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [ + { + "type": "function", + "description": "Get the current weather in a given location", + "name": "get_current_weather", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": [ + "celsius", + "fahrenheit" + ] + } + }, + "required": [ + "location", + "unit" + ] + }, + "strict": true + } + ], + "top_p": 1.0, + "truncation": "disabled", + "usage": { + "input_tokens": 291, + "output_tokens": 23, + "output_tokens_details": { + "reasoning_tokens": 0 + }, + "total_tokens": 314 + }, + "user": null, + "metadata": {} + } + - title: Reasoning + request: + curl: | + curl https://api.openai.com/v1/responses \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "o3-mini", + "input": "How much wood would a woodchuck chuck?", + "reasoning": { + "effort": "high" + } + }' + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + const response = await openai.responses.create({ + model: "o3-mini", + input: "How much wood would a woodchuck chuck?", + reasoning: { + effort: "high" + } + }); + + console.log(response); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for response in client.responses.create(): + print(response) + csharp: > + using System; + + using OpenAI.Responses; + + + OpenAIResponseClient client = new( + model: "o3-mini", + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + string userInputText = "How much wood would a woodchuck chuck?"; + + + ResponseCreationOptions options = new() + + { + ReasoningOptions = new() + { + ReasoningEffortLevel = ResponseReasoningEffortLevel.High, + }, + }; + + + OpenAIResponse response = client.CreateResponse(userInputText, + options); + + + Console.WriteLine(response.GetOutputText()); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.responses.create(); + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.New(context.TODO(), responses.ResponseNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.responses.create + + puts(response) + response: | + { + "id": "resp_67ccd7eca01881908ff0b5146584e408072912b2993db808", + "object": "response", + "created_at": 1741477868, + "status": "completed", + "completed_at": 1741477869, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "o1-2024-12-17", + "output": [ + { + "type": "message", + "id": "msg_67ccd7f7b5848190a6f3e95d809f6b44072912b2993db808", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "The classic tongue twister...", + "annotations": [] + } + ] + } + ], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": "high", + "summary": null + }, + "store": true, + "temperature": 1.0, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1.0, + "truncation": "disabled", + "usage": { + "input_tokens": 81, + "input_tokens_details": { + "cached_tokens": 0 + }, + "output_tokens": 1035, + "output_tokens_details": { + "reasoning_tokens": 832 + }, + "total_tokens": 1116 + }, + "user": null, + "metadata": {} + } + /responses/{response_id}: + get: + operationId: getResponse + tags: + - Responses + summary: | + Retrieves a model response with the given ID. + parameters: + - in: path + name: response_id + required: true + schema: + type: string + example: resp_677efb5139a88190b512bc3fef8e535d + description: The ID of the response to retrieve. + - in: query + name: include + schema: + type: array + items: + $ref: '#/components/schemas/IncludeEnum' + description: | + Additional fields to include in the response. See the `include` + parameter for Response creation above for more information. + - in: query + name: stream + schema: + type: boolean + description: > + 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. + - in: query + name: starting_after + schema: + type: integer + description: | + The sequence number of the event after which to start streaming. + - in: query + name: include_obfuscation + schema: + type: boolean + description: > + When true, stream obfuscation will be enabled. Stream obfuscation + adds + + random characters to an `obfuscation` field on streaming delta + events + + to normalize payload sizes as a mitigation to certain side-channel + + attacks. These obfuscation fields are included by default, but add a + + small amount of overhead to the data stream. You can set + + `include_obfuscation` to false to optimize for bandwidth if you + trust + + the network links between your application and the OpenAI API. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Response' + x-oaiMeta: + name: Get a model response + group: responses + examples: + request: + curl: | + curl https://api.openai.com/v1/responses/resp_123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: | + import OpenAI from "openai"; + const client = new OpenAI(); + + const response = await client.responses.retrieve("resp_123"); + console.log(response); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for response in client.responses.retrieve( + response_id="resp_677efb5139a88190b512bc3fef8e535d", + ): + print(response) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const response = await + client.responses.retrieve('resp_677efb5139a88190b512bc3fef8e535d'); + + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.Get(\n\t\tcontext.TODO(),\n\t\t\"resp_677efb5139a88190b512bc3fef8e535d\",\n\t\tresponses.ResponseGetParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().retrieve("resp_677efb5139a88190b512bc3fef8e535d"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + response = + openai.responses.retrieve("resp_677efb5139a88190b512bc3fef8e535d") + + + puts(response) + response: | + { + "id": "resp_67cb71b351908190a308f3859487620d06981a8637e6bc44", + "object": "response", + "created_at": 1741386163, + "status": "completed", + "completed_at": 1741386164, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-4o-2024-08-06", + "output": [ + { + "type": "message", + "id": "msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Silent circuits hum, \nThoughts emerge in data streams— \nDigital dawn breaks.", + "annotations": [] + } + ] + } + ], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "store": true, + "temperature": 1.0, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1.0, + "truncation": "disabled", + "usage": { + "input_tokens": 32, + "input_tokens_details": { + "cached_tokens": 0 + }, + "output_tokens": 18, + "output_tokens_details": { + "reasoning_tokens": 0 + }, + "total_tokens": 50 + }, + "user": null, + "metadata": {} + } + delete: + operationId: deleteResponse + tags: + - Responses + summary: | + Deletes a model response with the given ID. + parameters: + - in: path + name: response_id + required: true + schema: + type: string + example: resp_677efb5139a88190b512bc3fef8e535d + description: The ID of the response to delete. + responses: + '200': + description: OK + '404': + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + x-oaiMeta: + name: Delete a model response + group: responses + examples: + request: + curl: | + curl -X DELETE https://api.openai.com/v1/responses/resp_123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: | + import OpenAI from "openai"; + const client = new OpenAI(); + + const response = await client.responses.delete("resp_123"); + console.log(response); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + client.responses.delete( + "resp_677efb5139a88190b512bc3fef8e535d", + ) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + await + client.responses.delete('resp_677efb5139a88190b512bc3fef8e535d'); + go: "package main\n\nimport (\n\t\"context\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\terr := client.Responses.Delete(context.TODO(), \"resp_677efb5139a88190b512bc3fef8e535d\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.ResponseDeleteParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + client.responses().delete("resp_677efb5139a88190b512bc3fef8e535d"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + result = + openai.responses.delete("resp_677efb5139a88190b512bc3fef8e535d") + + + puts(result) + response: | + { + "id": "resp_6786a1bec27481909a17d673315b29f6", + "object": "response", + "deleted": true + } + /responses/{response_id}/cancel: + post: + operationId: cancelResponse + tags: + - Responses + summary: | + Cancels a model response with the given ID. Only responses created with + the `background` parameter set to `true` can be cancelled. + [Learn more](/docs/guides/background). + parameters: + - in: path + name: response_id + required: true + schema: + type: string + example: resp_677efb5139a88190b512bc3fef8e535d + description: The ID of the response to cancel. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Response' + '404': + description: Not Found + content: + application/json: + schema: + $ref: '#/components/schemas/Error' + x-oaiMeta: + name: Cancel a response + group: responses + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/responses/resp_123/cancel \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: | + import OpenAI from "openai"; + const client = new OpenAI(); + + const response = await client.responses.cancel("resp_123"); + console.log(response); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.responses.cancel( + "resp_677efb5139a88190b512bc3fef8e535d", + ) + print(response.id) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const response = await + client.responses.cancel('resp_677efb5139a88190b512bc3fef8e535d'); + + + console.log(response.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.Cancel(context.TODO(), \"resp_677efb5139a88190b512bc3fef8e535d\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.Response; + import com.openai.models.responses.ResponseCancelParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Response response = client.responses().cancel("resp_677efb5139a88190b512bc3fef8e535d"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + response = + openai.responses.cancel("resp_677efb5139a88190b512bc3fef8e535d") + + + puts(response) + response: | + { + "id": "resp_67cb71b351908190a308f3859487620d06981a8637e6bc44", + "object": "response", + "created_at": 1741386163, + "status": "cancelled", + "background": true, + "completed_at": null, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-4o-2024-08-06", + "output": [ + { + "type": "message", + "id": "msg_67cb71b3c2b0819084d481baaaf148f206981a8637e6bc44", + "status": "in_progress", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "Silent circuits hum, \nThoughts emerge in data streams— \nDigital dawn breaks.", + "annotations": [] + } + ] + } + ], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "store": true, + "temperature": 1.0, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1.0, + "truncation": "disabled", + "usage": null, + "user": null, + "metadata": {} + } + /responses/{response_id}/input_items: + get: + operationId: listInputItems + tags: + - Responses + summary: Returns a list of input items for a given response. + parameters: + - in: path + name: response_id + required: true + schema: + type: string + description: The ID of the response to retrieve input items for. + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between + + 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - in: query + name: order + schema: + type: string + enum: + - asc + - desc + description: | + The order to return the input items in. Default is `desc`. + - `asc`: Return the input items in ascending order. + - `desc`: Return the input items in descending order. + - in: query + name: after + schema: + type: string + description: | + An item ID to list items after, used in pagination. + - in: query + name: include + schema: + type: array + items: + $ref: '#/components/schemas/IncludeEnum' + description: | + Additional fields to include in the response. See the `include` + parameter for Response creation above for more information. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ResponseItemList' + x-oaiMeta: + name: List input items + group: responses + examples: + request: + curl: | + curl https://api.openai.com/v1/responses/resp_abc123/input_items \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: > + import OpenAI from "openai"; + + const client = new OpenAI(); + + + const response = await + client.responses.inputItems.list("resp_123"); + + console.log(response.data); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.responses.input_items.list( + response_id="response_id", + ) + page = page.data[0] + print(page) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const responseItem of + client.responses.inputItems.list('response_id')) { + console.log(responseItem); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Responses.InputItems.List(\n\t\tcontext.TODO(),\n\t\t\"response_id\",\n\t\tresponses.InputItemListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.inputitems.InputItemListPage; + import com.openai.models.responses.inputitems.InputItemListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + InputItemListPage page = client.responses().inputItems().list("response_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.responses.input_items.list("response_id") + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "msg_abc123", + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "Tell me a three sentence bedtime story about a unicorn." + } + ] + } + ], + "first_id": "msg_abc123", + "last_id": "msg_abc123", + "has_more": false + } + /threads: + post: + operationId: createThread + tags: + - Assistants + summary: Create a thread. + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CreateThreadRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ThreadObject' + x-oaiMeta: + name: Create thread + group: threads + beta: true + examples: + - title: Empty + request: + curl: | + curl https://api.openai.com/v1/threads \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + thread = client.beta.threads.create() + print(thread.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const emptyThread = await openai.beta.threads.create(); + + console.log(emptyThread); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const thread = await client.beta.threads.create(); + + console.log(thread.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tthread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", thread.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.Thread; + import com.openai.models.beta.threads.ThreadCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Thread thread = client.beta().threads().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + thread = openai.beta.threads.create + + puts(thread) + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699012949, + "metadata": {}, + "tool_resources": {} + } + - title: Messages + request: + curl: | + curl https://api.openai.com/v1/threads \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "messages": [{ + "role": "user", + "content": "Hello, what is AI?" + }, { + "role": "user", + "content": "How does AI work? Explain it in simple terms." + }] + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + thread = client.beta.threads.create() + print(thread.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const messageThread = await openai.beta.threads.create({ + messages: [ + { + role: "user", + content: "Hello, what is AI?" + }, + { + role: "user", + content: "How does AI work? Explain it in simple terms.", + }, + ], + }); + + console.log(messageThread); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const thread = await client.beta.threads.create(); + + console.log(thread.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tthread, err := client.Beta.Threads.New(context.TODO(), openai.BetaThreadNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", thread.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.Thread; + import com.openai.models.beta.threads.ThreadCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Thread thread = client.beta().threads().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + thread = openai.beta.threads.create + + puts(thread) + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699014083, + "metadata": {}, + "tool_resources": {} + } + /threads/runs: + post: + operationId: createThreadAndRun + tags: + - Assistants + summary: Create a thread and run it in one request. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateThreadAndRunRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/RunObject' + x-oaiMeta: + name: Create thread and run + group: threads + beta: true + examples: + - title: Default + request: + curl: | + curl https://api.openai.com/v1/threads/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_abc123", + "thread": { + "messages": [ + {"role": "user", "content": "Explain deep learning to a 5 year old."} + ] + } + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for thread in client.beta.threads.create_and_run( + assistant_id="assistant_id", + ): + print(thread) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.createAndRun({ + assistant_id: "asst_abc123", + thread: { + messages: [ + { role: "user", content: "Explain deep learning to a 5 year old." }, + ], + }, + }); + + console.log(run); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.beta.threads.createAndRun({ + assistant_id: 'assistant_id' }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{\n\t\tAssistantID: \"assistant_id\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.ThreadCreateAndRunParams; + import com.openai.models.beta.threads.runs.Run; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder() + .assistantId("assistant_id") + .build(); + Run run = client.beta().threads().createAndRun(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.create_and_run(assistant_id: + "assistant_id") + + + puts(run) + response: | + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699076792, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "queued", + "started_at": null, + "expires_at": 1699077392, + "cancelled_at": null, + "failed_at": null, + "completed_at": null, + "required_action": null, + "last_error": null, + "model": "gpt-4o", + "instructions": "You are a helpful assistant.", + "tools": [], + "tool_resources": {}, + "metadata": {}, + "temperature": 1.0, + "top_p": 1.0, + "max_completion_tokens": null, + "max_prompt_tokens": null, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "incomplete_details": null, + "usage": null, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/threads/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_123", + "thread": { + "messages": [ + {"role": "user", "content": "Hello"} + ] + }, + "stream": true + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for thread in client.beta.threads.create_and_run( + assistant_id="assistant_id", + ): + print(thread) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const stream = await openai.beta.threads.createAndRun({ + assistant_id: "asst_123", + thread: { + messages: [ + { role: "user", content: "Hello" }, + ], + }, + stream: true + }); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.beta.threads.createAndRun({ + assistant_id: 'assistant_id' }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{\n\t\tAssistantID: \"assistant_id\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.ThreadCreateAndRunParams; + import com.openai.models.beta.threads.runs.Run; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder() + .assistantId("assistant_id") + .build(); + Run run = client.beta().threads().createAndRun(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.create_and_run(assistant_id: + "assistant_id") + + + puts(run) + response: > + event: thread.created + + data: + {"id":"thread_123","object":"thread","created_at":1710348075,"metadata":{}} + + + event: thread.run.created + + data: + {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} + + + event: thread.run.queued + + data: + {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} + + + event: thread.run.in_progress + + data: + {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"tool_resources":{},"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} + + + event: thread.run.step.created + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} + + + event: thread.run.step.in_progress + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} + + + event: thread.message.created + + data: + {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], + "metadata":{}} + + + event: thread.message.in_progress + + data: + {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[], + "metadata":{}} + + + event: thread.message.delta + + data: + {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} + + + ... + + + event: thread.message.delta + + data: + {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" + today"}}]}} + + + event: thread.message.delta + + data: + {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} + + + event: thread.message.completed + + data: + {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! + How can I assist you today?","annotations":[]}}], "metadata":{}} + + + event: thread.run.step.completed + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} + + + event: thread.run.completed + + {"id":"run_123","object":"thread.run","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1713226836,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1713226837,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true} + + + event: done + + data: [DONE] + - title: Streaming with Functions + request: + curl: | + curl https://api.openai.com/v1/threads/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_abc123", + "thread": { + "messages": [ + {"role": "user", "content": "What is the weather like in San Francisco?"} + ] + }, + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"] + } + }, + "required": ["location"] + } + } + } + ], + "stream": true + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for thread in client.beta.threads.create_and_run( + assistant_id="assistant_id", + ): + print(thread) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + } + } + ]; + + async function main() { + const stream = await openai.beta.threads.createAndRun({ + assistant_id: "asst_123", + thread: { + messages: [ + { role: "user", content: "What is the weather like in San Francisco?" }, + ], + }, + tools: tools, + stream: true + }); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.beta.threads.createAndRun({ + assistant_id: 'assistant_id' }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.NewAndRun(context.TODO(), openai.BetaThreadNewAndRunParams{\n\t\tAssistantID: \"assistant_id\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.ThreadCreateAndRunParams; + import com.openai.models.beta.threads.runs.Run; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ThreadCreateAndRunParams params = ThreadCreateAndRunParams.builder() + .assistantId("assistant_id") + .build(); + Run run = client.beta().threads().createAndRun(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.create_and_run(assistant_id: + "assistant_id") + + + puts(run) + response: > + event: thread.created + + data: + {"id":"thread_123","object":"thread","created_at":1710351818,"metadata":{}} + + + event: thread.run.created + + data: + {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get + the current weather in a given + location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The + city and state, e.g. San Francisco, + CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.queued + + data: + {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get + the current weather in a given + location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The + city and state, e.g. San Francisco, + CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.in_progress + + data: + {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get + the current weather in a given + location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The + city and state, e.g. San Francisco, + CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.step.created + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null} + + + event: thread.run.step.in_progress + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710351819,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710352418,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[]},"usage":null} + + + event: thread.run.step.delta + + data: + {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"","output":null}}]}}} + + + event: thread.run.step.delta + + data: + {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"{\""}}]}}} + + + event: thread.run.step.delta + + data: + {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"location"}}]}}} + + + ... + + + event: thread.run.step.delta + + data: + {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"ahrenheit"}}]}}} + + + event: thread.run.step.delta + + data: + {"id":"step_001","object":"thread.run.step.delta","delta":{"step_details":{"type":"tool_calls","tool_calls":[{"index":0,"type":"function","function":{"arguments":"\"}"}}]}}} + + + event: thread.run.requires_action + + data: + {"id":"run_123","object":"thread.run","created_at":1710351818,"assistant_id":"asst_123","thread_id":"thread_123","status":"requires_action","started_at":1710351818,"expires_at":1710352418,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":{"type":"submit_tool_outputs","submit_tool_outputs":{"tool_calls":[{"id":"call_XXNp8YGaFrjrSjgqxtC8JJ1B","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San + Francisco, + CA\",\"unit\":\"fahrenheit\"}"}}]}},"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get + the current weather in a given + location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The + city and state, e.g. San Francisco, + CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":345,"completion_tokens":11,"total_tokens":356},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: done + + data: [DONE] + /threads/{thread_id}: + get: + operationId: getThread + tags: + - Assistants + summary: Retrieves a thread. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to retrieve. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ThreadObject' + x-oaiMeta: + name: Retrieve thread + group: threads + beta: true + examples: + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + thread = client.beta.threads.retrieve( + "thread_id", + ) + print(thread.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const myThread = await openai.beta.threads.retrieve( + "thread_abc123" + ); + + console.log(myThread); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const thread = await client.beta.threads.retrieve('thread_id'); + + console.log(thread.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tthread, err := client.Beta.Threads.Get(context.TODO(), \"thread_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", thread.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.Thread; + import com.openai.models.beta.threads.ThreadRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Thread thread = client.beta().threads().retrieve("thread_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + thread = openai.beta.threads.retrieve("thread_id") + + puts(thread) + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699014083, + "metadata": {}, + "tool_resources": { + "code_interpreter": { + "file_ids": [] + } + } + } + post: + operationId: modifyThread + tags: + - Assistants + summary: Modifies a thread. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to modify. Only the `metadata` can be modified. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ModifyThreadRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ThreadObject' + x-oaiMeta: + name: Modify thread + group: threads + beta: true + examples: + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "metadata": { + "modified": "true", + "user": "abc123" + } + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + thread = client.beta.threads.update( + thread_id="thread_id", + ) + print(thread.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const updatedThread = await openai.beta.threads.update( + "thread_abc123", + { + metadata: { modified: "true", user: "abc123" }, + } + ); + + console.log(updatedThread); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const thread = await client.beta.threads.update('thread_id'); + + console.log(thread.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tthread, err := client.Beta.Threads.Update(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\topenai.BetaThreadUpdateParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", thread.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.Thread; + import com.openai.models.beta.threads.ThreadUpdateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Thread thread = client.beta().threads().update("thread_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + thread = openai.beta.threads.update("thread_id") + + puts(thread) + response: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1699014083, + "metadata": { + "modified": "true", + "user": "abc123" + }, + "tool_resources": {} + } + delete: + operationId: deleteThread + tags: + - Assistants + summary: Delete a thread. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to delete. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteThreadResponse' + x-oaiMeta: + name: Delete thread + group: threads + beta: true + examples: + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -X DELETE + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + thread_deleted = client.beta.threads.delete( + "thread_id", + ) + print(thread_deleted.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const response = await openai.beta.threads.delete("thread_abc123"); + + console.log(response); + } + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const threadDeleted = await + client.beta.threads.delete('thread_id'); + + + console.log(threadDeleted.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tthreadDeleted, err := client.Beta.Threads.Delete(context.TODO(), \"thread_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", threadDeleted.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.ThreadDeleteParams; + import com.openai.models.beta.threads.ThreadDeleted; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ThreadDeleted threadDeleted = client.beta().threads().delete("thread_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + thread_deleted = openai.beta.threads.delete("thread_id") + + puts(thread_deleted) + response: | + { + "id": "thread_abc123", + "object": "thread.deleted", + "deleted": true + } + /threads/{thread_id}/messages: + get: + operationId: listMessages + tags: + - Assistants + summary: Returns a list of messages for a given thread. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: >- + The ID of the [thread](/docs/api-reference/threads) the messages + belong to. + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: before + in: query + description: > + A cursor for use in pagination. `before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the + previous page of the list. + schema: + type: string + - name: run_id + in: query + description: | + Filter messages by the run ID that generated them. + schema: + type: string + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListMessagesResponse' + x-oaiMeta: + name: List messages + group: threads + beta: true + examples: + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/messages \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.beta.threads.messages.list( + thread_id="thread_id", + ) + page = page.data[0] + print(page.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const threadMessages = await openai.beta.threads.messages.list( + "thread_abc123" + ); + + console.log(threadMessages.data); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const message of + client.beta.threads.messages.list('thread_id')) { + console.log(message.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Beta.Threads.Messages.List(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\topenai.BetaThreadMessageListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.messages.MessageListPage; + import com.openai.models.beta.threads.messages.MessageListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + MessageListPage page = client.beta().threads().messages().list("thread_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.beta.threads.messages.list("thread_id") + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1699016383, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "How does AI work? Explain it in simple terms.", + "annotations": [] + } + } + ], + "attachments": [], + "metadata": {} + }, + { + "id": "msg_abc456", + "object": "thread.message", + "created_at": 1699016383, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "Hello, what is AI?", + "annotations": [] + } + } + ], + "attachments": [], + "metadata": {} + } + ], + "first_id": "msg_abc123", + "last_id": "msg_abc456", + "has_more": false + } + post: + operationId: createMessage + tags: + - Assistants + summary: Create a message. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: >- + The ID of the [thread](/docs/api-reference/threads) to create a + message for. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateMessageRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/MessageObject' + x-oaiMeta: + name: Create message + group: threads + beta: true + examples: + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/messages \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "role": "user", + "content": "How does AI work? Explain it in simple terms." + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + message = client.beta.threads.messages.create( + thread_id="thread_id", + content="string", + role="user", + ) + print(message.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const threadMessages = await openai.beta.threads.messages.create( + "thread_abc123", + { role: "user", content: "How does AI work? Explain it in simple terms." } + ); + + console.log(threadMessages); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const message = await + client.beta.threads.messages.create('thread_id', { + content: 'string', + role: 'user', + }); + + + console.log(message.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tmessage, err := client.Beta.Threads.Messages.New(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\topenai.BetaThreadMessageNewParams{\n\t\t\tContent: openai.BetaThreadMessageNewParamsContentUnion{\n\t\t\t\tOfString: openai.String(\"string\"),\n\t\t\t},\n\t\t\tRole: openai.BetaThreadMessageNewParamsRoleUser,\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", message.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.beta.threads.messages.Message; + + import + com.openai.models.beta.threads.messages.MessageCreateParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + MessageCreateParams params = MessageCreateParams.builder() + .threadId("thread_id") + .content("string") + .role(MessageCreateParams.Role.USER) + .build(); + Message message = client.beta().threads().messages().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + message = openai.beta.threads.messages.create("thread_id", + content: "string", role: :user) + + + puts(message) + response: | + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1713226573, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "How does AI work? Explain it in simple terms.", + "annotations": [] + } + } + ], + "attachments": [], + "metadata": {} + } + /threads/{thread_id}/messages/{message_id}: + get: + operationId: getMessage + tags: + - Assistants + summary: Retrieve a message. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: >- + The ID of the [thread](/docs/api-reference/threads) to which this + message belongs. + - in: path + name: message_id + required: true + schema: + type: string + description: The ID of the message to retrieve. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/MessageObject' + x-oaiMeta: + name: Retrieve message + group: threads + beta: true + examples: + request: + curl: > + curl + https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 + \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + message = client.beta.threads.messages.retrieve( + message_id="message_id", + thread_id="thread_id", + ) + print(message.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const message = await openai.beta.threads.messages.retrieve( + "msg_abc123", + { thread_id: "thread_abc123" } + ); + + console.log(message); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const message = await + client.beta.threads.messages.retrieve('message_id', { + thread_id: 'thread_id', + }); + + + console.log(message.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tmessage, err := client.Beta.Threads.Messages.Get(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"message_id\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", message.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.beta.threads.messages.Message; + + import + com.openai.models.beta.threads.messages.MessageRetrieveParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + MessageRetrieveParams params = MessageRetrieveParams.builder() + .threadId("thread_id") + .messageId("message_id") + .build(); + Message message = client.beta().threads().messages().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + message = openai.beta.threads.messages.retrieve("message_id", + thread_id: "thread_id") + + + puts(message) + response: | + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1699017614, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "How does AI work? Explain it in simple terms.", + "annotations": [] + } + } + ], + "attachments": [], + "metadata": {} + } + post: + operationId: modifyMessage + tags: + - Assistants + summary: Modifies a message. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to which this message belongs. + - in: path + name: message_id + required: true + schema: + type: string + description: The ID of the message to modify. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ModifyMessageRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/MessageObject' + x-oaiMeta: + name: Modify message + group: threads + beta: true + examples: + request: + curl: > + curl + https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 + \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "metadata": { + "modified": "true", + "user": "abc123" + } + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + message = client.beta.threads.messages.update( + message_id="message_id", + thread_id="thread_id", + ) + print(message.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const message = await openai.beta.threads.messages.update( + "thread_abc123", + "msg_abc123", + { + metadata: { + modified: "true", + user: "abc123", + }, + } + }' + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const message = await + client.beta.threads.messages.update('message_id', { thread_id: + 'thread_id' }); + + + console.log(message.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tmessage, err := client.Beta.Threads.Messages.Update(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"message_id\",\n\t\topenai.BetaThreadMessageUpdateParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", message.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.beta.threads.messages.Message; + + import + com.openai.models.beta.threads.messages.MessageUpdateParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + MessageUpdateParams params = MessageUpdateParams.builder() + .threadId("thread_id") + .messageId("message_id") + .build(); + Message message = client.beta().threads().messages().update(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + message = openai.beta.threads.messages.update("message_id", + thread_id: "thread_id") + + + puts(message) + response: | + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1699017614, + "assistant_id": null, + "thread_id": "thread_abc123", + "run_id": null, + "role": "user", + "content": [ + { + "type": "text", + "text": { + "value": "How does AI work? Explain it in simple terms.", + "annotations": [] + } + } + ], + "file_ids": [], + "metadata": { + "modified": "true", + "user": "abc123" + } + } + delete: + operationId: deleteMessage + tags: + - Assistants + summary: Deletes a message. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to which this message belongs. + - in: path + name: message_id + required: true + schema: + type: string + description: The ID of the message to delete. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteMessageResponse' + x-oaiMeta: + name: Delete message + group: threads + beta: true + examples: + request: + curl: > + curl -X DELETE + https://api.openai.com/v1/threads/thread_abc123/messages/msg_abc123 + \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + message_deleted = client.beta.threads.messages.delete( + message_id="message_id", + thread_id="thread_id", + ) + print(message_deleted.id) + javascript: |- + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const deletedMessage = await openai.beta.threads.messages.delete( + "msg_abc123", + { thread_id: "thread_abc123" } + ); + + console.log(deletedMessage); + } + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const messageDeleted = await + client.beta.threads.messages.delete('message_id', { + thread_id: 'thread_id', + }); + + + console.log(messageDeleted.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tmessageDeleted, err := client.Beta.Threads.Messages.Delete(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"message_id\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", messageDeleted.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.beta.threads.messages.MessageDeleteParams; + + import com.openai.models.beta.threads.messages.MessageDeleted; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + MessageDeleteParams params = MessageDeleteParams.builder() + .threadId("thread_id") + .messageId("message_id") + .build(); + MessageDeleted messageDeleted = client.beta().threads().messages().delete(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + message_deleted = + openai.beta.threads.messages.delete("message_id", thread_id: + "thread_id") + + + puts(message_deleted) + response: | + { + "id": "msg_abc123", + "object": "thread.message.deleted", + "deleted": true + } + /threads/{thread_id}/runs: + get: + operationId: listRuns + tags: + - Assistants + summary: Returns a list of runs belonging to a thread. + parameters: + - name: thread_id + in: path + required: true + schema: + type: string + description: The ID of the thread the run belongs to. + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: before + in: query + description: > + A cursor for use in pagination. `before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the + previous page of the list. + schema: + type: string + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListRunsResponse' + x-oaiMeta: + name: List runs + group: threads + beta: true + examples: + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.beta.threads.runs.list( + thread_id="thread_id", + ) + page = page.data[0] + print(page.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const runs = await openai.beta.threads.runs.list( + "thread_abc123" + ); + + console.log(runs); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const run of + client.beta.threads.runs.list('thread_id')) { + console.log(run.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Beta.Threads.Runs.List(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\topenai.BetaThreadRunListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.runs.RunListPage; + import com.openai.models.beta.threads.runs.RunListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunListPage page = client.beta().threads().runs().list("thread_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.beta.threads.runs.list("thread_id") + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699075072, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699075072, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699075073, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ + { + "type": "code_interpreter" + } + ], + "tool_resources": { + "code_interpreter": { + "file_ids": [ + "file-abc123", + "file-abc456" + ] + } + }, + "metadata": {}, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + }, + { + "id": "run_abc456", + "object": "thread.run", + "created_at": 1699063290, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699063290, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699063291, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ + { + "type": "code_interpreter" + } + ], + "tool_resources": { + "code_interpreter": { + "file_ids": [ + "file-abc123", + "file-abc456" + ] + } + }, + "metadata": {}, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + ], + "first_id": "run_abc123", + "last_id": "run_abc456", + "has_more": false + } + post: + operationId: createRun + tags: + - Assistants + summary: Create a run. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to run. + - name: include[] + in: query + description: > + A list of additional fields to include in the response. Currently + the only supported value is + `step_details.tool_calls[*].file_search.results[*].content` to fetch + the file search result content. + + + See the [file search tool + documentation](/docs/assistants/tools/file-search#customizing-file-search-settings) + for more information. + schema: + type: array + items: + type: string + enum: + - step_details.tool_calls[*].file_search.results[*].content + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateRunRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/RunObject' + x-oaiMeta: + name: Create run + group: threads + beta: true + examples: + - title: Default + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_abc123" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for run in client.beta.threads.runs.create( + thread_id="thread_id", + assistant_id="assistant_id", + ): + print(run) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.create( + "thread_abc123", + { assistant_id: "asst_abc123" } + ); + + console.log(run); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.beta.threads.runs.create('thread_id', { + assistant_id: 'assistant_id' }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.Runs.New(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\topenai.BetaThreadRunNewParams{\n\t\t\tAssistantID: \"assistant_id\",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.runs.Run; + import com.openai.models.beta.threads.runs.RunCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunCreateParams params = RunCreateParams.builder() + .threadId("thread_id") + .assistantId("assistant_id") + .build(); + Run run = client.beta().threads().runs().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.runs.create("thread_id", assistant_id: + "assistant_id") + + + puts(run) + response: | + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699063290, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "queued", + "started_at": 1699063290, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699063291, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ + { + "type": "code_interpreter" + } + ], + "metadata": {}, + "usage": null, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + - title: Streaming + request: + curl: | + curl https://api.openai.com/v1/threads/thread_123/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_123", + "stream": true + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for run in client.beta.threads.runs.create( + thread_id="thread_id", + assistant_id="assistant_id", + ): + print(run) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const stream = await openai.beta.threads.runs.create( + "thread_123", + { assistant_id: "asst_123", stream: true } + ); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.beta.threads.runs.create('thread_id', { + assistant_id: 'assistant_id' }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.Runs.New(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\topenai.BetaThreadRunNewParams{\n\t\t\tAssistantID: \"assistant_id\",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.runs.Run; + import com.openai.models.beta.threads.runs.RunCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunCreateParams params = RunCreateParams.builder() + .threadId("thread_id") + .assistantId("assistant_id") + .build(); + Run run = client.beta().threads().runs().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.runs.create("thread_id", assistant_id: + "assistant_id") + + + puts(run) + response: > + event: thread.run.created + + data: + {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.queued + + data: + {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.in_progress + + data: + {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710330641,"expires_at":1710331240,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.step.created + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} + + + event: thread.run.step.in_progress + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} + + + event: thread.message.created + + data: + {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} + + + event: thread.message.in_progress + + data: + {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} + + + event: thread.message.delta + + data: + {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} + + + ... + + + event: thread.message.delta + + data: + {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" + today"}}]}} + + + event: thread.message.delta + + data: + {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} + + + event: thread.message.completed + + data: + {"id":"msg_001","object":"thread.message","created_at":1710330641,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710330642,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! + How can I assist you today?","annotations":[]}}],"metadata":{}} + + + event: thread.run.step.completed + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710330641,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710330642,"expires_at":1710331240,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} + + + event: thread.run.completed + + data: + {"id":"run_123","object":"thread.run","created_at":1710330640,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710330641,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710330642,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: done + + data: [DONE] + - title: Streaming with Functions + request: + curl: | + curl https://api.openai.com/v1/threads/thread_abc123/runs \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "assistant_id": "asst_abc123", + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"] + } + }, + "required": ["location"] + } + } + } + ], + "stream": true + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for run in client.beta.threads.runs.create( + thread_id="thread_id", + assistant_id="assistant_id", + ): + print(run) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + const tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + }, + "required": ["location"], + }, + } + } + ]; + + async function main() { + const stream = await openai.beta.threads.runs.create( + "thread_abc123", + { + assistant_id: "asst_abc123", + tools: tools, + stream: true + } + ); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.beta.threads.runs.create('thread_id', { + assistant_id: 'assistant_id' }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.Runs.New(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\topenai.BetaThreadRunNewParams{\n\t\t\tAssistantID: \"assistant_id\",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.runs.Run; + import com.openai.models.beta.threads.runs.RunCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunCreateParams params = RunCreateParams.builder() + .threadId("thread_id") + .assistantId("assistant_id") + .build(); + Run run = client.beta().threads().runs().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.runs.create("thread_id", assistant_id: + "assistant_id") + + + puts(run) + response: > + event: thread.run.created + + data: + {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.queued + + data: + {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":null,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.in_progress + + data: + {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710348075,"expires_at":1710348675,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.step.created + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} + + + event: thread.run.step.in_progress + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":null} + + + event: thread.message.created + + data: + {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} + + + event: thread.message.in_progress + + data: + {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} + + + event: thread.message.delta + + data: + {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"Hello","annotations":[]}}]}} + + + ... + + + event: thread.message.delta + + data: + {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" + today"}}]}} + + + event: thread.message.delta + + data: + {"id":"msg_001","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"?"}}]}} + + + event: thread.message.completed + + data: + {"id":"msg_001","object":"thread.message","created_at":1710348076,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710348077,"role":"assistant","content":[{"type":"text","text":{"value":"Hello! + How can I assist you today?","annotations":[]}}],"metadata":{}} + + + event: thread.run.step.completed + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710348076,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710348077,"expires_at":1710348675,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_001"}},"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31}} + + + event: thread.run.completed + + data: + {"id":"run_123","object":"thread.run","created_at":1710348075,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710348075,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710348077,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: done + + data: [DONE] + /threads/{thread_id}/runs/{run_id}: + get: + operationId: getRun + tags: + - Assistants + summary: Retrieves a run. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/docs/api-reference/threads) that was run. + - in: path + name: run_id + required: true + schema: + type: string + description: The ID of the run to retrieve. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/RunObject' + x-oaiMeta: + name: Retrieve run + group: threads + beta: true + examples: + request: + curl: > + curl + https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + run = client.beta.threads.runs.retrieve( + run_id="run_id", + thread_id="thread_id", + ) + print(run.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.retrieve( + "run_abc123", + { thread_id: "thread_abc123" } + ); + + console.log(run); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.beta.threads.runs.retrieve('run_id', { + thread_id: 'thread_id' }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.Runs.Get(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"run_id\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.runs.Run; + import com.openai.models.beta.threads.runs.RunRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunRetrieveParams params = RunRetrieveParams.builder() + .threadId("thread_id") + .runId("run_id") + .build(); + Run run = client.beta().threads().runs().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.runs.retrieve("run_id", thread_id: + "thread_id") + + + puts(run) + response: | + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699075072, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699075072, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699075073, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ + { + "type": "code_interpreter" + } + ], + "metadata": {}, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + post: + operationId: modifyRun + tags: + - Assistants + summary: Modifies a run. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the [thread](/docs/api-reference/threads) that was run. + - in: path + name: run_id + required: true + schema: + type: string + description: The ID of the run to modify. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ModifyRunRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/RunObject' + x-oaiMeta: + name: Modify run + group: threads + beta: true + examples: + request: + curl: > + curl + https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "metadata": { + "user_id": "user_abc123" + } + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + run = client.beta.threads.runs.update( + run_id="run_id", + thread_id="thread_id", + ) + print(run.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.update( + "run_abc123", + { + thread_id: "thread_abc123", + metadata: { + user_id: "user_abc123", + }, + } + ); + + console.log(run); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.beta.threads.runs.update('run_id', { + thread_id: 'thread_id' }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.Runs.Update(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"run_id\",\n\t\topenai.BetaThreadRunUpdateParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.runs.Run; + import com.openai.models.beta.threads.runs.RunUpdateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunUpdateParams params = RunUpdateParams.builder() + .threadId("thread_id") + .runId("run_id") + .build(); + Run run = client.beta().threads().runs().update(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.runs.update("run_id", thread_id: + "thread_id") + + + puts(run) + response: | + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699075072, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699075072, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699075073, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "incomplete_details": null, + "tools": [ + { + "type": "code_interpreter" + } + ], + "tool_resources": { + "code_interpreter": { + "file_ids": [ + "file-abc123", + "file-abc456" + ] + } + }, + "metadata": { + "user_id": "user_abc123" + }, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + /threads/{thread_id}/runs/{run_id}/cancel: + post: + operationId: cancelRun + tags: + - Assistants + summary: Cancels a run that is `in_progress`. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to which this run belongs. + - in: path + name: run_id + required: true + schema: + type: string + description: The ID of the run to cancel. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/RunObject' + x-oaiMeta: + name: Cancel a run + group: threads + beta: true + examples: + request: + curl: > + curl + https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/cancel + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: assistants=v2" \ + -X POST + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + run = client.beta.threads.runs.cancel( + run_id="run_id", + thread_id="thread_id", + ) + print(run.id) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.cancel( + "run_abc123", + { thread_id: "thread_abc123" } + ); + + console.log(run); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await client.beta.threads.runs.cancel('run_id', { + thread_id: 'thread_id' }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.Runs.Cancel(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"run_id\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.runs.Run; + import com.openai.models.beta.threads.runs.RunCancelParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunCancelParams params = RunCancelParams.builder() + .threadId("thread_id") + .runId("run_id") + .build(); + Run run = client.beta().threads().runs().cancel(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.runs.cancel("run_id", thread_id: + "thread_id") + + + puts(run) + response: | + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1699076126, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "cancelling", + "started_at": 1699076126, + "expires_at": 1699076726, + "cancelled_at": null, + "failed_at": null, + "completed_at": null, + "last_error": null, + "model": "gpt-4o", + "instructions": "You summarize books.", + "tools": [ + { + "type": "file_search" + } + ], + "tool_resources": { + "file_search": { + "vector_store_ids": ["vs_123"] + } + }, + "metadata": {}, + "usage": null, + "temperature": 1.0, + "top_p": 1.0, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + /threads/{thread_id}/runs/{run_id}/steps: + get: + operationId: listRunSteps + tags: + - Assistants + summary: Returns a list of run steps belonging to a run. + parameters: + - name: thread_id + in: path + required: true + schema: + type: string + description: The ID of the thread the run and run steps belong to. + - name: run_id + in: path + required: true + schema: + type: string + description: The ID of the run the run steps belong to. + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: before + in: query + description: > + A cursor for use in pagination. `before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the + previous page of the list. + schema: + type: string + - name: include[] + in: query + description: > + A list of additional fields to include in the response. Currently + the only supported value is + `step_details.tool_calls[*].file_search.results[*].content` to fetch + the file search result content. + + + See the [file search tool + documentation](/docs/assistants/tools/file-search#customizing-file-search-settings) + for more information. + schema: + type: array + items: + type: string + enum: + - step_details.tool_calls[*].file_search.results[*].content + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListRunStepsResponse' + x-oaiMeta: + name: List run steps + group: threads + beta: true + examples: + request: + curl: > + curl + https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.beta.threads.runs.steps.list( + run_id="run_id", + thread_id="thread_id", + ) + page = page.data[0] + print(page.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const runStep = await openai.beta.threads.runs.steps.list( + "run_abc123", + { thread_id: "thread_abc123" } + ); + console.log(runStep); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const runStep of + client.beta.threads.runs.steps.list('run_id', { + thread_id: 'thread_id', + })) { + console.log(runStep.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Beta.Threads.Runs.Steps.List(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"run_id\",\n\t\topenai.BetaThreadRunStepListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.threads.runs.steps.StepListPage; + import com.openai.models.beta.threads.runs.steps.StepListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + StepListParams params = StepListParams.builder() + .threadId("thread_id") + .runId("run_id") + .build(); + StepListPage page = client.beta().threads().runs().steps().list(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + page = openai.beta.threads.runs.steps.list("run_id", thread_id: + "thread_id") + + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "step_abc123", + "object": "thread.run.step", + "created_at": 1699063291, + "run_id": "run_abc123", + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "type": "message_creation", + "status": "completed", + "cancelled_at": null, + "completed_at": 1699063291, + "expired_at": null, + "failed_at": null, + "last_error": null, + "step_details": { + "type": "message_creation", + "message_creation": { + "message_id": "msg_abc123" + } + }, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + } + } + ], + "first_id": "step_abc123", + "last_id": "step_abc456", + "has_more": false + } + /threads/{thread_id}/runs/{run_id}/steps/{step_id}: + get: + operationId: getRunStep + tags: + - Assistants + summary: Retrieves a run step. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: The ID of the thread to which the run and run step belongs. + - in: path + name: run_id + required: true + schema: + type: string + description: The ID of the run to which the run step belongs. + - in: path + name: step_id + required: true + schema: + type: string + description: The ID of the run step to retrieve. + - name: include[] + in: query + description: > + A list of additional fields to include in the response. Currently + the only supported value is + `step_details.tool_calls[*].file_search.results[*].content` to fetch + the file search result content. + + + See the [file search tool + documentation](/docs/assistants/tools/file-search#customizing-file-search-settings) + for more information. + schema: + type: array + items: + type: string + enum: + - step_details.tool_calls[*].file_search.results[*].content + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/RunStepObject' + x-oaiMeta: + name: Retrieve run step + group: threads + beta: true + examples: + request: + curl: > + curl + https://api.openai.com/v1/threads/thread_abc123/runs/run_abc123/steps/step_abc123 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + run_step = client.beta.threads.runs.steps.retrieve( + step_id="step_id", + thread_id="thread_id", + run_id="run_id", + ) + print(run_step.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const runStep = await openai.beta.threads.runs.steps.retrieve( + "step_abc123", + { thread_id: "thread_abc123", run_id: "run_abc123" } + ); + console.log(runStep); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const runStep = await + client.beta.threads.runs.steps.retrieve('step_id', { + thread_id: 'thread_id', + run_id: 'run_id', + }); + + + console.log(runStep.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trunStep, err := client.Beta.Threads.Runs.Steps.Get(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"run_id\",\n\t\t\"step_id\",\n\t\topenai.BetaThreadRunStepGetParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", runStep.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.beta.threads.runs.steps.RunStep; + + import + com.openai.models.beta.threads.runs.steps.StepRetrieveParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + StepRetrieveParams params = StepRetrieveParams.builder() + .threadId("thread_id") + .runId("run_id") + .stepId("step_id") + .build(); + RunStep runStep = client.beta().threads().runs().steps().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run_step = openai.beta.threads.runs.steps.retrieve("step_id", + thread_id: "thread_id", run_id: "run_id") + + + puts(run_step) + response: | + { + "id": "step_abc123", + "object": "thread.run.step", + "created_at": 1699063291, + "run_id": "run_abc123", + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "type": "message_creation", + "status": "completed", + "cancelled_at": null, + "completed_at": 1699063291, + "expired_at": null, + "failed_at": null, + "last_error": null, + "step_details": { + "type": "message_creation", + "message_creation": { + "message_id": "msg_abc123" + } + }, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + } + } + /threads/{thread_id}/runs/{run_id}/submit_tool_outputs: + post: + operationId: submitToolOuputsToRun + tags: + - Assistants + summary: > + When a run has the `status: "requires_action"` and + `required_action.type` is `submit_tool_outputs`, this endpoint can be + used to submit the outputs from the tool calls once they're all + completed. All outputs must be submitted in a single request. + parameters: + - in: path + name: thread_id + required: true + schema: + type: string + description: >- + The ID of the [thread](/docs/api-reference/threads) to which this + run belongs. + - in: path + name: run_id + required: true + schema: + type: string + description: The ID of the run that requires the tool output submission. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/SubmitToolOutputsRunRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/RunObject' + x-oaiMeta: + name: Submit tool outputs to run + group: threads + beta: true + examples: + - title: Default + request: + curl: > + curl + https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "tool_outputs": [ + { + "tool_call_id": "call_001", + "output": "70 degrees and sunny." + } + ] + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for run in client.beta.threads.runs.submit_tool_outputs( + run_id="run_id", + thread_id="thread_id", + tool_outputs=[{}], + ): + print(run) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const run = await openai.beta.threads.runs.submitToolOutputs( + "run_123", + { + thread_id: "thread_123", + tool_outputs: [ + { + tool_call_id: "call_001", + output: "70 degrees and sunny.", + }, + ], + } + ); + + console.log(run); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await + client.beta.threads.runs.submitToolOutputs('run_id', { + thread_id: 'thread_id', + tool_outputs: [{}], + }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.Runs.SubmitToolOutputs(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"run_id\",\n\t\topenai.BetaThreadRunSubmitToolOutputsParams{\n\t\t\tToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{{}},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.beta.threads.runs.Run; + + import + com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder() + .threadId("thread_id") + .runId("run_id") + .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build()) + .build(); + Run run = client.beta().threads().runs().submitToolOutputs(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.runs.submit_tool_outputs("run_id", + thread_id: "thread_id", tool_outputs: [{}]) + + + puts(run) + response: | + { + "id": "run_123", + "object": "thread.run", + "created_at": 1699075592, + "assistant_id": "asst_123", + "thread_id": "thread_123", + "status": "queued", + "started_at": 1699075592, + "expires_at": 1699076192, + "cancelled_at": null, + "failed_at": null, + "completed_at": null, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "tools": [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA" + }, + "unit": { + "type": "string", + "enum": ["celsius", "fahrenheit"] + } + }, + "required": ["location"] + } + } + } + ], + "metadata": {}, + "usage": null, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + - title: Streaming + request: + curl: > + curl + https://api.openai.com/v1/threads/thread_123/runs/run_123/submit_tool_outputs + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "tool_outputs": [ + { + "tool_call_id": "call_001", + "output": "70 degrees and sunny." + } + ], + "stream": true + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + for run in client.beta.threads.runs.submit_tool_outputs( + run_id="run_id", + thread_id="thread_id", + tool_outputs=[{}], + ): + print(run) + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + async function main() { + const stream = await openai.beta.threads.runs.submitToolOutputs( + "run_123", + { + thread_id: "thread_123", + tool_outputs: [ + { + tool_call_id: "call_001", + output: "70 degrees and sunny.", + }, + ], + } + ); + + for await (const event of stream) { + console.log(event); + } + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const run = await + client.beta.threads.runs.submitToolOutputs('run_id', { + thread_id: 'thread_id', + tool_outputs: [{}], + }); + + + console.log(run.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\trun, err := client.Beta.Threads.Runs.SubmitToolOutputs(\n\t\tcontext.TODO(),\n\t\t\"thread_id\",\n\t\t\"run_id\",\n\t\topenai.BetaThreadRunSubmitToolOutputsParams{\n\t\t\tToolOutputs: []openai.BetaThreadRunSubmitToolOutputsParamsToolOutput{{}},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", run.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.beta.threads.runs.Run; + + import + com.openai.models.beta.threads.runs.RunSubmitToolOutputsParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + RunSubmitToolOutputsParams params = RunSubmitToolOutputsParams.builder() + .threadId("thread_id") + .runId("run_id") + .addToolOutput(RunSubmitToolOutputsParams.ToolOutput.builder().build()) + .build(); + Run run = client.beta().threads().runs().submitToolOutputs(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + run = openai.beta.threads.runs.submit_tool_outputs("run_id", + thread_id: "thread_id", tool_outputs: [{}]) + + + puts(run) + response: > + event: thread.run.step.completed + + data: + {"id":"step_001","object":"thread.run.step","created_at":1710352449,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"tool_calls","status":"completed","cancelled_at":null,"completed_at":1710352475,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"tool_calls","tool_calls":[{"id":"call_iWr0kQ2EaYMaxNdl0v3KYkx7","type":"function","function":{"name":"get_current_weather","arguments":"{\"location\":\"San + Francisco, CA\",\"unit\":\"fahrenheit\"}","output":"70 degrees and + sunny."}}]},"usage":{"prompt_tokens":291,"completion_tokens":24,"total_tokens":315}} + + + event: thread.run.queued + + data: + {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"queued","started_at":1710352448,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get + the current weather in a given + location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The + city and state, e.g. San Francisco, + CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.in_progress + + data: + {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"in_progress","started_at":1710352475,"expires_at":1710353047,"cancelled_at":null,"failed_at":null,"completed_at":null,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get + the current weather in a given + location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The + city and state, e.g. San Francisco, + CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":null,"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: thread.run.step.created + + data: + {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null} + + + event: thread.run.step.in_progress + + data: + {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"in_progress","cancelled_at":null,"completed_at":null,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":null} + + + event: thread.message.created + + data: + {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} + + + event: thread.message.in_progress + + data: + {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"in_progress","incomplete_details":null,"incomplete_at":null,"completed_at":null,"role":"assistant","content":[],"metadata":{}} + + + event: thread.message.delta + + data: + {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"The","annotations":[]}}]}} + + + event: thread.message.delta + + data: + {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" + current"}}]}} + + + event: thread.message.delta + + data: + {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" + weather"}}]}} + + + ... + + + event: thread.message.delta + + data: + {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":" + sunny"}}]}} + + + event: thread.message.delta + + data: + {"id":"msg_002","object":"thread.message.delta","delta":{"content":[{"index":0,"type":"text","text":{"value":"."}}]}} + + + event: thread.message.completed + + data: + {"id":"msg_002","object":"thread.message","created_at":1710352476,"assistant_id":"asst_123","thread_id":"thread_123","run_id":"run_123","status":"completed","incomplete_details":null,"incomplete_at":null,"completed_at":1710352477,"role":"assistant","content":[{"type":"text","text":{"value":"The + current weather in San Francisco, CA is 70 degrees Fahrenheit and + sunny.","annotations":[]}}],"metadata":{}} + + + event: thread.run.step.completed + + data: + {"id":"step_002","object":"thread.run.step","created_at":1710352476,"run_id":"run_123","assistant_id":"asst_123","thread_id":"thread_123","type":"message_creation","status":"completed","cancelled_at":null,"completed_at":1710352477,"expires_at":1710353047,"failed_at":null,"last_error":null,"step_details":{"type":"message_creation","message_creation":{"message_id":"msg_002"}},"usage":{"prompt_tokens":329,"completion_tokens":18,"total_tokens":347}} + + + event: thread.run.completed + + data: + {"id":"run_123","object":"thread.run","created_at":1710352447,"assistant_id":"asst_123","thread_id":"thread_123","status":"completed","started_at":1710352475,"expires_at":null,"cancelled_at":null,"failed_at":null,"completed_at":1710352477,"required_action":null,"last_error":null,"model":"gpt-4o","instructions":null,"tools":[{"type":"function","function":{"name":"get_current_weather","description":"Get + the current weather in a given + location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The + city and state, e.g. San Francisco, + CA"},"unit":{"type":"string","enum":["celsius","fahrenheit"]}},"required":["location"]}}}],"metadata":{},"temperature":1.0,"top_p":1.0,"max_completion_tokens":null,"max_prompt_tokens":null,"truncation_strategy":{"type":"auto","last_messages":null},"incomplete_details":null,"usage":{"prompt_tokens":20,"completion_tokens":11,"total_tokens":31},"response_format":"auto","tool_choice":"auto","parallel_tool_calls":true}} + + + event: done + + data: [DONE] + /uploads: + post: + operationId: createUpload + tags: + - Uploads + summary: > + Creates an intermediate [Upload](/docs/api-reference/uploads/object) + object + + that you can add [Parts](/docs/api-reference/uploads/part-object) to. + + Currently, an Upload can accept at most 8 GB in total and expires after + an + + hour after you create it. + + + Once you complete the Upload, we will create a + + [File](/docs/api-reference/files/object) object that contains all the + parts + + you uploaded. This File is usable in the rest of our platform as a + regular + + File object. + + + For certain `purpose` values, the correct `mime_type` must be + specified. + + Please refer to documentation for the + + [supported MIME types for your use + case](/docs/assistants/tools/file-search#supported-files). + + + For guidance on the proper filename extensions for each purpose, please + + follow the documentation on [creating a + + File](/docs/api-reference/files/create). + + + Returns the Upload object with status `pending`. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateUploadRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Upload' + x-oaiMeta: + name: Create upload + group: uploads + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "purpose": "fine-tune", + "filename": "training_examples.jsonl", + "bytes": 2147483648, + "mime_type": "text/jsonl", + "expires_after": { + "anchor": "created_at", + "seconds": 3600 + } + }' + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const upload = await client.uploads.create({ + bytes: 0, + filename: 'filename', + mime_type: 'mime_type', + purpose: 'assistants', + }); + + console.log(upload.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + upload = client.uploads.create( + bytes=0, + filename="filename", + mime_type="mime_type", + purpose="assistants", + ) + print(upload.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tupload, err := client.Uploads.New(context.TODO(), openai.UploadNewParams{\n\t\tBytes: 0,\n\t\tFilename: \"filename\",\n\t\tMimeType: \"mime_type\",\n\t\tPurpose: openai.FilePurposeAssistants,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", upload.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.files.FilePurpose; + import com.openai.models.uploads.Upload; + import com.openai.models.uploads.UploadCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + UploadCreateParams params = UploadCreateParams.builder() + .bytes(0L) + .filename("filename") + .mimeType("mime_type") + .purpose(FilePurpose.ASSISTANTS) + .build(); + Upload upload = client.uploads().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + upload = openai.uploads.create(bytes: 0, filename: "filename", + mime_type: "mime_type", purpose: :assistants) + + + puts(upload) + response: | + { + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "pending", + "expires_at": 1719127296 + } + /uploads/{upload_id}/cancel: + post: + operationId: cancelUpload + tags: + - Uploads + summary: | + Cancels the Upload. No Parts may be added after an Upload is cancelled. + + Returns the Upload object with status `cancelled`. + parameters: + - in: path + name: upload_id + required: true + schema: + type: string + example: upload_abc123 + description: | + The ID of the Upload. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Upload' + x-oaiMeta: + name: Cancel upload + group: uploads + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads/upload_abc123/cancel + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const upload = await client.uploads.cancel('upload_abc123'); + + console.log(upload.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + upload = client.uploads.cancel( + "upload_abc123", + ) + print(upload.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tupload, err := client.Uploads.Cancel(context.TODO(), \"upload_abc123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", upload.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.uploads.Upload; + import com.openai.models.uploads.UploadCancelParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Upload upload = client.uploads().cancel("upload_abc123"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + upload = openai.uploads.cancel("upload_abc123") + + puts(upload) + response: | + { + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "cancelled", + "expires_at": 1719127296 + } + /uploads/{upload_id}/complete: + post: + operationId: completeUpload + tags: + - Uploads + summary: > + Completes the [Upload](/docs/api-reference/uploads/object). + + + Within the returned Upload object, there is a nested + [File](/docs/api-reference/files/object) object that is ready to use in + the rest of the platform. + + + You can specify the order of the Parts by passing in an ordered list of + the Part IDs. + + + The number of bytes uploaded upon completion must match the number of + bytes initially specified when creating the Upload object. No Parts may + be added after an Upload is completed. + + Returns the Upload object with status `completed`, including an + additional `file` property containing the created usable File object. + parameters: + - in: path + name: upload_id + required: true + schema: + type: string + example: upload_abc123 + description: | + The ID of the Upload. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CompleteUploadRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/Upload' + x-oaiMeta: + name: Complete upload + group: uploads + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads/upload_abc123/complete + -d '{ + "part_ids": ["part_def456", "part_ghi789"] + }' + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const upload = await client.uploads.complete('upload_abc123', { + part_ids: ['string'] }); + + + console.log(upload.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + upload = client.uploads.complete( + upload_id="upload_abc123", + part_ids=["string"], + ) + print(upload.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tupload, err := client.Uploads.Complete(\n\t\tcontext.TODO(),\n\t\t\"upload_abc123\",\n\t\topenai.UploadCompleteParams{\n\t\t\tPartIDs: []string{\"string\"},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", upload.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.uploads.Upload; + import com.openai.models.uploads.UploadCompleteParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + UploadCompleteParams params = UploadCompleteParams.builder() + .uploadId("upload_abc123") + .addPartId("string") + .build(); + Upload upload = client.uploads().complete(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + upload = openai.uploads.complete("upload_abc123", part_ids: + ["string"]) + + + puts(upload) + response: | + { + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "completed", + "expires_at": 1719127296, + "file": { + "id": "file-xyz321", + "object": "file", + "bytes": 2147483648, + "created_at": 1719186911, + "expires_at": 1719127296, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + } + } + /uploads/{upload_id}/parts: + post: + operationId: addUploadPart + tags: + - Uploads + summary: > + Adds a [Part](/docs/api-reference/uploads/part-object) to an + [Upload](/docs/api-reference/uploads/object) object. A Part represents a + chunk of bytes from the file you are trying to upload. + + + Each Part can be at most 64 MB, and you can add Parts until you hit the + Upload maximum of 8 GB. + + + It is possible to add multiple Parts in parallel. You can decide the + intended order of the Parts when you [complete the + Upload](/docs/api-reference/uploads/complete). + parameters: + - in: path + name: upload_id + required: true + schema: + type: string + example: upload_abc123 + description: | + The ID of the Upload. + requestBody: + required: true + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/AddUploadPartRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/UploadPart' + x-oaiMeta: + name: Add upload part + group: uploads + examples: + request: + curl: | + curl https://api.openai.com/v1/uploads/upload_abc123/parts + -F data="aHR0cHM6Ly9hcGkub3BlbmFpLmNvbS92MS91cGxvYWRz..." + node.js: >- + import fs from 'fs'; + + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const uploadPart = await + client.uploads.parts.create('upload_abc123', { + data: fs.createReadStream('path/to/file'), + }); + + + console.log(uploadPart.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + upload_part = client.uploads.parts.create( + upload_id="upload_abc123", + data=b"Example data", + ) + print(upload_part.id) + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tuploadPart, err := client.Uploads.Parts.New(\n\t\tcontext.TODO(),\n\t\t\"upload_abc123\",\n\t\topenai.UploadPartNewParams{\n\t\t\tData: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", uploadPart.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.uploads.parts.PartCreateParams; + import com.openai.models.uploads.parts.UploadPart; + import java.io.ByteArrayInputStream; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + PartCreateParams params = PartCreateParams.builder() + .uploadId("upload_abc123") + .data(new ByteArrayInputStream("Example data".getBytes())) + .build(); + UploadPart uploadPart = client.uploads().parts().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + upload_part = openai.uploads.parts.create("upload_abc123", data: + StringIO.new("Example data")) + + + puts(upload_part) + response: | + { + "id": "part_def456", + "object": "upload.part", + "created_at": 1719185911, + "upload_id": "upload_abc123" + } + /vector_stores: + get: + operationId: listVectorStores + tags: + - Vector stores + summary: Returns a list of vector stores. + parameters: + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: before + in: query + description: > + A cursor for use in pagination. `before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the + previous page of the list. + schema: + type: string + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListVectorStoresResponse' + x-oaiMeta: + name: List vector stores + group: vector_stores + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.vector_stores.list() + page = page.data[0] + print(page.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStores = await openai.vectorStores.list(); + console.log(vectorStores); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + // Automatically fetches more pages as needed. + for await (const vectorStore of client.vectorStores.list()) { + console.log(vectorStore.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.VectorStores.List(context.TODO(), openai.VectorStoreListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.VectorStoreListPage; + import com.openai.models.vectorstores.VectorStoreListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VectorStoreListPage page = client.vectorStores().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.vector_stores.list + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "vs_abc123", + "object": "vector_store", + "created_at": 1699061776, + "name": "Support FAQ", + "description": "Contains commonly asked questions and answers, organized by topic.", + "bytes": 139920, + "file_counts": { + "in_progress": 0, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 3 + } + }, + { + "id": "vs_abc456", + "object": "vector_store", + "created_at": 1699061776, + "name": "Support FAQ v2", + "description": null, + "bytes": 139920, + "file_counts": { + "in_progress": 0, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 3 + } + } + ], + "first_id": "vs_abc123", + "last_id": "vs_abc456", + "has_more": false + } + post: + operationId: createVectorStore + tags: + - Vector stores + summary: Create a vector store. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateVectorStoreRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreObject' + x-oaiMeta: + name: Create vector store + group: vector_stores + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "name": "Support FAQ" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + vector_store = client.vector_stores.create() + print(vector_store.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStore = await openai.vectorStores.create({ + name: "Support FAQ" + }); + console.log(vectorStore); + } + + main(); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const vectorStore = await client.vectorStores.create(); + + console.log(vectorStore.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStore, err := client.VectorStores.New(context.TODO(), openai.VectorStoreNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStore.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.VectorStore; + import com.openai.models.vectorstores.VectorStoreCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VectorStore vectorStore = client.vectorStores().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + vector_store = openai.vector_stores.create + + puts(vector_store) + response: | + { + "id": "vs_abc123", + "object": "vector_store", + "created_at": 1699061776, + "name": "Support FAQ", + "description": "Contains commonly asked questions and answers, organized by topic.", + "bytes": 139920, + "file_counts": { + "in_progress": 0, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 3 + } + } + /vector_stores/{vector_store_id}: + get: + operationId: getVectorStore + tags: + - Vector stores + summary: Retrieves a vector store. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + description: The ID of the vector store to retrieve. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreObject' + x-oaiMeta: + name: Retrieve vector store + group: vector_stores + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + vector_store = client.vector_stores.retrieve( + "vector_store_id", + ) + print(vector_store.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStore = await openai.vectorStores.retrieve( + "vs_abc123" + ); + console.log(vectorStore); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStore = await + client.vectorStores.retrieve('vector_store_id'); + + + console.log(vectorStore.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStore, err := client.VectorStores.Get(context.TODO(), \"vector_store_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStore.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.VectorStore; + import com.openai.models.vectorstores.VectorStoreRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VectorStore vectorStore = client.vectorStores().retrieve("vector_store_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + vector_store = openai.vector_stores.retrieve("vector_store_id") + + puts(vector_store) + response: | + { + "id": "vs_abc123", + "object": "vector_store", + "created_at": 1699061776 + } + post: + operationId: modifyVectorStore + tags: + - Vector stores + summary: Modifies a vector store. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + description: The ID of the vector store to modify. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateVectorStoreRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreObject' + x-oaiMeta: + name: Modify vector store + group: vector_stores + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + -d '{ + "name": "Support FAQ" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + vector_store = client.vector_stores.update( + vector_store_id="vector_store_id", + ) + print(vector_store.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStore = await openai.vectorStores.update( + "vs_abc123", + { + name: "Support FAQ" + } + ); + console.log(vectorStore); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStore = await + client.vectorStores.update('vector_store_id'); + + + console.log(vectorStore.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStore, err := client.VectorStores.Update(\n\t\tcontext.TODO(),\n\t\t\"vector_store_id\",\n\t\topenai.VectorStoreUpdateParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStore.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.VectorStore; + import com.openai.models.vectorstores.VectorStoreUpdateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VectorStore vectorStore = client.vectorStores().update("vector_store_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + vector_store = openai.vector_stores.update("vector_store_id") + + puts(vector_store) + response: | + { + "id": "vs_abc123", + "object": "vector_store", + "created_at": 1699061776, + "name": "Support FAQ", + "description": "Contains commonly asked questions and answers, organized by topic.", + "bytes": 139920, + "file_counts": { + "in_progress": 0, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 3 + } + } + delete: + operationId: deleteVectorStore + tags: + - Vector stores + summary: Delete a vector store. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + description: The ID of the vector store to delete. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteVectorStoreResponse' + x-oaiMeta: + name: Delete vector store + group: vector_stores + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -X DELETE + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + vector_store_deleted = client.vector_stores.delete( + "vector_store_id", + ) + print(vector_store_deleted.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const deletedVectorStore = await openai.vectorStores.delete( + "vs_abc123" + ); + console.log(deletedVectorStore); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStoreDeleted = await + client.vectorStores.delete('vector_store_id'); + + + console.log(vectorStoreDeleted.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStoreDeleted, err := client.VectorStores.Delete(context.TODO(), \"vector_store_id\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStoreDeleted.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.VectorStoreDeleteParams; + import com.openai.models.vectorstores.VectorStoreDeleted; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VectorStoreDeleted vectorStoreDeleted = client.vectorStores().delete("vector_store_id"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + vector_store_deleted = + openai.vector_stores.delete("vector_store_id") + + + puts(vector_store_deleted) + response: | + { + id: "vs_abc123", + object: "vector_store.deleted", + deleted: true + } + /vector_stores/{vector_store_id}/file_batches: + post: + operationId: createVectorStoreFileBatch + tags: + - Vector stores + summary: Create a vector store file batch. + description: > + The maximum number of files in a single batch request is 2000. + + Vector store file attach requests are rate limited per vector store (300 + requests per minute across both this endpoint and + `/vector_stores/{vector_store_id}/files`). + + For ingesting multiple files into the same vector store, this batch + endpoint is recommended. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + example: vs_abc123 + description: | + The ID of the vector store for which to create a File Batch. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateVectorStoreFileBatchRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreFileBatchObject' + x-oaiMeta: + name: Create vector store file batch + group: vector_stores + description: > + Attaches multiple files to a vector store in one request. This is the + recommended approach for multi-file ingestion, especially because + per-vector-store file attach writes are rate-limited (300 + requests/minute shared with `/vector_stores/{vector_store_id}/files`). + examples: + request: + curl: > + curl + https://api.openai.com/v1/vector_stores/vs_abc123/file_batches \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "files": [ + { + "file_id": "file-abc123", + "attributes": {"category": "finance"} + }, + { + "file_id": "file-abc456", + "chunking_strategy": { + "type": "static", + "max_chunk_size_tokens": 1200, + "chunk_overlap_tokens": 200 + } + } + ] + }' + python: >- + import os + + from openai import OpenAI + + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + + vector_store_file_batch = + client.vector_stores.file_batches.create( + vector_store_id="vs_abc123", + ) + + print(vector_store_file_batch.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const myVectorStoreFileBatch = await openai.vectorStores.fileBatches.create( + "vs_abc123", + { + files: [ + { + file_id: "file-abc123", + attributes: { category: "finance" }, + }, + { + file_id: "file-abc456", + chunking_strategy: { + type: "static", + max_chunk_size_tokens: 1200, + chunk_overlap_tokens: 200, + }, + }, + ] + } + ); + console.log(myVectorStoreFileBatch); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStoreFileBatch = await + client.vectorStores.fileBatches.create('vs_abc123'); + + + console.log(vectorStoreFileBatch.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStoreFileBatch, err := client.VectorStores.FileBatches.New(\n\t\tcontext.TODO(),\n\t\t\"vs_abc123\",\n\t\topenai.VectorStoreFileBatchNewParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStoreFileBatch.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.vectorstores.filebatches.FileBatchCreateParams; + + import + com.openai.models.vectorstores.filebatches.VectorStoreFileBatch; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().create("vs_abc123"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + vector_store_file_batch = + openai.vector_stores.file_batches.create("vs_abc123") + + + puts(vector_store_file_batch) + response: | + { + "id": "vsfb_abc123", + "object": "vector_store.file_batch", + "created_at": 1699061776, + "vector_store_id": "vs_abc123", + "status": "in_progress", + "file_counts": { + "in_progress": 1, + "completed": 1, + "failed": 0, + "cancelled": 0, + "total": 0, + } + } + /vector_stores/{vector_store_id}/file_batches/{batch_id}: + get: + operationId: getVectorStoreFileBatch + tags: + - Vector stores + summary: Retrieves a vector store file batch. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + example: vs_abc123 + description: The ID of the vector store that the file batch belongs to. + - in: path + name: batch_id + required: true + schema: + type: string + example: vsfb_abc123 + description: The ID of the file batch being retrieved. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreFileBatchObject' + x-oaiMeta: + name: Retrieve vector store file batch + group: vector_stores + examples: + request: + curl: > + curl + https://api.openai.com/v1/vector_stores/vs_abc123/file_batches/vsfb_abc123 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: >- + import os + + from openai import OpenAI + + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + + vector_store_file_batch = + client.vector_stores.file_batches.retrieve( + batch_id="vsfb_abc123", + vector_store_id="vs_abc123", + ) + + print(vector_store_file_batch.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStoreFileBatch = await openai.vectorStores.fileBatches.retrieve( + "vsfb_abc123", + { vector_store_id: "vs_abc123" } + ); + console.log(vectorStoreFileBatch); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStoreFileBatch = await + client.vectorStores.fileBatches.retrieve('vsfb_abc123', { + vector_store_id: 'vs_abc123', + }); + + + console.log(vectorStoreFileBatch.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStoreFileBatch, err := client.VectorStores.FileBatches.Get(\n\t\tcontext.TODO(),\n\t\t\"vs_abc123\",\n\t\t\"vsfb_abc123\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStoreFileBatch.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.vectorstores.filebatches.FileBatchRetrieveParams; + + import + com.openai.models.vectorstores.filebatches.VectorStoreFileBatch; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileBatchRetrieveParams params = FileBatchRetrieveParams.builder() + .vectorStoreId("vs_abc123") + .batchId("vsfb_abc123") + .build(); + VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + vector_store_file_batch = + openai.vector_stores.file_batches.retrieve("vsfb_abc123", + vector_store_id: "vs_abc123") + + + puts(vector_store_file_batch) + response: | + { + "id": "vsfb_abc123", + "object": "vector_store.file_batch", + "created_at": 1699061776, + "vector_store_id": "vs_abc123", + "status": "in_progress", + "file_counts": { + "in_progress": 1, + "completed": 1, + "failed": 0, + "cancelled": 0, + "total": 0, + } + } + /vector_stores/{vector_store_id}/file_batches/{batch_id}/cancel: + post: + operationId: cancelVectorStoreFileBatch + tags: + - Vector stores + summary: >- + Cancel a vector store file batch. This attempts to cancel the processing + of files in this batch as soon as possible. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + description: The ID of the vector store that the file batch belongs to. + - in: path + name: batch_id + required: true + schema: + type: string + description: The ID of the file batch to cancel. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreFileBatchObject' + x-oaiMeta: + name: Cancel vector store file batch + group: vector_stores + examples: + request: + curl: > + curl + https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/cancel + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -X POST + python: >- + import os + + from openai import OpenAI + + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + + vector_store_file_batch = + client.vector_stores.file_batches.cancel( + batch_id="batch_id", + vector_store_id="vector_store_id", + ) + + print(vector_store_file_batch.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const deletedVectorStoreFileBatch = await openai.vectorStores.fileBatches.cancel( + "vsfb_abc123", + { vector_store_id: "vs_abc123" } + ); + console.log(deletedVectorStoreFileBatch); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStoreFileBatch = await + client.vectorStores.fileBatches.cancel('batch_id', { + vector_store_id: 'vector_store_id', + }); + + + console.log(vectorStoreFileBatch.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStoreFileBatch, err := client.VectorStores.FileBatches.Cancel(\n\t\tcontext.TODO(),\n\t\t\"vector_store_id\",\n\t\t\"batch_id\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStoreFileBatch.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.vectorstores.filebatches.FileBatchCancelParams; + + import + com.openai.models.vectorstores.filebatches.VectorStoreFileBatch; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileBatchCancelParams params = FileBatchCancelParams.builder() + .vectorStoreId("vector_store_id") + .batchId("batch_id") + .build(); + VectorStoreFileBatch vectorStoreFileBatch = client.vectorStores().fileBatches().cancel(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + vector_store_file_batch = + openai.vector_stores.file_batches.cancel("batch_id", + vector_store_id: "vector_store_id") + + + puts(vector_store_file_batch) + response: | + { + "id": "vsfb_abc123", + "object": "vector_store.file_batch", + "created_at": 1699061776, + "vector_store_id": "vs_abc123", + "status": "in_progress", + "file_counts": { + "in_progress": 12, + "completed": 3, + "failed": 0, + "cancelled": 0, + "total": 15, + } + } + /vector_stores/{vector_store_id}/file_batches/{batch_id}/files: + get: + operationId: listFilesInVectorStoreBatch + tags: + - Vector stores + summary: Returns a list of vector store files in a batch. + parameters: + - name: vector_store_id + in: path + description: The ID of the vector store that the files belong to. + required: true + schema: + type: string + - name: batch_id + in: path + description: The ID of the file batch that the files belong to. + required: true + schema: + type: string + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: before + in: query + description: > + A cursor for use in pagination. `before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the + previous page of the list. + schema: + type: string + - name: filter + in: query + description: >- + Filter by file status. One of `in_progress`, `completed`, `failed`, + `cancelled`. + schema: + type: string + enum: + - in_progress + - completed + - failed + - cancelled + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListVectorStoreFilesResponse' + x-oaiMeta: + name: List vector store files in a batch + group: vector_stores + examples: + request: + curl: > + curl + https://api.openai.com/v1/vector_stores/vs_abc123/files_batches/vsfb_abc123/files + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.vector_stores.file_batches.list_files( + batch_id="batch_id", + vector_store_id="vector_store_id", + ) + page = page.data[0] + print(page.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStoreFiles = await openai.vectorStores.fileBatches.listFiles( + "vsfb_abc123", + { vector_store_id: "vs_abc123" } + ); + console.log(vectorStoreFiles); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const vectorStoreFile of + client.vectorStores.fileBatches.listFiles('batch_id', { + vector_store_id: 'vector_store_id', + })) { + console.log(vectorStoreFile.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.VectorStores.FileBatches.ListFiles(\n\t\tcontext.TODO(),\n\t\t\"vector_store_id\",\n\t\t\"batch_id\",\n\t\topenai.VectorStoreFileBatchListFilesParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.vectorstores.filebatches.FileBatchListFilesPage; + + import + com.openai.models.vectorstores.filebatches.FileBatchListFilesParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileBatchListFilesParams params = FileBatchListFilesParams.builder() + .vectorStoreId("vector_store_id") + .batchId("batch_id") + .build(); + FileBatchListFilesPage page = client.vectorStores().fileBatches().listFiles(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + page = openai.vector_stores.file_batches.list_files("batch_id", + vector_store_id: "vector_store_id") + + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abc123" + }, + { + "id": "file-abc456", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abc123" + } + ], + "first_id": "file-abc123", + "last_id": "file-abc456", + "has_more": false + } + /vector_stores/{vector_store_id}/files: + get: + operationId: listVectorStoreFiles + tags: + - Vector stores + summary: Returns a list of vector store files. + parameters: + - name: vector_store_id + in: path + description: The ID of the vector store that the files belong to. + required: true + schema: + type: string + - name: limit + in: query + description: > + A limit on the number of objects to be returned. Limit can range + between 1 and 100, and the default is 20. + required: false + schema: + type: integer + default: 20 + - name: order + in: query + description: > + Sort order by the `created_at` timestamp of the objects. `asc` for + ascending order and `desc` for descending order. + schema: + type: string + default: desc + enum: + - asc + - desc + - name: after + in: query + description: > + A cursor for use in pagination. `after` is an object ID that defines + your place in the list. For instance, if you make a list request and + receive 100 objects, ending with obj_foo, your subsequent call can + include after=obj_foo in order to fetch the next page of the list. + schema: + type: string + - name: before + in: query + description: > + A cursor for use in pagination. `before` is an object ID that + defines your place in the list. For instance, if you make a list + request and receive 100 objects, starting with obj_foo, your + subsequent call can include before=obj_foo in order to fetch the + previous page of the list. + schema: + type: string + - name: filter + in: query + description: >- + Filter by file status. One of `in_progress`, `completed`, `failed`, + `cancelled`. + schema: + type: string + enum: + - in_progress + - completed + - failed + - cancelled + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/ListVectorStoreFilesResponse' + x-oaiMeta: + name: List vector store files + group: vector_stores + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.vector_stores.files.list( + vector_store_id="vector_store_id", + ) + page = page.data[0] + print(page.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStoreFiles = await openai.vectorStores.files.list( + "vs_abc123" + ); + console.log(vectorStoreFiles); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const vectorStoreFile of + client.vectorStores.files.list('vector_store_id')) { + console.log(vectorStoreFile.id); + } + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.VectorStores.Files.List(\n\t\tcontext.TODO(),\n\t\t\"vector_store_id\",\n\t\topenai.VectorStoreFileListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.files.FileListPage; + import com.openai.models.vectorstores.files.FileListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileListPage page = client.vectorStores().files().list("vector_store_id"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.vector_stores.files.list("vector_store_id") + + puts(page) + response: | + { + "object": "list", + "data": [ + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abc123" + }, + { + "id": "file-abc456", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abc123" + } + ], + "first_id": "file-abc123", + "last_id": "file-abc456", + "has_more": false + } + post: + operationId: createVectorStoreFile + tags: + - Vector stores + summary: >- + Create a vector store file by attaching a + [File](/docs/api-reference/files) to a [vector + store](/docs/api-reference/vector-stores/object). + description: >- + This endpoint is subject to a per-vector-store write rate limit of 300 + requests per minute, shared with + `/vector_stores/{vector_store_id}/file_batches`. + + For uploading multiple files to the same vector store, use the file + batches endpoint to reduce request volume. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + example: vs_abc123 + description: | + The ID of the vector store for which to create a File. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/CreateVectorStoreFileRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreFileObject' + x-oaiMeta: + name: Create vector store file + group: vector_stores + description: > + Attaches one file to a vector store. File attach writes are + rate-limited per vector store (300 requests/minute shared with + `/vector_stores/{vector_store_id}/file_batches`), so use file batches + when uploading multiple files. + examples: + request: + curl: | + curl https://api.openai.com/v1/vector_stores/vs_abc123/files \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -d '{ + "file_id": "file-abc123" + }' + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + vector_store_file = client.vector_stores.files.create( + vector_store_id="vs_abc123", + file_id="file_id", + ) + print(vector_store_file.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const myVectorStoreFile = await openai.vectorStores.files.create( + "vs_abc123", + { + file_id: "file-abc123" + } + ); + console.log(myVectorStoreFile); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStoreFile = await + client.vectorStores.files.create('vs_abc123', { file_id: 'file_id' + }); + + + console.log(vectorStoreFile.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStoreFile, err := client.VectorStores.Files.New(\n\t\tcontext.TODO(),\n\t\t\"vs_abc123\",\n\t\topenai.VectorStoreFileNewParams{\n\t\t\tFileID: \"file_id\",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStoreFile.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.files.FileCreateParams; + import com.openai.models.vectorstores.files.VectorStoreFile; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileCreateParams params = FileCreateParams.builder() + .vectorStoreId("vs_abc123") + .fileId("file_id") + .build(); + VectorStoreFile vectorStoreFile = client.vectorStores().files().create(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + vector_store_file = openai.vector_stores.files.create("vs_abc123", + file_id: "file_id") + + + puts(vector_store_file) + response: | + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "usage_bytes": 1234, + "vector_store_id": "vs_abcd", + "status": "completed", + "last_error": null + } + /vector_stores/{vector_store_id}/files/{file_id}: + get: + operationId: getVectorStoreFile + tags: + - Vector stores + summary: Retrieves a vector store file. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + example: vs_abc123 + description: The ID of the vector store that the file belongs to. + - in: path + name: file_id + required: true + schema: + type: string + example: file-abc123 + description: The ID of the file being retrieved. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreFileObject' + x-oaiMeta: + name: Retrieve vector store file + group: vector_stores + examples: + request: + curl: > + curl + https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + vector_store_file = client.vector_stores.files.retrieve( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + print(vector_store_file.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const vectorStoreFile = await openai.vectorStores.files.retrieve( + "file-abc123", + { vector_store_id: "vs_abc123" } + ); + console.log(vectorStoreFile); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStoreFile = await + client.vectorStores.files.retrieve('file-abc123', { + vector_store_id: 'vs_abc123', + }); + + + console.log(vectorStoreFile.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStoreFile, err := client.VectorStores.Files.Get(\n\t\tcontext.TODO(),\n\t\t\"vs_abc123\",\n\t\t\"file-abc123\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStoreFile.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.files.FileRetrieveParams; + import com.openai.models.vectorstores.files.VectorStoreFile; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileRetrieveParams params = FileRetrieveParams.builder() + .vectorStoreId("vs_abc123") + .fileId("file-abc123") + .build(); + VectorStoreFile vectorStoreFile = client.vectorStores().files().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + vector_store_file = + openai.vector_stores.files.retrieve("file-abc123", + vector_store_id: "vs_abc123") + + + puts(vector_store_file) + response: | + { + "id": "file-abc123", + "object": "vector_store.file", + "created_at": 1699061776, + "vector_store_id": "vs_abcd", + "status": "completed", + "last_error": null + } + delete: + operationId: deleteVectorStoreFile + tags: + - Vector stores + summary: >- + Delete a vector store file. This will remove the file from the vector + store but the file itself will not be deleted. To delete the file, use + the [delete file](/docs/api-reference/files/delete) endpoint. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + description: The ID of the vector store that the file belongs to. + - in: path + name: file_id + required: true + schema: + type: string + description: The ID of the file to delete. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/DeleteVectorStoreFileResponse' + x-oaiMeta: + name: Delete vector store file + group: vector_stores + examples: + request: + curl: > + curl + https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123 + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -H "OpenAI-Beta: assistants=v2" \ + -X DELETE + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + vector_store_file_deleted = client.vector_stores.files.delete( + file_id="file_id", + vector_store_id="vector_store_id", + ) + print(vector_store_file_deleted.id) + javascript: | + import OpenAI from "openai"; + const openai = new OpenAI(); + + async function main() { + const deletedVectorStoreFile = await openai.vectorStores.files.delete( + "file-abc123", + { vector_store_id: "vs_abc123" } + ); + console.log(deletedVectorStoreFile); + } + + main(); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStoreFileDeleted = await + client.vectorStores.files.delete('file_id', { + vector_store_id: 'vector_store_id', + }); + + + console.log(vectorStoreFileDeleted.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStoreFileDeleted, err := client.VectorStores.Files.Delete(\n\t\tcontext.TODO(),\n\t\t\"vector_store_id\",\n\t\t\"file_id\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStoreFileDeleted.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.vectorstores.files.FileDeleteParams; + + import + com.openai.models.vectorstores.files.VectorStoreFileDeleted; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileDeleteParams params = FileDeleteParams.builder() + .vectorStoreId("vector_store_id") + .fileId("file_id") + .build(); + VectorStoreFileDeleted vectorStoreFileDeleted = client.vectorStores().files().delete(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + vector_store_file_deleted = + openai.vector_stores.files.delete("file_id", vector_store_id: + "vector_store_id") + + + puts(vector_store_file_deleted) + response: | + { + id: "file-abc123", + object: "vector_store.file.deleted", + deleted: true + } + post: + operationId: updateVectorStoreFileAttributes + tags: + - Vector stores + summary: Update attributes on a vector store file. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + example: vs_abc123 + description: The ID of the vector store the file belongs to. + - in: path + name: file_id + required: true + schema: + type: string + example: file-abc123 + description: The ID of the file to update attributes. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateVectorStoreFileAttributesRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreFileObject' + x-oaiMeta: + name: Update vector store file attributes + group: vector_stores + examples: + request: + curl: > + curl + https://api.openai.com/v1/vector_stores/{vector_store_id}/files/{file_id} + \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"attributes": {"key1": "value1", "key2": 2}}' + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const vectorStoreFile = await + client.vectorStores.files.update('file-abc123', { + vector_store_id: 'vs_abc123', + attributes: { foo: 'string' }, + }); + + + console.log(vectorStoreFile.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + vector_store_file = client.vector_stores.files.update( + file_id="file-abc123", + vector_store_id="vs_abc123", + attributes={ + "foo": "string" + }, + ) + print(vector_store_file.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvectorStoreFile, err := client.VectorStores.Files.Update(\n\t\tcontext.TODO(),\n\t\t\"vs_abc123\",\n\t\t\"file-abc123\",\n\t\topenai.VectorStoreFileUpdateParams{\n\t\t\tAttributes: map[string]openai.VectorStoreFileUpdateParamsAttributeUnion{\n\t\t\t\t\"foo\": {\n\t\t\t\t\tOfString: openai.String(\"string\"),\n\t\t\t\t},\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", vectorStoreFile.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.core.JsonValue; + import com.openai.models.vectorstores.files.FileUpdateParams; + import com.openai.models.vectorstores.files.VectorStoreFile; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileUpdateParams params = FileUpdateParams.builder() + .vectorStoreId("vs_abc123") + .fileId("file-abc123") + .attributes(FileUpdateParams.Attributes.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build()) + .build(); + VectorStoreFile vectorStoreFile = client.vectorStores().files().update(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + vector_store_file = openai.vector_stores.files.update( + "file-abc123", + vector_store_id: "vs_abc123", + attributes: {foo: "string"} + ) + + puts(vector_store_file) + response: | + { + "id": "file-abc123", + "object": "vector_store.file", + "usage_bytes": 1234, + "created_at": 1699061776, + "vector_store_id": "vs_abcd", + "status": "completed", + "last_error": null, + "chunking_strategy": {...}, + "attributes": {"key1": "value1", "key2": 2} + } + /vector_stores/{vector_store_id}/files/{file_id}/content: + get: + operationId: retrieveVectorStoreFileContent + tags: + - Vector stores + summary: Retrieve the parsed contents of a vector store file. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + example: vs_abc123 + description: The ID of the vector store. + - in: path + name: file_id + required: true + schema: + type: string + example: file-abc123 + description: The ID of the file within the vector store. + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreFileContentResponse' + x-oaiMeta: + name: Retrieve vector store file content + group: vector_stores + examples: + request: + curl: > + curl \ + + https://api.openai.com/v1/vector_stores/vs_abc123/files/file-abc123/content + \ + + -H "Authorization: Bearer $OPENAI_API_KEY" + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const fileContentResponse of + client.vectorStores.files.content('file-abc123', { + vector_store_id: 'vs_abc123', + })) { + console.log(fileContentResponse.text); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.vector_stores.files.content( + file_id="file-abc123", + vector_store_id="vs_abc123", + ) + page = page.data[0] + print(page.text) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.VectorStores.Files.Content(\n\t\tcontext.TODO(),\n\t\t\"vs_abc123\",\n\t\t\"file-abc123\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.files.FileContentPage; + import com.openai.models.vectorstores.files.FileContentParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + FileContentParams params = FileContentParams.builder() + .vectorStoreId("vs_abc123") + .fileId("file-abc123") + .build(); + FileContentPage page = client.vectorStores().files().content(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + page = openai.vector_stores.files.content("file-abc123", + vector_store_id: "vs_abc123") + + + puts(page) + response: | + { + "file_id": "file-abc123", + "filename": "example.txt", + "attributes": {"key": "value"}, + "content": [ + {"type": "text", "text": "..."}, + ... + ] + } + /vector_stores/{vector_store_id}/search: + post: + operationId: searchVectorStore + tags: + - Vector stores + summary: >- + Search a vector store for relevant chunks based on a query and file + attributes filter. + parameters: + - in: path + name: vector_store_id + required: true + schema: + type: string + example: vs_abc123 + description: The ID of the vector store to search. + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreSearchRequest' + responses: + '200': + description: OK + content: + application/json: + schema: + $ref: '#/components/schemas/VectorStoreSearchResultsPage' + x-oaiMeta: + name: Search vector store + group: vector_stores + examples: + request: + curl: | + curl -X POST \ + https://api.openai.com/v1/vector_stores/vs_abc123/search \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{"query": "What is the return policy?", "filters": {...}}' + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const vectorStoreSearchResponse of + client.vectorStores.search('vs_abc123', { + query: 'string', + })) { + console.log(vectorStoreSearchResponse.file_id); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.vector_stores.search( + vector_store_id="vs_abc123", + query="string", + ) + page = page.data[0] + print(page.file_id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.VectorStores.Search(\n\t\tcontext.TODO(),\n\t\t\"vs_abc123\",\n\t\topenai.VectorStoreSearchParams{\n\t\t\tQuery: openai.VectorStoreSearchParamsQueryUnion{\n\t\t\t\tOfString: openai.String(\"string\"),\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.vectorstores.VectorStoreSearchPage; + import com.openai.models.vectorstores.VectorStoreSearchParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VectorStoreSearchParams params = VectorStoreSearchParams.builder() + .vectorStoreId("vs_abc123") + .query("string") + .build(); + VectorStoreSearchPage page = client.vectorStores().search(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.vector_stores.search("vs_abc123", query: "string") + + puts(page) + response: | + { + "object": "vector_store.search_results.page", + "search_query": "What is the return policy?", + "data": [ + { + "file_id": "file_123", + "filename": "document.pdf", + "score": 0.95, + "attributes": { + "author": "John Doe", + "date": "2023-01-01" + }, + "content": [ + { + "type": "text", + "text": "Relevant chunk" + } + ] + }, + { + "file_id": "file_456", + "filename": "notes.txt", + "score": 0.89, + "attributes": { + "author": "Jane Smith", + "date": "2023-01-02" + }, + "content": [ + { + "type": "text", + "text": "Sample text content from the vector store." + } + ] + } + ], + "has_more": false, + "next_page": null + } + /conversations: + post: + tags: + - Conversations + summary: Create a conversation. + operationId: createConversation + parameters: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CreateConversationBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationResource' + x-oaiMeta: + name: Create a conversation + group: conversations + path: create + examples: + request: + curl: | + curl https://api.openai.com/v1/conversations \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "metadata": {"topic": "demo"}, + "items": [ + { + "type": "message", + "role": "user", + "content": "Hello!" + } + ] + }' + javascript: | + import OpenAI from "openai"; + const client = new OpenAI(); + + const conversation = await client.conversations.create({ + metadata: { topic: "demo" }, + items: [ + { type: "message", role: "user", content: "Hello!" } + ], + }); + console.log(conversation); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + conversation = client.conversations.create() + print(conversation.id) + csharp: | + using System; + using System.Collections.Generic; + using OpenAI.Conversations; + + OpenAIConversationClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + Conversation conversation = client.CreateConversation( + new CreateConversationOptions + { + Metadata = new Dictionary + { + { "topic", "demo" } + }, + Items = + { + new ConversationMessageInput + { + Role = "user", + Content = "Hello!", + } + } + } + ); + Console.WriteLine(conversation.Id); + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const conversation = await client.conversations.create(); + + console.log(conversation.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/conversations\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tconversation, err := client.Conversations.New(context.TODO(), conversations.ConversationNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", conversation.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.conversations.Conversation; + import com.openai.models.conversations.ConversationCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Conversation conversation = client.conversations().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + conversation = openai.conversations.create + + puts(conversation) + response: | + { + "id": "conv_123", + "object": "conversation", + "created_at": 1741900000, + "metadata": {"topic": "demo"} + } + /conversations/{conversation_id}: + get: + tags: + - Conversations + summary: Get a conversation + operationId: getConversation + parameters: + - name: conversation_id + in: path + description: The ID of the conversation to retrieve. + required: true + schema: + example: conv_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationResource' + x-oaiMeta: + name: Retrieve a conversation + group: conversations + path: retrieve + examples: + request: + curl: | + curl https://api.openai.com/v1/conversations/conv_123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: > + import OpenAI from "openai"; + + const client = new OpenAI(); + + + const conversation = await + client.conversations.retrieve("conv_123"); + + console.log(conversation); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + conversation = client.conversations.retrieve( + "conv_123", + ) + print(conversation.id) + csharp: | + using System; + using OpenAI.Conversations; + + OpenAIConversationClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + Conversation conversation = client.GetConversation("conv_123"); + Console.WriteLine(conversation.Id); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const conversation = await + client.conversations.retrieve('conv_123'); + + + console.log(conversation.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tconversation, err := client.Conversations.Get(context.TODO(), \"conv_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", conversation.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.conversations.Conversation; + import com.openai.models.conversations.ConversationRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Conversation conversation = client.conversations().retrieve("conv_123"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + conversation = openai.conversations.retrieve("conv_123") + + puts(conversation) + response: | + { + "id": "conv_123", + "object": "conversation", + "created_at": 1741900000, + "metadata": {"topic": "demo"} + } + delete: + tags: + - Conversations + summary: Delete a conversation. Items in the conversation will not be deleted. + operationId: deleteConversation + parameters: + - name: conversation_id + in: path + description: The ID of the conversation to delete. + required: true + schema: + example: conv_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/DeletedConversationResource' + x-oaiMeta: + name: Delete a conversation + group: conversations + path: delete + examples: + request: + curl: | + curl -X DELETE https://api.openai.com/v1/conversations/conv_123 \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: | + import OpenAI from "openai"; + const client = new OpenAI(); + + const deleted = await client.conversations.delete("conv_123"); + console.log(deleted); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + conversation_deleted_resource = client.conversations.delete( + "conv_123", + ) + print(conversation_deleted_resource.id) + csharp: > + using System; + + using OpenAI.Conversations; + + + OpenAIConversationClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + + DeletedConversation deleted = + client.DeleteConversation("conv_123"); + + Console.WriteLine(deleted.Id); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const conversationDeletedResource = await + client.conversations.delete('conv_123'); + + + console.log(conversationDeletedResource.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tconversationDeletedResource, err := client.Conversations.Delete(context.TODO(), \"conv_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", conversationDeletedResource.ID)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.conversations.ConversationDeleteParams; + + import + com.openai.models.conversations.ConversationDeletedResource; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ConversationDeletedResource conversationDeletedResource = client.conversations().delete("conv_123"); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + conversation_deleted_resource = + openai.conversations.delete("conv_123") + + + puts(conversation_deleted_resource) + response: | + { + "id": "conv_123", + "object": "conversation.deleted", + "deleted": true + } + post: + tags: + - Conversations + summary: Update a conversation + operationId: updateConversation + parameters: + - name: conversation_id + in: path + description: The ID of the conversation to update. + required: true + schema: + example: conv_123 + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/UpdateConversationBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ConversationResource' + x-oaiMeta: + name: Update a conversation + group: conversations + path: update + examples: + request: + curl: | + curl https://api.openai.com/v1/conversations/conv_123 \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "metadata": {"topic": "project-x"} + }' + javascript: | + import OpenAI from "openai"; + const client = new OpenAI(); + + const updated = await client.conversations.update( + "conv_123", + { metadata: { topic: "project-x" } } + ); + console.log(updated); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + conversation = client.conversations.update( + conversation_id="conv_123", + metadata={ + "foo": "string" + }, + ) + print(conversation.id) + csharp: | + using System; + using System.Collections.Generic; + using OpenAI.Conversations; + + OpenAIConversationClient client = new( + apiKey: Environment.GetEnvironmentVariable("OPENAI_API_KEY") + ); + + Conversation updated = client.UpdateConversation( + conversationId: "conv_123", + new UpdateConversationOptions + { + Metadata = new Dictionary + { + { "topic", "project-x" } + } + } + ); + Console.WriteLine(updated.Id); + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const conversation = await client.conversations.update('conv_123', + { metadata: { foo: 'string' } }); + + + console.log(conversation.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/conversations\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/shared\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tconversation, err := client.Conversations.Update(\n\t\tcontext.TODO(),\n\t\t\"conv_123\",\n\t\tconversations.ConversationUpdateParams{\n\t\t\tMetadata: shared.Metadata{\n\t\t\t\t\"foo\": \"string\",\n\t\t\t},\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", conversation.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.core.JsonValue; + import com.openai.models.conversations.Conversation; + import com.openai.models.conversations.ConversationUpdateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ConversationUpdateParams params = ConversationUpdateParams.builder() + .conversationId("conv_123") + .metadata(ConversationUpdateParams.Metadata.builder() + .putAdditionalProperty("foo", JsonValue.from("string")) + .build()) + .build(); + Conversation conversation = client.conversations().update(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + conversation = openai.conversations.update("conv_123", metadata: + {foo: "string"}) + + + puts(conversation) + response: | + { + "id": "conv_123", + "object": "conversation", + "created_at": 1741900000, + "metadata": {"topic": "project-x"} + } + /videos: + post: + tags: + - Videos + summary: >- + Create a new video generation job from a prompt and optional reference + assets. + operationId: createVideo + parameters: [] + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateVideoMultipartBody' + application/json: + schema: + $ref: '#/components/schemas/CreateVideoJsonBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/VideoResource' + x-oaiMeta: + name: Create video + group: videos + path: create + examples: + request: + curl: | + curl https://api.openai.com/v1/videos \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -F "model=sora-2" \ + -F "prompt=A calico cat playing a piano on stage" + javascript: > + import OpenAI from 'openai'; + + + const openai = new OpenAI(); + + + const video = await openai.videos.create({ prompt: 'A calico cat + playing a piano on stage' }); + + + console.log(video.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + video = client.videos.create( + prompt="x", + ) + print(video.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvideo, err := client.Videos.New(context.TODO(), openai.VideoNewParams{\n\t\tPrompt: \"x\",\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", video.ID)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + video = openai.videos.create(prompt: "x") + + puts(video) + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.videos.Video; + import com.openai.models.videos.VideoCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VideoCreateParams params = VideoCreateParams.builder() + .prompt("x") + .build(); + Video video = client.videos().create(params); + } + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const video = await client.videos.create({ prompt: 'x' }); + + console.log(video.id); + response: | + { + "id": "video_123", + "object": "video", + "model": "sora-2", + "status": "queued", + "progress": 0, + "created_at": 1712697600, + "size": "1024x1792", + "seconds": "8", + "quality": "standard" + } + get: + tags: + - Videos + summary: List recently generated videos for the current project. + operationId: ListVideos + parameters: + - name: limit + in: query + description: Number of items to retrieve + required: false + schema: + type: integer + minimum: 0 + maximum: 100 + - name: order + in: query + description: >- + Sort order of results by timestamp. Use `asc` for ascending order or + `desc` for descending order. + required: false + schema: + $ref: '#/components/schemas/OrderEnum' + - name: after + in: query + description: Identifier for the last item from the previous pagination request + required: false + schema: + description: Identifier for the last item from the previous pagination request + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/VideoListResource' + x-oaiMeta: + name: List videos + group: videos + path: list for the organization. + examples: + request: + curl: | + curl https://api.openai.com/v1/videos \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: | + import OpenAI from 'openai'; + + const openai = new OpenAI(); + + // Automatically fetches more pages as needed. + for await (const video of openai.videos.list()) { + console.log(video.id); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.videos.list() + page = page.data[0] + print(page.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Videos.List(context.TODO(), openai.VideoListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.videos.list + + puts(page) + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.videos.VideoListPage; + import com.openai.models.videos.VideoListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VideoListPage page = client.videos().list(); + } + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + // Automatically fetches more pages as needed. + for await (const video of client.videos.list()) { + console.log(video.id); + } + response: | + { + "data": [ + { + "id": "video_123", + "object": "video", + "model": "sora-2", + "status": "completed" + } + ], + "object": "list" + } + /videos/characters: + post: + tags: + - Videos + summary: Create a character from an uploaded video. + operationId: CreateVideoCharacter + parameters: [] + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateVideoCharacterBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/VideoCharacterResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: |- + import fs from 'fs'; + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.videos.createCharacter({ + name: 'x', + video: fs.createReadStream('path/to/file'), + }); + + console.log(response.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.videos.create_character( + name="x", + video=b"Example data", + ) + print(response.id) + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Videos.NewCharacter(context.TODO(), openai.VideoNewCharacterParams{\n\t\tName: \"x\",\n\t\tVideo: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.videos.VideoCreateCharacterParams; + import com.openai.models.videos.VideoCreateCharacterResponse; + import java.io.ByteArrayInputStream; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VideoCreateCharacterParams params = VideoCreateCharacterParams.builder() + .name("x") + .video(new ByteArrayInputStream("Example data".getBytes())) + .build(); + VideoCreateCharacterResponse response = client.videos().createCharacter(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + response = openai.videos.create_character(name: "x", video: + StringIO.new("Example data")) + + + puts(response) + /videos/characters/{character_id}: + get: + tags: + - Videos + summary: Fetch a character. + operationId: GetVideoCharacter + parameters: + - name: character_id + in: path + description: The identifier of the character to retrieve. + required: true + schema: + example: char_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/VideoCharacterResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.videos.getCharacter('char_123'); + + console.log(response.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.videos.get_character( + "char_123", + ) + print(response.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Videos.GetCharacter(context.TODO(), \"char_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.videos.VideoGetCharacterParams; + import com.openai.models.videos.VideoGetCharacterResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VideoGetCharacterResponse response = client.videos().getCharacter("char_123"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.videos.get_character("char_123") + + puts(response) + /videos/edits: + post: + tags: + - Videos + summary: >- + Create a new video generation job by editing a source video or existing + generated video. + operationId: CreateVideoEdit + parameters: [] + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateVideoEditMultipartBody' + application/json: + schema: + $ref: '#/components/schemas/CreateVideoEditJsonBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/VideoResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const video = await client.videos.edit({ prompt: 'x', video: + fs.createReadStream('path/to/file') }); + + + console.log(video.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + video = client.videos.edit( + prompt="x", + video=b"Example data", + ) + print(video.id) + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvideo, err := client.Videos.Edit(context.TODO(), openai.VideoEditParams{\n\t\tPrompt: \"x\",\n\t\tVideo: openai.VideoEditParamsVideoUnion{\n\t\t\tOfFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", video.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.videos.Video; + import com.openai.models.videos.VideoEditParams; + import java.io.ByteArrayInputStream; + import java.io.InputStream; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VideoEditParams params = VideoEditParams.builder() + .prompt("x") + .video(new ByteArrayInputStream("Example data".getBytes())) + .build(); + Video video = client.videos().edit(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + video = openai.videos.edit(prompt: "x", video: + StringIO.new("Example data")) + + + puts(video) + /videos/extensions: + post: + tags: + - Videos + summary: Create an extension of a completed video. + operationId: CreateVideoExtend + parameters: [] + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateVideoExtendMultipartBody' + application/json: + schema: + $ref: '#/components/schemas/CreateVideoExtendJsonBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/VideoResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const video = await client.videos.extend({ + prompt: 'x', + seconds: '4', + video: fs.createReadStream('path/to/file'), + }); + + console.log(video.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + video = client.videos.extend( + prompt="x", + seconds="4", + video=b"Example data", + ) + print(video.id) + go: "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"io\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvideo, err := client.Videos.Extend(context.TODO(), openai.VideoExtendParams{\n\t\tPrompt: \"x\",\n\t\tSeconds: openai.VideoSeconds4,\n\t\tVideo: openai.VideoExtendParamsVideoUnion{\n\t\t\tOfFile: io.Reader(bytes.NewBuffer([]byte(\"Example data\"))),\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", video.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.videos.Video; + import com.openai.models.videos.VideoExtendParams; + import com.openai.models.videos.VideoSeconds; + import java.io.ByteArrayInputStream; + import java.io.InputStream; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VideoExtendParams params = VideoExtendParams.builder() + .prompt("x") + .seconds(VideoSeconds._4) + .video(new ByteArrayInputStream("Example data".getBytes())) + .build(); + Video video = client.videos().extend(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + video = openai.videos.extend_(prompt: "x", seconds: :"4", video: + StringIO.new("Example data")) + + + puts(video) + /videos/{video_id}: + get: + tags: + - Videos + summary: Fetch the latest metadata for a generated video. + operationId: GetVideo + parameters: + - name: video_id + in: path + description: The identifier of the video to retrieve. + required: true + schema: + example: video_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/VideoResource' + x-oaiMeta: + name: Retrieve video + group: videos + path: retrieve matching the provided identifier. + examples: + response: '' + request: + javascript: | + import OpenAI from 'openai'; + + const client = new OpenAI(); + + const video = await client.videos.retrieve('video_123'); + + console.log(video.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + video = client.videos.retrieve( + "video_123", + ) + print(video.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvideo, err := client.Videos.Get(context.TODO(), \"video_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", video.ID)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + video = openai.videos.retrieve("video_123") + + puts(video) + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.videos.Video; + import com.openai.models.videos.VideoRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Video video = client.videos().retrieve("video_123"); + } + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const video = await client.videos.retrieve('video_123'); + + console.log(video.id); + delete: + tags: + - Videos + summary: Permanently delete a completed or failed video and its stored assets. + operationId: DeleteVideo + parameters: + - name: video_id + in: path + description: The identifier of the video to delete. + required: true + schema: + example: video_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/DeletedVideoResource' + x-oaiMeta: + name: Delete video + group: videos + path: delete + examples: + response: '' + request: + javascript: | + import OpenAI from 'openai'; + + const client = new OpenAI(); + + const video = await client.videos.delete('video_123'); + + console.log(video.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + video = client.videos.delete( + "video_123", + ) + print(video.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvideo, err := client.Videos.Delete(context.TODO(), \"video_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", video.ID)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + video = openai.videos.delete("video_123") + + puts(video) + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.videos.VideoDeleteParams; + import com.openai.models.videos.VideoDeleteResponse; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VideoDeleteResponse video = client.videos().delete("video_123"); + } + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const video = await client.videos.delete('video_123'); + + console.log(video.id); + /videos/{video_id}/content: + get: + tags: + - Videos + summary: |- + Download the generated video bytes or a derived preview asset. + + Streams the rendered video content for the specified video job. + operationId: RetrieveVideoContent + parameters: + - name: video_id + in: path + description: The identifier of the video whose media to download. + required: true + schema: + example: video_123 + type: string + - name: variant + in: query + description: Which downloadable asset to return. Defaults to the MP4 video. + required: false + schema: + $ref: '#/components/schemas/VideoContentVariant' + responses: + '200': + description: The video bytes or preview asset that matches the requested variant. + content: + video/mp4: + schema: + type: string + format: binary + image/webp: + schema: + type: string + format: binary + application/json: + schema: + type: string + x-oaiMeta: + name: Retrieve video content + group: videos + path: content + examples: + response: '' + request: + javascript: | + import OpenAI from 'openai'; + + const client = new OpenAI(); + + const response = await client.videos.downloadContent('video_123'); + + console.log(response); + + const content = await response.blob(); + console.log(content); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.videos.download_content( + video_id="video_123", + ) + print(response) + content = response.read() + print(content) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Videos.DownloadContent(\n\t\tcontext.TODO(),\n\t\t\"video_123\",\n\t\topenai.VideoDownloadContentParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.videos.download_content("video_123") + + puts(response) + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.core.http.HttpResponse; + import com.openai.models.videos.VideoDownloadContentParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + HttpResponse response = client.videos().downloadContent("video_123"); + } + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.videos.downloadContent('video_123'); + + console.log(response); + + const content = await response.blob(); + console.log(content); + /videos/{video_id}/remix: + post: + tags: + - Videos + summary: Create a remix of a completed video using a refreshed prompt. + operationId: CreateVideoRemix + parameters: + - name: video_id + in: path + description: The identifier of the completed video to remix. + required: true + schema: + example: video_123 + type: string + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateVideoRemixBody' + application/json: + schema: + $ref: '#/components/schemas/CreateVideoRemixBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/VideoResource' + x-oaiMeta: + name: Remix video + group: videos + path: remix using the provided prompt. + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/videos/video_123/remix \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "Content-Type: application/json" \ + -d '{ + "prompt": "Extend the scene with the cat taking a bow to the cheering audience" + }' + javascript: > + import OpenAI from 'openai'; + + + const client = new OpenAI(); + + + const video = await client.videos.remix('video_123', { prompt: + 'Extend the scene with the cat taking a bow to the cheering + audience' }); + + + console.log(video.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + video = client.videos.remix( + video_id="video_123", + prompt="x", + ) + print(video.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tvideo, err := client.Videos.Remix(\n\t\tcontext.TODO(),\n\t\t\"video_123\",\n\t\topenai.VideoRemixParams{\n\t\t\tPrompt: \"x\",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", video.ID)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + video = openai.videos.remix("video_123", prompt: "x") + + puts(video) + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.videos.Video; + import com.openai.models.videos.VideoRemixParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VideoRemixParams params = VideoRemixParams.builder() + .videoId("video_123") + .prompt("x") + .build(); + Video video = client.videos().remix(params); + } + } + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const video = await client.videos.remix('video_123', { prompt: 'x' + }); + + + console.log(video.id); + response: | + { + "id": "video_456", + "object": "video", + "model": "sora-2", + "status": "queued", + "progress": 0, + "created_at": 1712698600, + "size": "720x1280", + "seconds": "8", + "remixed_from_video_id": "video_123" + } + /responses/input_tokens: + post: + summary: >- + Returns input token counts of the request. + + + Returns an object with `object` set to `response.input_tokens` and an + `input_tokens` count. + operationId: Getinputtokencounts + parameters: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/TokenCountsBody' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/TokenCountsBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/TokenCountsResource' + x-oaiMeta: + name: Get input token counts + group: responses + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/responses/input_tokens \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5", + "input": "Tell me a joke." + }' + javascript: | + import OpenAI from "openai"; + + const client = new OpenAI(); + + const response = await client.responses.inputTokens.count({ + model: "gpt-5", + input: "Tell me a joke.", + }); + + console.log(response.input_tokens); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + response = client.responses.input_tokens.count() + print(response.input_tokens) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tresponse, err := client.Responses.InputTokens.Count(context.TODO(), responses.InputTokenCountParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", response.InputTokens)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + response = openai.responses.input_tokens.count + + puts(response) + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.responses.inputtokens.InputTokenCountParams; + + import + com.openai.models.responses.inputtokens.InputTokenCountResponse; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + InputTokenCountResponse response = client.responses().inputTokens().count(); + } + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const response = await client.responses.inputTokens.count(); + + console.log(response.input_tokens); + response: | + { + "object": "response.input_tokens", + "input_tokens": 11 + } + /responses/compact: + post: + summary: >- + Compact a conversation. Returns a compacted response object. + + + Learn when and how to compact long-running conversations in the + [conversation state + guide](/docs/guides/conversation-state#managing-the-context-window). For + ZDR-compatible compaction details, see [Compaction + (advanced)](/docs/guides/conversation-state#compaction-advanced). + operationId: Compactconversation + parameters: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CompactResponseMethodPublicBody' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/CompactResponseMethodPublicBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/CompactResource' + x-oaiMeta: + name: Compact a response + group: responses + examples: + request: + curl: | + curl -X POST https://api.openai.com/v1/responses/compact \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -d '{ + "model": "gpt-5.1-codex-max", + "input": [ + { + "role": "user", + "content": "Create a simple landing page for a dog petting café." + }, + { + "id": "msg_001", + "type": "message", + "status": "completed", + "content": [ + { + "type": "output_text", + "annotations": [], + "logprobs": [], + "text": "Below is a single file, ready-to-use landing page for a dog petting café:..." + } + ], + "role": "assistant" + } + ] + }' + javascript: | + import OpenAI from "openai"; + + const openai = new OpenAI(); + + // Compact the previous response if you are running out of tokens + const compactedResponse = await openai.responses.compact({ + model: "gpt-5.1-codex-max", + input: [ + { + role: "user", + content: "Create a simple landing page for a dog petting café.", + }, + // All items returned from previous requests are included here, like reasoning, message, function call, etc. + { + id: "msg_030d085c0b53e67e0069332e3a72d4819c96c6f2c4adc15d33", + type: "message", + status: "completed", + content: [ + { + type: "output_text", + annotations: [], + logprobs: [], + text: "Below is a single file, ready-to-use landing page for a dog petting café:...", + }, + ], + role: "assistant", + }, + ], + }); + + // Pass the compactedResponse.output as input to the next request + console.log(compactedResponse); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + compacted_response = client.responses.compact( + model="gpt-5.4", + ) + print(compacted_response.id) + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const compactedResponse = await client.responses.compact({ model: + 'gpt-5.4' }); + + + console.log(compactedResponse.id); + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n\t\"github.com/openai/openai-go/responses\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tcompactedResponse, err := client.Responses.Compact(context.TODO(), responses.ResponseCompactParams{\n\t\tModel: responses.ResponseCompactParamsModelGPT5_4,\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", compactedResponse.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.responses.CompactedResponse; + import com.openai.models.responses.ResponseCompactParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ResponseCompactParams params = ResponseCompactParams.builder() + .model(ResponseCompactParams.Model.GPT_5_4) + .build(); + CompactedResponse compactedResponse = client.responses().compact(params); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + compacted_response = openai.responses.compact(model: :"gpt-5.4") + + puts(compacted_response) + response: | + { + "id": "resp_001", + "object": "response.compaction", + "created_at": 1764967971, + "output": [ + { + "id": "msg_000", + "type": "message", + "status": "completed", + "content": [ + { + "type": "input_text", + "text": "Create a simple landing page for a dog petting cafe." + } + ], + "role": "user" + }, + { + "id": "cmp_001", + "type": "compaction", + "encrypted_content": "gAAAAABpM0Yj-...=" + } + ], + "usage": { + "input_tokens": 139, + "input_tokens_details": { + "cached_tokens": 0 + }, + "output_tokens": 438, + "output_tokens_details": { + "reasoning_tokens": 64 + }, + "total_tokens": 577 + } + } + /skills: + post: + tags: + - Skills + summary: Create a new skill. + operationId: CreateSkill + parameters: [] + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateSkillBody' + application/json: + schema: + $ref: '#/components/schemas/CreateSkillBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/SkillResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const skill = await client.skills.create(); + + console.log(skill.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + skill = client.skills.create() + print(skill.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tskill, err := client.Skills.New(context.TODO(), openai.SkillNewParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", skill.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.skills.Skill; + import com.openai.models.skills.SkillCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Skill skill = client.skills().create(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + skill = openai.skills.create + + puts(skill) + get: + tags: + - Skills + summary: List all skills for the current project. + operationId: ListSkills + parameters: + - name: limit + in: query + description: Number of items to retrieve + required: false + schema: + type: integer + minimum: 0 + maximum: 100 + - name: order + in: query + description: >- + Sort order of results by timestamp. Use `asc` for ascending order or + `desc` for descending order. + required: false + schema: + $ref: '#/components/schemas/OrderEnum' + - name: after + in: query + description: Identifier for the last item from the previous pagination request + required: false + schema: + description: Identifier for the last item from the previous pagination request + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/SkillListResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + // Automatically fetches more pages as needed. + for await (const skill of client.skills.list()) { + console.log(skill.id); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.skills.list() + page = page.data[0] + print(page.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Skills.List(context.TODO(), openai.SkillListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.skills.SkillListPage; + import com.openai.models.skills.SkillListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + SkillListPage page = client.skills().list(); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.skills.list + + puts(page) + /skills/{skill_id}: + delete: + tags: + - Skills + summary: Delete a skill by its ID. + operationId: DeleteSkill + parameters: + - name: skill_id + in: path + description: The identifier of the skill to delete. + required: true + schema: + example: skill_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/DeletedSkillResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const deletedSkill = await client.skills.delete('skill_123'); + + console.log(deletedSkill.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + deleted_skill = client.skills.delete( + "skill_123", + ) + print(deleted_skill.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tdeletedSkill, err := client.Skills.Delete(context.TODO(), \"skill_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", deletedSkill.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.skills.DeletedSkill; + import com.openai.models.skills.SkillDeleteParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + DeletedSkill deletedSkill = client.skills().delete("skill_123"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + deleted_skill = openai.skills.delete("skill_123") + + puts(deleted_skill) + get: + tags: + - Skills + summary: Get a skill by its ID. + operationId: GetSkill + parameters: + - name: skill_id + in: path + description: The identifier of the skill to retrieve. + required: true + schema: + example: skill_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/SkillResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const skill = await client.skills.retrieve('skill_123'); + + console.log(skill.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + skill = client.skills.retrieve( + "skill_123", + ) + print(skill.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tskill, err := client.Skills.Get(context.TODO(), \"skill_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", skill.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.skills.Skill; + import com.openai.models.skills.SkillRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + Skill skill = client.skills().retrieve("skill_123"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + skill = openai.skills.retrieve("skill_123") + + puts(skill) + post: + tags: + - Skills + summary: Update the default version pointer for a skill. + operationId: UpdateSkillDefaultVersion + parameters: + - name: skill_id + in: path + description: The identifier of the skill. + required: true + schema: + example: skill_123 + type: string + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/SetDefaultSkillVersionBody' + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/SetDefaultSkillVersionBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/SkillResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const skill = await client.skills.update('skill_123', { + default_version: 'default_version' }); + + + console.log(skill.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + skill = client.skills.update( + skill_id="skill_123", + default_version="default_version", + ) + print(skill.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tskill, err := client.Skills.Update(\n\t\tcontext.TODO(),\n\t\t\"skill_123\",\n\t\topenai.SkillUpdateParams{\n\t\t\tDefaultVersion: \"default_version\",\n\t\t},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", skill.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.skills.Skill; + import com.openai.models.skills.SkillUpdateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + SkillUpdateParams params = SkillUpdateParams.builder() + .skillId("skill_123") + .defaultVersion("default_version") + .build(); + Skill skill = client.skills().update(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + skill = openai.skills.update("skill_123", default_version: + "default_version") + + + puts(skill) + /skills/{skill_id}/content: + get: + tags: + - Skills + summary: Download a skill zip bundle by its ID. + operationId: GetSkillContent + parameters: + - name: skill_id + in: path + description: The identifier of the skill to download. + required: true + schema: + example: skill_123 + type: string + responses: + '200': + description: The skill zip bundle. + content: + application/zip: + schema: + type: string + format: binary + application/json: + schema: + type: string + x-oaiMeta: + examples: + response: '' + request: + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const content = await client.skills.content.retrieve('skill_123'); + + console.log(content); + + const data = await content.blob(); + console.log(data); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + content = client.skills.content.retrieve( + "skill_123", + ) + print(content) + data = content.read() + print(data) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tcontent, err := client.Skills.Content.Get(context.TODO(), \"skill_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", content)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.core.http.HttpResponse; + import com.openai.models.skills.content.ContentRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + HttpResponse content = client.skills().content().retrieve("skill_123"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + content = openai.skills.content.retrieve("skill_123") + + puts(content) + /skills/{skill_id}/versions: + post: + tags: + - Skills + summary: Create a new immutable skill version. + operationId: CreateSkillVersion + parameters: + - name: skill_id + in: path + description: The identifier of the skill to version. + required: true + schema: + example: skill_123 + type: string + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/CreateSkillVersionBody' + application/json: + schema: + $ref: '#/components/schemas/CreateSkillVersionBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/SkillVersionResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const skillVersion = await + client.skills.versions.create('skill_123'); + + + console.log(skillVersion.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + skill_version = client.skills.versions.create( + skill_id="skill_123", + ) + print(skill_version.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tskillVersion, err := client.Skills.Versions.New(\n\t\tcontext.TODO(),\n\t\t\"skill_123\",\n\t\topenai.SkillVersionNewParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", skillVersion.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.skills.versions.SkillVersion; + import com.openai.models.skills.versions.VersionCreateParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + SkillVersion skillVersion = client.skills().versions().create("skill_123"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + skill_version = openai.skills.versions.create("skill_123") + + puts(skill_version) + get: + tags: + - Skills + summary: List skill versions for a skill. + operationId: ListSkillVersions + parameters: + - name: skill_id + in: path + description: The identifier of the skill. + required: true + schema: + example: skill_123 + type: string + - name: limit + in: query + description: Number of versions to retrieve. + required: false + schema: + type: integer + minimum: 0 + maximum: 100 + - name: order + in: query + description: Sort order of results by version number. + required: false + schema: + $ref: '#/components/schemas/OrderEnum' + - name: after + in: query + description: The skill version ID to start after. + required: false + schema: + example: skillver_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/SkillVersionListResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const skillVersion of + client.skills.versions.list('skill_123')) { + console.log(skillVersion.id); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.skills.versions.list( + skill_id="skill_123", + ) + page = page.data[0] + print(page.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Skills.Versions.List(\n\t\tcontext.TODO(),\n\t\t\"skill_123\",\n\t\topenai.SkillVersionListParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.skills.versions.VersionListPage; + import com.openai.models.skills.versions.VersionListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VersionListPage page = client.skills().versions().list("skill_123"); + } + } + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.skills.versions.list("skill_123") + + puts(page) + /skills/{skill_id}/versions/{version}: + get: + tags: + - Skills + summary: Get a specific skill version. + operationId: GetSkillVersion + parameters: + - name: skill_id + in: path + description: The identifier of the skill. + required: true + schema: + example: skill_123 + type: string + - name: version + in: path + description: The version number to retrieve. + required: true + schema: + description: The version number to retrieve. + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/SkillVersionResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const skillVersion = await + client.skills.versions.retrieve('version', { skill_id: 'skill_123' + }); + + + console.log(skillVersion.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + skill_version = client.skills.versions.retrieve( + version="version", + skill_id="skill_123", + ) + print(skill_version.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tskillVersion, err := client.Skills.Versions.Get(\n\t\tcontext.TODO(),\n\t\t\"skill_123\",\n\t\t\"version\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", skillVersion.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.skills.versions.SkillVersion; + import com.openai.models.skills.versions.VersionRetrieveParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VersionRetrieveParams params = VersionRetrieveParams.builder() + .skillId("skill_123") + .version("version") + .build(); + SkillVersion skillVersion = client.skills().versions().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + skill_version = openai.skills.versions.retrieve("version", + skill_id: "skill_123") + + + puts(skill_version) + delete: + tags: + - Skills + summary: Delete a skill version. + operationId: DeleteSkillVersion + parameters: + - name: skill_id + in: path + description: The identifier of the skill. + required: true + schema: + example: skill_123 + type: string + - name: version + in: path + description: The skill version number. + required: true + schema: + description: The skill version number. + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/DeletedSkillVersionResource' + x-oaiMeta: + examples: + response: '' + request: + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const deletedSkillVersion = await + client.skills.versions.delete('version', { + skill_id: 'skill_123', + }); + + + console.log(deletedSkillVersion.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + deleted_skill_version = client.skills.versions.delete( + version="version", + skill_id="skill_123", + ) + print(deleted_skill_version.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tdeletedSkillVersion, err := client.Skills.Versions.Delete(\n\t\tcontext.TODO(),\n\t\t\"skill_123\",\n\t\t\"version\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", deletedSkillVersion.ID)\n}\n" + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.skills.versions.DeletedSkillVersion; + import com.openai.models.skills.versions.VersionDeleteParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + VersionDeleteParams params = VersionDeleteParams.builder() + .skillId("skill_123") + .version("version") + .build(); + DeletedSkillVersion deletedSkillVersion = client.skills().versions().delete(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + deleted_skill_version = openai.skills.versions.delete("version", + skill_id: "skill_123") + + + puts(deleted_skill_version) + /skills/{skill_id}/versions/{version}/content: + get: + tags: + - Skills + summary: Download a skill version zip bundle. + operationId: GetSkillVersionContent + parameters: + - name: skill_id + in: path + description: The identifier of the skill. + required: true + schema: + example: skill_123 + type: string + - name: version + in: path + description: The skill version number. + required: true + schema: + description: The skill version number. + type: string + responses: + '200': + description: The skill zip bundle. + content: + application/zip: + schema: + type: string + format: binary + application/json: + schema: + type: string + x-oaiMeta: + examples: + response: '' + request: + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const content = await + client.skills.versions.content.retrieve('version', { skill_id: + 'skill_123' }); + + + console.log(content); + + + const data = await content.blob(); + + console.log(data); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + content = client.skills.versions.content.retrieve( + version="version", + skill_id="skill_123", + ) + print(content) + data = content.read() + print(data) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tcontent, err := client.Skills.Versions.Content.Get(\n\t\tcontext.TODO(),\n\t\t\"skill_123\",\n\t\t\"version\",\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", content)\n}\n" + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.core.http.HttpResponse; + + import + com.openai.models.skills.versions.content.ContentRetrieveParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ContentRetrieveParams params = ContentRetrieveParams.builder() + .skillId("skill_123") + .version("version") + .build(); + HttpResponse content = client.skills().versions().content().retrieve(params); + } + } + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + content = openai.skills.versions.content.retrieve("version", + skill_id: "skill_123") + + + puts(content) + /chatkit/sessions/{session_id}/cancel: + post: + summary: |- + Cancel an active ChatKit session and return its most recent metadata. + + Cancelling prevents new requests from using the issued client secret. + operationId: CancelChatSessionMethod + parameters: + - name: session_id + in: path + description: Unique identifier for the ChatKit session to cancel. + required: true + schema: + example: cksess_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ChatSessionResource' + x-oaiMeta: + name: Cancel chat session + group: chatkit + beta: true + path: cancel-session new requests from using the issued client secret. + examples: + request: + curl: | + curl -X POST \ + https://api.openai.com/v1/chatkit/sessions/cksess_123/cancel \ + -H "OpenAI-Beta: chatkit_beta=v1" \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: > + import OpenAI from 'openai'; + + + const client = new OpenAI(); + + + const chatSession = await + client.beta.chatkit.sessions.cancel('cksess_123'); + + + console.log(chatSession.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + chat_session = client.beta.chatkit.sessions.cancel( + "cksess_123", + ) + print(chat_session.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatSession, err := client.Beta.ChatKit.Sessions.Cancel(context.TODO(), \"cksess_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatSession.ID)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + chat_session = openai.beta.chatkit.sessions.cancel("cksess_123") + + puts(chat_session) + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.beta.chatkit.sessions.SessionCancelParams; + + import com.openai.models.beta.chatkit.threads.ChatSession; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatSession chatSession = client.beta().chatkit().sessions().cancel("cksess_123"); + } + } + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const chatSession = await + client.beta.chatkit.sessions.cancel('cksess_123'); + + + console.log(chatSession.id); + response: | + { + "id": "cksess_123", + "object": "chatkit.session", + "workflow": { + "id": "workflow_alpha", + "version": "1" + }, + "scope": { + "customer_id": "cust_456" + }, + "max_requests_per_1_minute": 30, + "ttl_seconds": 900, + "status": "cancelled", + "cancelled_at": 1712345678 + } + /chatkit/sessions: + post: + summary: Create a ChatKit session. + operationId: CreateChatSessionMethod + parameters: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/CreateChatSessionBody' + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ChatSessionResource' + x-oaiMeta: + name: Create ChatKit session + group: chatkit + beta: true + path: sessions/create object. + examples: + request: + curl: | + curl https://api.openai.com/v1/chatkit/sessions \ + -H "Content-Type: application/json" \ + -H "Authorization: Bearer $OPENAI_API_KEY" \ + -H "OpenAI-Beta: chatkit_beta=v1" \ + -d '{ + "workflow": { + "id": "workflow_alpha", + "version": "2024-10-01" + }, + "scope": { + "project": "alpha", + "environment": "staging" + }, + "expires_after": 1800, + "max_requests_per_1_minute": 60, + "max_requests_per_session": 500 + }' + javascript: > + import OpenAI from 'openai'; + + + const client = new OpenAI(); + + + const chatSession = await client.beta.chatkit.sessions.create({ + user: 'user', workflow: { id: 'id' } }); + + + console.log(chatSession.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + chat_session = client.beta.chatkit.sessions.create( + user="x", + workflow={ + "id": "id" + }, + ) + print(chat_session.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatSession, err := client.Beta.ChatKit.Sessions.New(context.TODO(), openai.BetaChatKitSessionNewParams{\n\t\tUser: \"x\",\n\t\tWorkflow: openai.ChatSessionWorkflowParam{\n\t\t\tID: \"id\",\n\t\t},\n\t})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatSession.ID)\n}\n" + ruby: >- + require "openai" + + + openai = OpenAI::Client.new(api_key: "My API Key") + + + chat_session = openai.beta.chatkit.sessions.create(user: "x", + workflow: {id: "id"}) + + + puts(chat_session) + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import + com.openai.models.beta.chatkit.sessions.SessionCreateParams; + + import com.openai.models.beta.chatkit.threads.ChatSession; + + import + com.openai.models.beta.chatkit.threads.ChatSessionWorkflowParam; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + SessionCreateParams params = SessionCreateParams.builder() + .user("x") + .workflow(ChatSessionWorkflowParam.builder() + .id("id") + .build()) + .build(); + ChatSession chatSession = client.beta().chatkit().sessions().create(params); + } + } + node.js: |- + import OpenAI from 'openai'; + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + const chatSession = await client.beta.chatkit.sessions.create({ + user: 'x', + workflow: { id: 'id' }, + }); + + console.log(chatSession.id); + response: | + { + "client_secret": "chatkit_token_123", + "expires_at": 1735689600, + "workflow": { + "id": "workflow_alpha", + "version": "2024-10-01" + }, + "scope": { + "project": "alpha", + "environment": "staging" + }, + "max_requests_per_1_minute": 60, + "max_requests_per_session": 500, + "status": "active" + } + /chatkit/threads/{thread_id}/items: + get: + summary: List items that belong to a ChatKit thread. + operationId: ListThreadItemsMethod + parameters: + - name: thread_id + in: path + description: Identifier of the ChatKit thread whose items are requested. + required: true + schema: + example: cthr_123 + type: string + - name: limit + in: query + description: Maximum number of thread items to return. Defaults to 20. + required: false + schema: + type: integer + minimum: 0 + maximum: 100 + - name: order + in: query + description: Sort order for results by creation time. Defaults to `desc`. + required: false + schema: + $ref: '#/components/schemas/OrderEnum' + - name: after + in: query + description: >- + List items created after this thread item ID. Defaults to null for + the first page. + required: false + schema: + description: >- + List items created after this thread item ID. Defaults to null for + the first page. + type: string + - name: before + in: query + description: >- + List items created before this thread item ID. Defaults to null for + the newest results. + required: false + schema: + description: >- + List items created before this thread item ID. Defaults to null + for the newest results. + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ThreadItemListResource' + x-oaiMeta: + name: List ChatKit thread items + group: chatkit + beta: true + path: threads/list-items for the specified thread. + examples: + request: + curl: > + curl + "https://api.openai.com/v1/chatkit/threads/cthr_abc123/items?limit=3" + \ + -H "OpenAI-Beta: chatkit_beta=v1" \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: > + import OpenAI from 'openai'; + + + const client = new OpenAI(); + + + // Automatically fetches more pages as needed. + + for await (const thread of + client.beta.chatkit.threads.listItems('cthr_123')) { + console.log(thread); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.beta.chatkit.threads.list_items( + thread_id="cthr_123", + ) + page = page.data[0] + print(page) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Beta.ChatKit.Threads.ListItems(\n\t\tcontext.TODO(),\n\t\t\"cthr_123\",\n\t\topenai.BetaChatKitThreadListItemsParams{},\n\t)\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.beta.chatkit.threads.list_items("cthr_123") + + puts(page) + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.beta.chatkit.threads.ThreadListItemsPage; + + import + com.openai.models.beta.chatkit.threads.ThreadListItemsParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ThreadListItemsPage page = client.beta().chatkit().threads().listItems("cthr_123"); + } + } + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const thread of + client.beta.chatkit.threads.listItems('cthr_123')) { + console.log(thread); + } + response: | + { + "data": [ + { + "id": "cthi_user_001", + "object": "chatkit.thread_item", + "type": "user_message", + "content": [ + { + "type": "input_text", + "text": "I need help debugging an onboarding issue." + } + ], + "attachments": [] + }, + { + "id": "cthi_assistant_002", + "object": "chatkit.thread_item", + "type": "assistant_message", + "content": [ + { + "type": "output_text", + "text": "Let's start by confirming the workflow version you deployed." + } + ] + } + ], + "has_more": false, + "object": "list" + } + /chatkit/threads/{thread_id}: + get: + summary: Retrieve a ChatKit thread by its identifier. + operationId: GetThreadMethod + parameters: + - name: thread_id + in: path + description: Identifier of the ChatKit thread to retrieve. + required: true + schema: + example: cthr_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ThreadResource' + x-oaiMeta: + name: Retrieve ChatKit thread + group: chatkit + beta: true + path: threads/retrieve + examples: + request: + curl: | + curl https://api.openai.com/v1/chatkit/threads/cthr_abc123 \ + -H "OpenAI-Beta: chatkit_beta=v1" \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: > + import OpenAI from 'openai'; + + + const client = new OpenAI(); + + + const chatkitThread = await + client.beta.chatkit.threads.retrieve('cthr_123'); + + + console.log(chatkitThread.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + chatkit_thread = client.beta.chatkit.threads.retrieve( + "cthr_123", + ) + print(chatkit_thread.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tchatkitThread, err := client.Beta.ChatKit.Threads.Get(context.TODO(), \"cthr_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", chatkitThread.ID)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + chatkit_thread = openai.beta.chatkit.threads.retrieve("cthr_123") + + puts(chatkit_thread) + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.beta.chatkit.threads.ChatKitThread; + + import + com.openai.models.beta.chatkit.threads.ThreadRetrieveParams; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ChatKitThread chatkitThread = client.beta().chatkit().threads().retrieve("cthr_123"); + } + } + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const chatkitThread = await + client.beta.chatkit.threads.retrieve('cthr_123'); + + + console.log(chatkitThread.id); + response: | + { + "id": "cthr_abc123", + "object": "chatkit.thread", + "title": "Customer escalation", + "items": { + "data": [ + { + "id": "cthi_user_001", + "object": "chatkit.thread_item", + "type": "user_message", + "content": [ + { + "type": "input_text", + "text": "I need help debugging an onboarding issue." + } + ], + "attachments": [] + }, + { + "id": "cthi_assistant_002", + "object": "chatkit.thread_item", + "type": "assistant_message", + "content": [ + { + "type": "output_text", + "text": "Let's start by confirming the workflow version you deployed." + } + ] + } + ], + "has_more": false + } + } + delete: + summary: Delete a ChatKit thread along with its items and stored attachments. + operationId: DeleteThreadMethod + parameters: + - name: thread_id + in: path + description: Identifier of the ChatKit thread to delete. + required: true + schema: + example: cthr_123 + type: string + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/DeletedThreadResource' + x-oaiMeta: + beta: true + examples: + response: '' + request: + javascript: > + import OpenAI from 'openai'; + + + const client = new OpenAI(); + + + const thread = await + client.beta.chat_kit.threads.delete('cthr_123'); + + + console.log(thread.id); + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + thread = client.beta.chatkit.threads.delete( + "cthr_123", + ) + print(thread.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tthread, err := client.Beta.ChatKit.Threads.Delete(context.TODO(), \"cthr_123\")\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", thread.ID)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + thread = openai.beta.chatkit.threads.delete("cthr_123") + + puts(thread) + java: >- + package com.openai.example; + + + import com.openai.client.OpenAIClient; + + import com.openai.client.okhttp.OpenAIOkHttpClient; + + import com.openai.models.beta.chatkit.threads.ThreadDeleteParams; + + import + com.openai.models.beta.chatkit.threads.ThreadDeleteResponse; + + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ThreadDeleteResponse thread = client.beta().chatkit().threads().delete("cthr_123"); + } + } + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + const thread = await + client.beta.chatkit.threads.delete('cthr_123'); + + + console.log(thread.id); + name: Delete ChatKit thread + group: chatkit + path: threads/delete + /chatkit/threads: + get: + summary: List ChatKit threads with optional pagination and user filters. + operationId: ListThreadsMethod + parameters: + - name: limit + in: query + description: Maximum number of thread items to return. Defaults to 20. + required: false + schema: + type: integer + minimum: 0 + maximum: 100 + - name: order + in: query + description: Sort order for results by creation time. Defaults to `desc`. + required: false + schema: + $ref: '#/components/schemas/OrderEnum' + - name: after + in: query + description: >- + List items created after this thread item ID. Defaults to null for + the first page. + required: false + schema: + description: >- + List items created after this thread item ID. Defaults to null for + the first page. + type: string + - name: before + in: query + description: >- + List items created before this thread item ID. Defaults to null for + the newest results. + required: false + schema: + description: >- + List items created before this thread item ID. Defaults to null + for the newest results. + type: string + - name: user + in: query + description: >- + Filter threads that belong to this user identifier. Defaults to null + to return all users. + required: false + schema: + description: >- + Filter threads that belong to this user identifier. Defaults to + null to return all users. + type: string + minLength: 1 + maxLength: 512 + responses: + '200': + description: Success + content: + application/json: + schema: + $ref: '#/components/schemas/ThreadListResource' + x-oaiMeta: + name: List ChatKit threads + group: chatkit + beta: true + path: list-threads scope. + examples: + request: + curl: > + curl + "https://api.openai.com/v1/chatkit/threads?limit=2&order=desc" \ + -H "OpenAI-Beta: chatkit_beta=v1" \ + -H "Authorization: Bearer $OPENAI_API_KEY" + javascript: > + import OpenAI from 'openai'; + + + const client = new OpenAI(); + + + // Automatically fetches more pages as needed. + + for await (const chatkitThread of + client.beta.chatkit.threads.list()) { + console.log(chatkitThread.id); + } + python: |- + import os + from openai import OpenAI + + client = OpenAI( + api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted + ) + page = client.beta.chatkit.threads.list() + page = page.data[0] + print(page.id) + go: "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\n\t\"github.com/openai/openai-go\"\n\t\"github.com/openai/openai-go/option\"\n)\n\nfunc main() {\n\tclient := openai.NewClient(\n\t\toption.WithAPIKey(\"My API Key\"),\n\t)\n\tpage, err := client.Beta.ChatKit.Threads.List(context.TODO(), openai.BetaChatKitThreadListParams{})\n\tif err != nil {\n\t\tpanic(err.Error())\n\t}\n\tfmt.Printf(\"%+v\\n\", page)\n}\n" + ruby: |- + require "openai" + + openai = OpenAI::Client.new(api_key: "My API Key") + + page = openai.beta.chatkit.threads.list + + puts(page) + java: |- + package com.openai.example; + + import com.openai.client.OpenAIClient; + import com.openai.client.okhttp.OpenAIOkHttpClient; + import com.openai.models.beta.chatkit.threads.ThreadListPage; + import com.openai.models.beta.chatkit.threads.ThreadListParams; + + public final class Main { + private Main() {} + + public static void main(String[] args) { + OpenAIClient client = OpenAIOkHttpClient.fromEnv(); + + ThreadListPage page = client.beta().chatkit().threads().list(); + } + } + node.js: >- + import OpenAI from 'openai'; + + + const client = new OpenAI({ + apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted + }); + + + // Automatically fetches more pages as needed. + + for await (const chatkitThread of + client.beta.chatkit.threads.list()) { + console.log(chatkitThread.id); + } + response: | + { + "data": [ + { + "id": "cthr_abc123", + "object": "chatkit.thread", + "title": "Customer escalation" + }, + { + "id": "cthr_def456", + "object": "chatkit.thread", + "title": "Demo feedback" + } + ], + "has_more": false, + "object": "list" + } +components: + schemas: + AddUploadPartRequest: + type: object + additionalProperties: false + properties: + data: + description: | + The chunk of bytes for this Part. + type: string + format: binary + required: + - data + AdminApiKey: + type: object + description: Represents an individual Admin API key in an org. + properties: + object: + type: string + example: organization.admin_api_key + description: The object type, which is always `organization.admin_api_key` + x-stainless-const: true + id: + type: string + example: key_abc + description: The identifier, which can be referenced in API endpoints + name: + type: string + example: Administration Key + description: The name of the API key + redacted_value: + type: string + example: sk-admin...def + description: The redacted value of the API key + value: + type: string + example: sk-admin-1234abcd + description: The value of the API key. Only shown on create. + created_at: + type: integer + format: int64 + example: 1711471533 + description: The Unix timestamp (in seconds) of when the API key was created + last_used_at: + anyOf: + - type: integer + format: int64 + example: 1711471534 + description: >- + The Unix timestamp (in seconds) of when the API key was last + used + - type: 'null' + owner: + type: object + properties: + type: + type: string + example: user + description: Always `user` + object: + type: string + example: organization.user + description: The object type, which is always organization.user + id: + type: string + example: sa_456 + description: The identifier, which can be referenced in API endpoints + name: + type: string + example: My Service Account + description: The name of the user + created_at: + type: integer + format: int64 + example: 1711471533 + description: The Unix timestamp (in seconds) of when the user was created + role: + type: string + example: owner + description: Always `owner` + required: + - object + - redacted_value + - name + - created_at + - last_used_at + - id + - owner + x-oaiMeta: + name: The admin API key object + example: | + { + "object": "organization.admin_api_key", + "id": "key_abc", + "name": "Main Admin Key", + "redacted_value": "sk-admin...xyz", + "created_at": 1711471533, + "last_used_at": 1711471534, + "owner": { + "type": "user", + "object": "organization.user", + "id": "user_123", + "name": "John Doe", + "created_at": 1711471533, + "role": "owner" + } + } + ApiKeyList: + type: object + properties: + object: + type: string + example: list + data: + type: array + items: + $ref: '#/components/schemas/AdminApiKey' + has_more: + type: boolean + example: false + first_id: + type: string + example: key_abc + last_id: + type: string + example: key_xyz + AssignedRoleDetails: + type: object + description: >- + Detailed information about a role assignment entry returned when listing + assignments. + properties: + id: + type: string + description: Identifier for the role. + name: + type: string + description: Name of the role. + permissions: + type: array + description: Permissions associated with the role. + items: + type: string + resource_type: + type: string + description: Resource type the role applies to. + predefined_role: + type: boolean + description: Whether the role is predefined by OpenAI. + description: + description: Description of the role. + anyOf: + - type: string + - type: 'null' + created_at: + description: When the role was created. + anyOf: + - type: integer + format: int64 + - type: 'null' + updated_at: + description: When the role was last updated. + anyOf: + - type: integer + format: int64 + - type: 'null' + created_by: + description: Identifier of the actor who created the role. + anyOf: + - type: string + - type: 'null' + created_by_user_obj: + description: User details for the actor that created the role, when available. + anyOf: + - type: object + additionalProperties: true + - type: 'null' + metadata: + description: Arbitrary metadata stored on the role. + anyOf: + - type: object + additionalProperties: true + - type: 'null' + required: + - id + - name + - permissions + - resource_type + - predefined_role + - description + - created_at + - updated_at + - created_by + - created_by_user_obj + - metadata + AssistantObject: + type: object + title: Assistant + description: Represents an `assistant` that can call the model and use tools. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `assistant`. + type: string + enum: + - assistant + x-stainless-const: true + created_at: + description: The Unix timestamp (in seconds) for when the assistant was created. + type: integer + name: + anyOf: + - description: | + The name of the assistant. The maximum length is 256 characters. + type: string + maxLength: 256 + - type: 'null' + description: + anyOf: + - description: > + The description of the assistant. The maximum length is 512 + characters. + type: string + maxLength: 512 + - type: 'null' + model: + description: > + ID of the model to use. You can use the [List + models](/docs/api-reference/models/list) API to see all of your + available models, or see our [Model overview](/docs/models) for + descriptions of them. + type: string + instructions: + anyOf: + - description: > + The system instructions that the assistant uses. The maximum + length is 256,000 characters. + type: string + maxLength: 256000 + - type: 'null' + tools: + description: > + A list of tool enabled on the assistant. There can be a maximum of + 128 tools per assistant. Tools can be of types `code_interpreter`, + `file_search`, or `function`. + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: '#/components/schemas/AssistantToolsCode' + - $ref: '#/components/schemas/AssistantToolsFileSearch' + - $ref: '#/components/schemas/AssistantToolsFunction' + tool_resources: + anyOf: + - type: object + description: > + A set of resources that are used by the assistant's tools. The + resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the + `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: > + A list of [file](/docs/api-reference/files) IDs made + available to the `code_interpreter`` tool. There can be + a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: > + The ID of the [vector + store](/docs/api-reference/vector-stores/object) + attached to this assistant. There can be a maximum of 1 + vector store attached to the assistant. + maxItems: 1 + items: + type: string + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + temperature: + anyOf: + - description: > + What sampling temperature to use, between 0 and 2. Higher values + like 0.8 will make the output more random, while lower values + like 0.2 will make it more focused and deterministic. + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + - type: 'null' + top_p: + anyOf: + - type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + description: > + An alternative to sampling with temperature, called nucleus + sampling, where the model considers the results of the tokens + with top_p probability mass. So 0.1 means only the tokens + comprising the top 10% probability mass are considered. + + + We generally recommend altering this or temperature but not + both. + - type: 'null' + response_format: + anyOf: + - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' + - type: 'null' + required: + - id + - object + - created_at + - name + - description + - model + - instructions + - tools + - metadata + x-oaiMeta: + name: The assistant object + example: | + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1698984975, + "name": "Math Tutor", + "description": null, + "model": "gpt-4o", + "instructions": "You are a personal math tutor. When asked a question, write and run Python code to answer the question.", + "tools": [ + { + "type": "code_interpreter" + } + ], + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + } + deprecated: true + AssistantStreamEvent: + description: > + Represents an event emitted when streaming a Run. + + + Each event in a server-sent events stream has an `event` and `data` + property: + + + ``` + + event: thread.created + + data: {"id": "thread_123", "object": "thread", ...} + + ``` + + + We emit events whenever a new object is created, transitions to a new + state, or is being + + streamed in parts (deltas). For example, we emit `thread.run.created` + when a new run + + is created, `thread.run.completed` when a run completes, and so on. When + an Assistant chooses + + to create a message during a run, we emit a `thread.message.created + event`, a + + `thread.message.in_progress` event, many `thread.message.delta` events, + and finally a + + `thread.message.completed` event. + + + We may add additional events over time, so we recommend handling unknown + events gracefully + + in your code. See the [Assistants API + quickstart](/docs/assistants/overview) to learn how to + + integrate the Assistants API with streaming. + oneOf: + - $ref: '#/components/schemas/ThreadStreamEvent' + - $ref: '#/components/schemas/RunStreamEvent' + - $ref: '#/components/schemas/RunStepStreamEvent' + - $ref: '#/components/schemas/MessageStreamEvent' + - $ref: '#/components/schemas/ErrorEvent' + - $ref: '#/components/schemas/DoneEvent' + x-oaiMeta: + name: Assistant stream events + beta: true + AssistantSupportedModels: + type: string + enum: + - gpt-5 + - gpt-5-mini + - gpt-5-nano + - gpt-5-2025-08-07 + - gpt-5-mini-2025-08-07 + - gpt-5-nano-2025-08-07 + - gpt-4.1 + - gpt-4.1-mini + - gpt-4.1-nano + - gpt-4.1-2025-04-14 + - gpt-4.1-mini-2025-04-14 + - gpt-4.1-nano-2025-04-14 + - o3-mini + - o3-mini-2025-01-31 + - o1 + - o1-2024-12-17 + - gpt-4o + - gpt-4o-2024-11-20 + - gpt-4o-2024-08-06 + - gpt-4o-2024-05-13 + - gpt-4o-mini + - gpt-4o-mini-2024-07-18 + - gpt-4.5-preview + - gpt-4.5-preview-2025-02-27 + - gpt-4-turbo + - gpt-4-turbo-2024-04-09 + - gpt-4-0125-preview + - gpt-4-turbo-preview + - gpt-4-1106-preview + - gpt-4-vision-preview + - gpt-4 + - gpt-4-0314 + - gpt-4-0613 + - gpt-4-32k + - gpt-4-32k-0314 + - gpt-4-32k-0613 + - gpt-3.5-turbo + - gpt-3.5-turbo-16k + - gpt-3.5-turbo-0613 + - gpt-3.5-turbo-1106 + - gpt-3.5-turbo-0125 + - gpt-3.5-turbo-16k-0613 + AssistantToolsCode: + type: object + title: Code interpreter tool + properties: + type: + type: string + description: 'The type of tool being defined: `code_interpreter`' + enum: + - code_interpreter + x-stainless-const: true + required: + - type + AssistantToolsFileSearch: + type: object + title: FileSearch tool + properties: + type: + type: string + description: 'The type of tool being defined: `file_search`' + enum: + - file_search + x-stainless-const: true + file_search: + type: object + description: Overrides for the file search tool. + properties: + max_num_results: + type: integer + minimum: 1 + maximum: 50 + description: > + The maximum number of results the file search tool should + output. The default is 20 for `gpt-4*` models and 5 for + `gpt-3.5-turbo`. This number should be between 1 and 50 + inclusive. + + + Note that the file search tool may output fewer than + `max_num_results` results. See the [file search tool + documentation](/docs/assistants/tools/file-search#customizing-file-search-settings) + for more information. + ranking_options: + $ref: '#/components/schemas/FileSearchRankingOptions' + required: + - type + AssistantToolsFileSearchTypeOnly: + type: object + title: FileSearch tool + properties: + type: + type: string + description: 'The type of tool being defined: `file_search`' + enum: + - file_search + x-stainless-const: true + required: + - type + AssistantToolsFunction: + type: object + title: Function tool + properties: + type: + type: string + description: 'The type of tool being defined: `function`' + enum: + - function + x-stainless-const: true + function: + $ref: '#/components/schemas/FunctionObject' + required: + - type + - function + AssistantsApiResponseFormatOption: + description: > + Specifies the format that the model must output. Compatible with + [GPT-4o](/docs/models#gpt-4o), [GPT-4 + Turbo](/docs/models#gpt-4-turbo-and-gpt-4), and all GPT-3.5 Turbo models + since `gpt-3.5-turbo-1106`. + + + Setting to `{ "type": "json_schema", "json_schema": {...} }` enables + Structured Outputs which ensures the model will match your supplied JSON + schema. Learn more in the [Structured Outputs + guide](/docs/guides/structured-outputs). + + + Setting to `{ "type": "json_object" }` enables JSON mode, which ensures + the message the model generates is valid JSON. + + + **Important:** when using JSON mode, you **must** also instruct the + model to produce JSON yourself via a system or user message. Without + this, the model may generate an unending stream of whitespace until the + generation reaches the token limit, resulting in a long-running and + seemingly "stuck" request. Also note that the message content may be + partially cut off if `finish_reason="length"`, which indicates the + generation exceeded `max_tokens` or the conversation exceeded the max + context length. + oneOf: + - type: string + description: | + `auto` is the default value + enum: + - auto + x-stainless-const: true + - $ref: '#/components/schemas/ResponseFormatText' + - $ref: '#/components/schemas/ResponseFormatJsonObject' + - $ref: '#/components/schemas/ResponseFormatJsonSchema' + AssistantsApiToolChoiceOption: + description: > + Controls which (if any) tool is called by the model. + + `none` means the model will not call any tools and instead generates a + message. + + `auto` is the default value and means the model can pick between + generating a message or calling one or more tools. + + `required` means the model must call one or more tools before responding + to the user. + + Specifying a particular tool like `{"type": "file_search"}` or `{"type": + "function", "function": {"name": "my_function"}}` forces the model to + call that tool. + oneOf: + - type: string + description: > + `none` means the model will not call any tools and instead generates + a message. `auto` means the model can pick between generating a + message or calling one or more tools. `required` means the model + must call one or more tools before responding to the user. + enum: + - none + - auto + - required + - $ref: '#/components/schemas/AssistantsNamedToolChoice' + AssistantsNamedToolChoice: + type: object + description: >- + Specifies a tool the model should use. Use to force the model to call a + specific tool. + properties: + type: + type: string + enum: + - function + - code_interpreter + - file_search + description: >- + The type of the tool. If type is `function`, the function name must + be set + function: + type: object + properties: + name: + type: string + description: The name of the function to call. + required: + - name + required: + - type + AudioResponseFormat: + description: > + The format of the output, in one of these options: `json`, `text`, + `srt`, `verbose_json`, `vtt`, or `diarized_json`. For + `gpt-4o-transcribe` and `gpt-4o-mini-transcribe`, the only supported + format is `json`. For `gpt-4o-transcribe-diarize`, the supported formats + are `json`, `text`, and `diarized_json`, with `diarized_json` required + to receive speaker annotations. + type: string + enum: + - json + - text + - srt + - verbose_json + - vtt + - diarized_json + default: json + AudioTranscription: + type: object + properties: + model: + description: > + The model to use for transcription. Current options are `whisper-1`, + `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, + `gpt-4o-transcribe`, and `gpt-4o-transcribe-diarize`. Use + `gpt-4o-transcribe-diarize` when you need diarization with speaker + labels. + anyOf: + - type: string + - type: string + enum: + - whisper-1 + - gpt-4o-mini-transcribe + - gpt-4o-mini-transcribe-2025-12-15 + - gpt-4o-transcribe + - gpt-4o-transcribe-diarize + language: + type: string + description: > + The language of the input audio. Supplying the input language in + + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + (e.g. `en`) format + + will improve accuracy and latency. + prompt: + type: string + description: > + An optional text to guide the model's style or continue a previous + audio + + segment. + + For `whisper-1`, the [prompt is a list of + keywords](/docs/guides/speech-to-text#prompting). + + For `gpt-4o-transcribe` models (excluding + `gpt-4o-transcribe-diarize`), the prompt is a free text string, for + example "expect words related to technology". + AuditLog: + type: object + description: A log of a user action or configuration change within this organization. + properties: + id: + type: string + description: The ID of this log. + type: + $ref: '#/components/schemas/AuditLogEventType' + effective_at: + type: integer + description: The Unix timestamp (in seconds) of the event. + project: + type: object + description: >- + The project that the action was scoped to. Absent for actions not + scoped to projects. Note that any admin actions taken via Admin API + keys are associated with the default project. + properties: + id: + type: string + description: The project ID. + name: + type: string + description: The project title. + actor: + $ref: '#/components/schemas/AuditLogActor' + api_key.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The tracking ID of the API key. + data: + type: object + description: The payload used to create the API key. + properties: + scopes: + type: array + items: + type: string + description: >- + A list of scopes allowed for the API key, e.g. + `["api.model.request"]` + api_key.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The tracking ID of the API key. + changes_requested: + type: object + description: The payload used to update the API key. + properties: + scopes: + type: array + items: + type: string + description: >- + A list of scopes allowed for the API key, e.g. + `["api.model.request"]` + api_key.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The tracking ID of the API key. + checkpoint.permission.created: + type: object + description: >- + The project and fine-tuned model checkpoint that the checkpoint + permission was created for. + properties: + id: + type: string + description: The ID of the checkpoint permission. + data: + type: object + description: The payload used to create the checkpoint permission. + properties: + project_id: + type: string + description: >- + The ID of the project that the checkpoint permission was + created for. + fine_tuned_model_checkpoint: + type: string + description: The ID of the fine-tuned model checkpoint. + checkpoint.permission.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the checkpoint permission. + external_key.registered: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the external key configuration. + data: + type: object + description: The configuration for the external key. + external_key.removed: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the external key configuration. + group.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the group. + data: + type: object + description: Information about the created group. + properties: + group_name: + type: string + description: The group name. + group.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the group. + changes_requested: + type: object + description: The payload used to update the group. + properties: + group_name: + type: string + description: The updated group name. + group.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the group. + scim.enabled: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the SCIM was enabled for. + scim.disabled: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the SCIM was disabled for. + invite.sent: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the invite. + data: + type: object + description: The payload used to create the invite. + properties: + email: + type: string + description: The email invited to the organization. + role: + type: string + description: >- + The role the email was invited to be. Is either `owner` or + `member`. + invite.accepted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the invite. + invite.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the invite. + ip_allowlist.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the IP allowlist configuration. + name: + type: string + description: The name of the IP allowlist configuration. + allowed_ips: + type: array + description: The IP addresses or CIDR ranges included in the configuration. + items: + type: string + ip_allowlist.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the IP allowlist configuration. + allowed_ips: + type: array + description: >- + The updated set of IP addresses or CIDR ranges in the + configuration. + items: + type: string + ip_allowlist.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The ID of the IP allowlist configuration. + name: + type: string + description: The name of the IP allowlist configuration. + allowed_ips: + type: array + description: The IP addresses or CIDR ranges that were in the configuration. + items: + type: string + ip_allowlist.config.activated: + type: object + description: The details for events with this `type`. + properties: + configs: + type: array + description: The configurations that were activated. + items: + type: object + properties: + id: + type: string + description: The ID of the IP allowlist configuration. + name: + type: string + description: The name of the IP allowlist configuration. + ip_allowlist.config.deactivated: + type: object + description: The details for events with this `type`. + properties: + configs: + type: array + description: The configurations that were deactivated. + items: + type: object + properties: + id: + type: string + description: The ID of the IP allowlist configuration. + name: + type: string + description: The name of the IP allowlist configuration. + login.succeeded: + type: object + description: >- + This event has no additional fields beyond the standard audit log + attributes. + login.failed: + type: object + description: The details for events with this `type`. + properties: + error_code: + type: string + description: The error code of the failure. + error_message: + type: string + description: The error message of the failure. + logout.succeeded: + type: object + description: >- + This event has no additional fields beyond the standard audit log + attributes. + logout.failed: + type: object + description: The details for events with this `type`. + properties: + error_code: + type: string + description: The error code of the failure. + error_message: + type: string + description: The error message of the failure. + organization.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The organization ID. + changes_requested: + type: object + description: The payload used to update the organization settings. + properties: + title: + type: string + description: The organization title. + description: + type: string + description: The organization description. + name: + type: string + description: The organization name. + threads_ui_visibility: + type: string + description: >- + Visibility of the threads page which shows messages created + with the Assistants API and Playground. One of `ANY_ROLE`, + `OWNERS`, or `NONE`. + usage_dashboard_visibility: + type: string + description: >- + Visibility of the usage dashboard which shows activity and + costs for your organization. One of `ANY_ROLE` or `OWNERS`. + api_call_logging: + type: string + description: >- + How your organization logs data from supported API calls. + One of `disabled`, `enabled_per_call`, + `enabled_for_all_projects`, or + `enabled_for_selected_projects` + api_call_logging_project_ids: + type: string + description: >- + The list of project ids if api_call_logging is set to + `enabled_for_selected_projects` + project.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + data: + type: object + description: The payload used to create the project. + properties: + name: + type: string + description: The project name. + title: + type: string + description: The title of the project as seen on the dashboard. + project.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + changes_requested: + type: object + description: The payload used to update the project. + properties: + title: + type: string + description: The title of the project as seen on the dashboard. + project.archived: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + project.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + rate_limit.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The rate limit ID + changes_requested: + type: object + description: The payload used to update the rate limits. + properties: + max_requests_per_1_minute: + type: integer + description: The maximum requests per minute. + max_tokens_per_1_minute: + type: integer + description: The maximum tokens per minute. + max_images_per_1_minute: + type: integer + description: >- + The maximum images per minute. Only relevant for certain + models. + max_audio_megabytes_per_1_minute: + type: integer + description: >- + The maximum audio megabytes per minute. Only relevant for + certain models. + max_requests_per_1_day: + type: integer + description: >- + The maximum requests per day. Only relevant for certain + models. + batch_1_day_max_input_tokens: + type: integer + description: >- + The maximum batch input tokens per day. Only relevant for + certain models. + rate_limit.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The rate limit ID + role.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The role ID. + role_name: + type: string + description: The name of the role. + permissions: + type: array + items: + type: string + description: The permissions granted by the role. + resource_type: + type: string + description: The type of resource the role belongs to. + resource_id: + type: string + description: The resource the role is scoped to. + role.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The role ID. + changes_requested: + type: object + description: The payload used to update the role. + properties: + role_name: + type: string + description: The updated role name, when provided. + resource_id: + type: string + description: The resource the role is scoped to. + resource_type: + type: string + description: The type of resource the role belongs to. + permissions_added: + type: array + items: + type: string + description: The permissions added to the role. + permissions_removed: + type: array + items: + type: string + description: The permissions removed from the role. + description: + type: string + description: The updated role description, when provided. + metadata: + type: object + description: Additional metadata stored on the role. + role.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The role ID. + role.assignment.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The identifier of the role assignment. + principal_id: + type: string + description: The principal (user or group) that received the role. + principal_type: + type: string + description: The type of principal (user or group) that received the role. + resource_id: + type: string + description: The resource the role assignment is scoped to. + resource_type: + type: string + description: The type of resource the role assignment is scoped to. + role.assignment.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The identifier of the role assignment. + principal_id: + type: string + description: The principal (user or group) that had the role removed. + principal_type: + type: string + description: The type of principal (user or group) that had the role removed. + resource_id: + type: string + description: The resource the role assignment was scoped to. + resource_type: + type: string + description: The type of resource the role assignment was scoped to. + service_account.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The service account ID. + data: + type: object + description: The payload used to create the service account. + properties: + role: + type: string + description: >- + The role of the service account. Is either `owner` or + `member`. + service_account.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The service account ID. + changes_requested: + type: object + description: The payload used to updated the service account. + properties: + role: + type: string + description: >- + The role of the service account. Is either `owner` or + `member`. + service_account.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The service account ID. + user.added: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The user ID. + data: + type: object + description: The payload used to add the user to the project. + properties: + role: + type: string + description: The role of the user. Is either `owner` or `member`. + user.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The project ID. + changes_requested: + type: object + description: The payload used to update the user. + properties: + role: + type: string + description: The role of the user. Is either `owner` or `member`. + user.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The user ID. + certificate.created: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The certificate ID. + name: + type: string + description: The name of the certificate. + certificate.updated: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The certificate ID. + name: + type: string + description: The name of the certificate. + certificate.deleted: + type: object + description: The details for events with this `type`. + properties: + id: + type: string + description: The certificate ID. + name: + type: string + description: The name of the certificate. + certificate: + type: string + description: The certificate content in PEM format. + certificates.activated: + type: object + description: The details for events with this `type`. + properties: + certificates: + type: array + items: + type: object + properties: + id: + type: string + description: The certificate ID. + name: + type: string + description: The name of the certificate. + certificates.deactivated: + type: object + description: The details for events with this `type`. + properties: + certificates: + type: array + items: + type: object + properties: + id: + type: string + description: The certificate ID. + name: + type: string + description: The name of the certificate. + required: + - id + - type + - effective_at + - actor + x-oaiMeta: + name: The audit log object + example: | + { + "id": "req_xxx_20240101", + "type": "api_key.created", + "effective_at": 1720804090, + "actor": { + "type": "session", + "session": { + "user": { + "id": "user-xxx", + "email": "user@example.com" + }, + "ip_address": "127.0.0.1", + "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" + } + }, + "api_key.created": { + "id": "key_xxxx", + "data": { + "scopes": ["resource.operation"] + } + } + } + AuditLogActor: + type: object + description: The actor who performed the audit logged action. + properties: + type: + type: string + description: The type of actor. Is either `session` or `api_key`. + enum: + - session + - api_key + session: + $ref: '#/components/schemas/AuditLogActorSession' + api_key: + $ref: '#/components/schemas/AuditLogActorApiKey' + AuditLogActorApiKey: + type: object + description: The API Key used to perform the audit logged action. + properties: + id: + type: string + description: The tracking id of the API key. + type: + type: string + description: The type of API key. Can be either `user` or `service_account`. + enum: + - user + - service_account + user: + $ref: '#/components/schemas/AuditLogActorUser' + service_account: + $ref: '#/components/schemas/AuditLogActorServiceAccount' + AuditLogActorServiceAccount: + type: object + description: The service account that performed the audit logged action. + properties: + id: + type: string + description: The service account id. + AuditLogActorSession: + type: object + description: The session in which the audit logged action was performed. + properties: + user: + $ref: '#/components/schemas/AuditLogActorUser' + ip_address: + type: string + description: The IP address from which the action was performed. + AuditLogActorUser: + type: object + description: The user who performed the audit logged action. + properties: + id: + type: string + description: The user id. + email: + type: string + description: The user email. + AuditLogEventType: + type: string + description: The event type. + enum: + - api_key.created + - api_key.updated + - api_key.deleted + - certificate.created + - certificate.updated + - certificate.deleted + - certificates.activated + - certificates.deactivated + - checkpoint.permission.created + - checkpoint.permission.deleted + - external_key.registered + - external_key.removed + - group.created + - group.updated + - group.deleted + - invite.sent + - invite.accepted + - invite.deleted + - ip_allowlist.created + - ip_allowlist.updated + - ip_allowlist.deleted + - ip_allowlist.config.activated + - ip_allowlist.config.deactivated + - login.succeeded + - login.failed + - logout.succeeded + - logout.failed + - organization.updated + - project.created + - project.updated + - project.archived + - project.deleted + - rate_limit.updated + - rate_limit.deleted + - resource.deleted + - tunnel.created + - tunnel.updated + - tunnel.deleted + - role.created + - role.updated + - role.deleted + - role.assignment.created + - role.assignment.deleted + - scim.enabled + - scim.disabled + - service_account.created + - service_account.updated + - service_account.deleted + - user.added + - user.updated + - user.deleted + AutoChunkingStrategyRequestParam: + type: object + title: Auto Chunking Strategy + description: >- + The default strategy. This strategy currently uses a + `max_chunk_size_tokens` of `800` and `chunk_overlap_tokens` of `400`. + additionalProperties: false + properties: + type: + type: string + description: Always `auto`. + enum: + - auto + x-stainless-const: true + required: + - type + Batch: + type: object + properties: + id: + type: string + object: + type: string + enum: + - batch + description: The object type, which is always `batch`. + x-stainless-const: true + endpoint: + type: string + description: The OpenAI API endpoint used by the batch. + model: + type: string + description: > + Model ID used to process the batch, like `gpt-5-2025-08-07`. OpenAI + + offers a wide range of models with different capabilities, + performance + + characteristics, and price points. Refer to the [model + + guide](/docs/models) to browse and compare available models. + errors: + type: object + properties: + object: + type: string + description: The object type, which is always `list`. + data: + type: array + items: + type: object + properties: + code: + type: string + description: An error code identifying the error type. + message: + type: string + description: >- + A human-readable message providing more details about the + error. + param: + anyOf: + - type: string + description: >- + The name of the parameter that caused the error, if + applicable. + - type: 'null' + line: + anyOf: + - type: integer + description: >- + The line number of the input file where the error + occurred, if applicable. + - type: 'null' + input_file_id: + type: string + description: The ID of the input file for the batch. + completion_window: + type: string + description: The time frame within which the batch should be processed. + status: + type: string + description: The current status of the batch. + enum: + - validating + - failed + - in_progress + - finalizing + - completed + - expired + - cancelling + - cancelled + output_file_id: + type: string + description: >- + The ID of the file containing the outputs of successfully executed + requests. + error_file_id: + type: string + description: The ID of the file containing the outputs of requests with errors. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was created. + in_progress_at: + type: integer + description: >- + The Unix timestamp (in seconds) for when the batch started + processing. + expires_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch will expire. + finalizing_at: + type: integer + description: >- + The Unix timestamp (in seconds) for when the batch started + finalizing. + completed_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was completed. + failed_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch failed. + expired_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch expired. + cancelling_at: + type: integer + description: >- + The Unix timestamp (in seconds) for when the batch started + cancelling. + cancelled_at: + type: integer + description: The Unix timestamp (in seconds) for when the batch was cancelled. + request_counts: + type: object + properties: + total: + type: integer + description: Total number of requests in the batch. + completed: + type: integer + description: Number of requests that have been completed successfully. + failed: + type: integer + description: Number of requests that have failed. + required: + - total + - completed + - failed + description: The request counts for different statuses within the batch. + usage: + type: object + description: > + Represents token usage details including input tokens, output + tokens, a + + breakdown of output tokens, and the total tokens used. Only + populated on + + batches created after September 7, 2025. + properties: + input_tokens: + type: integer + description: The number of input tokens. + input_tokens_details: + type: object + description: A detailed breakdown of the input tokens. + properties: + cached_tokens: + type: integer + description: > + The number of tokens that were retrieved from the cache. + [More on + + prompt caching](/docs/guides/prompt-caching). + required: + - cached_tokens + output_tokens: + type: integer + description: The number of output tokens. + output_tokens_details: + type: object + description: A detailed breakdown of the output tokens. + properties: + reasoning_tokens: + type: integer + description: The number of reasoning tokens. + required: + - reasoning_tokens + total_tokens: + type: integer + description: The total number of tokens used. + required: + - input_tokens + - input_tokens_details + - output_tokens + - output_tokens_details + - total_tokens + metadata: + $ref: '#/components/schemas/Metadata' + required: + - id + - object + - endpoint + - input_file_id + - completion_window + - status + - created_at + x-oaiMeta: + name: The batch object + example: | + { + "id": "batch_abc123", + "object": "batch", + "endpoint": "/v1/completions", + "model": "gpt-5-2025-08-07", + "errors": null, + "input_file_id": "file-abc123", + "completion_window": "24h", + "status": "completed", + "output_file_id": "file-cvaTdG", + "error_file_id": "file-HOWS94", + "created_at": 1711471533, + "in_progress_at": 1711471538, + "expires_at": 1711557933, + "finalizing_at": 1711493133, + "completed_at": 1711493163, + "failed_at": null, + "expired_at": null, + "cancelling_at": null, + "cancelled_at": null, + "request_counts": { + "total": 100, + "completed": 95, + "failed": 5 + }, + "usage": { + "input_tokens": 1500, + "input_tokens_details": { + "cached_tokens": 1024 + }, + "output_tokens": 500, + "output_tokens_details": { + "reasoning_tokens": 300 + }, + "total_tokens": 2000 + }, + "metadata": { + "customer_id": "user_123456789", + "batch_description": "Nightly eval job", + } + } + BatchFileExpirationAfter: + type: object + title: File expiration policy + description: >- + The expiration policy for the output and/or error file that are + generated for a batch. + properties: + anchor: + description: >- + Anchor timestamp after which the expiration policy applies. + Supported anchors: `created_at`. Note that the anchor is the file + creation time, not the time the batch is created. + type: string + enum: + - created_at + x-stainless-const: true + seconds: + description: >- + The number of seconds after the anchor time that the file will + expire. Must be between 3600 (1 hour) and 2592000 (30 days). + type: integer + minimum: 3600 + maximum: 2592000 + required: + - anchor + - seconds + Certificate: + type: object + description: Represents an individual `certificate` uploaded to the organization. + properties: + object: + type: string + enum: + - certificate + - organization.certificate + - organization.project.certificate + description: > + The object type. + + + - If creating, updating, or getting a specific certificate, the + object type is `certificate`. + + - If listing, activating, or deactivating certificates for the + organization, the object type is `organization.certificate`. + + - If listing, activating, or deactivating certificates for a + project, the object type is `organization.project.certificate`. + x-stainless-const: true + id: + type: string + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the certificate. + created_at: + type: integer + description: >- + The Unix timestamp (in seconds) of when the certificate was + uploaded. + certificate_details: + type: object + properties: + valid_at: + type: integer + description: >- + The Unix timestamp (in seconds) of when the certificate becomes + valid. + expires_at: + type: integer + description: The Unix timestamp (in seconds) of when the certificate expires. + content: + type: string + description: The content of the certificate in PEM format. + active: + type: boolean + description: >- + Whether the certificate is currently active at the specified scope. + Not returned when getting details for a specific certificate. + required: + - object + - id + - name + - created_at + - certificate_details + x-oaiMeta: + name: The certificate object + example: | + { + "object": "certificate", + "id": "cert_abc", + "name": "My Certificate", + "created_at": 1234567, + "certificate_details": { + "valid_at": 1234567, + "expires_at": 12345678, + "content": "-----BEGIN CERTIFICATE----- MIIGAjCCA...6znFlOW+ -----END CERTIFICATE-----" + } + } + ChatCompletionAllowedTools: + type: object + title: Allowed tools + description: | + Constrains the tools available to the model to a pre-defined set. + properties: + mode: + type: string + enum: + - auto + - required + description: > + Constrains the tools available to the model to a pre-defined set. + + + `auto` allows the model to pick from among the allowed tools and + generate a + + message. + + + `required` requires the model to call one or more of the allowed + tools. + tools: + type: array + description: > + A list of tool definitions that the model should be allowed to call. + + + For the Chat Completions API, the list of tool definitions might + look like: + + ```json + + [ + { "type": "function", "function": { "name": "get_weather" } }, + { "type": "function", "function": { "name": "get_time" } } + ] + + ``` + items: + type: object + x-oaiExpandable: false + description: | + A tool definition that the model should be allowed to call. + additionalProperties: true + required: + - mode + - tools + ChatCompletionAllowedToolsChoice: + type: object + title: Allowed tools + description: | + Constrains the tools available to the model to a pre-defined set. + properties: + type: + type: string + enum: + - allowed_tools + description: Allowed tool configuration type. Always `allowed_tools`. + x-stainless-const: true + allowed_tools: + $ref: '#/components/schemas/ChatCompletionAllowedTools' + required: + - type + - allowed_tools + ChatCompletionDeleted: + type: object + properties: + object: + type: string + description: The type of object being deleted. + enum: + - chat.completion.deleted + x-stainless-const: true + id: + type: string + description: The ID of the chat completion that was deleted. + deleted: + type: boolean + description: Whether the chat completion was deleted. + required: + - object + - id + - deleted + ChatCompletionFunctionCallOption: + type: object + description: > + Specifying a particular function via `{"name": "my_function"}` forces + the model to call that function. + properties: + name: + type: string + description: The name of the function to call. + required: + - name + ChatCompletionFunctions: + type: object + deprecated: true + properties: + description: + type: string + description: >- + A description of what the function does, used by the model to choose + when and how to call the function. + name: + type: string + description: >- + The name of the function to be called. Must be a-z, A-Z, 0-9, or + contain underscores and dashes, with a maximum length of 64. + parameters: + $ref: '#/components/schemas/FunctionParameters' + required: + - name + ChatCompletionList: + type: object + title: ChatCompletionList + description: | + An object representing a list of Chat Completions. + properties: + object: + type: string + enum: + - list + default: list + description: | + The type of this object. It is always set to "list". + x-stainless-const: true + data: + type: array + description: | + An array of chat completion objects. + items: + $ref: '#/components/schemas/CreateChatCompletionResponse' + first_id: + type: string + description: The identifier of the first chat completion in the data array. + last_id: + type: string + description: The identifier of the last chat completion in the data array. + has_more: + type: boolean + description: Indicates whether there are more Chat Completions available. + required: + - object + - data + - first_id + - last_id + - has_more + x-oaiMeta: + name: The chat completion list object + group: chat + example: | + { + "object": "list", + "data": [ + { + "object": "chat.completion", + "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", + "model": "gpt-4o-2024-08-06", + "created": 1738960610, + "request_id": "req_ded8ab984ec4bf840f37566c1011c417", + "tool_choice": null, + "usage": { + "total_tokens": 31, + "completion_tokens": 18, + "prompt_tokens": 13 + }, + "seed": 4944116822809979520, + "top_p": 1.0, + "temperature": 1.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0, + "system_fingerprint": "fp_50cad350e4", + "input_user": null, + "service_tier": "default", + "tools": null, + "metadata": {}, + "choices": [ + { + "index": 0, + "message": { + "content": "Mind of circuits hum, \nLearning patterns in silence— \nFuture's quiet spark.", + "role": "assistant", + "tool_calls": null, + "function_call": null + }, + "finish_reason": "stop", + "logprobs": null + } + ], + "response_format": null + } + ], + "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", + "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2", + "has_more": false + } + ChatCompletionMessageCustomToolCall: + type: object + title: Custom tool call + description: | + A call to a custom tool created by the model. + properties: + id: + type: string + description: The ID of the tool call. + type: + type: string + enum: + - custom + description: The type of the tool. Always `custom`. + x-stainless-const: true + custom: + type: object + description: The custom tool that the model called. + properties: + name: + type: string + description: The name of the custom tool to call. + input: + type: string + description: The input for the custom tool call generated by the model. + required: + - name + - input + required: + - id + - type + - custom + ChatCompletionMessageList: + type: object + title: ChatCompletionMessageList + description: | + An object representing a list of chat completion messages. + properties: + object: + type: string + enum: + - list + default: list + description: | + The type of this object. It is always set to "list". + x-stainless-const: true + data: + type: array + description: | + An array of chat completion message objects. + items: + allOf: + - $ref: '#/components/schemas/ChatCompletionResponseMessage' + - type: object + required: + - id + properties: + id: + type: string + description: The identifier of the chat message. + content_parts: + anyOf: + - type: array + description: > + If a content parts array was provided, this is an + array of `text` and `image_url` parts. + + Otherwise, null. + items: + oneOf: + - $ref: >- + #/components/schemas/ChatCompletionRequestMessageContentPartText + - $ref: >- + #/components/schemas/ChatCompletionRequestMessageContentPartImage + - type: 'null' + first_id: + type: string + description: The identifier of the first chat message in the data array. + last_id: + type: string + description: The identifier of the last chat message in the data array. + has_more: + type: boolean + description: Indicates whether there are more chat messages available. + required: + - object + - data + - first_id + - last_id + - has_more + x-oaiMeta: + name: The chat completion message list object + group: chat + example: | + { + "object": "list", + "data": [ + { + "id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", + "role": "user", + "content": "write a haiku about ai", + "name": null, + "content_parts": null + } + ], + "first_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", + "last_id": "chatcmpl-AyPNinnUqUDYo9SAdA52NobMflmj2-0", + "has_more": false + } + ChatCompletionMessageToolCall: + type: object + title: Function tool call + description: | + A call to a function tool created by the model. + properties: + id: + type: string + description: The ID of the tool call. + type: + type: string + enum: + - function + description: The type of the tool. Currently, only `function` is supported. + x-stainless-const: true + function: + type: object + description: The function that the model called. + properties: + name: + type: string + description: The name of the function to call. + arguments: + type: string + description: >- + The arguments to call the function with, as generated by the + model in JSON format. Note that the model does not always + generate valid JSON, and may hallucinate parameters not defined + by your function schema. Validate the arguments in your code + before calling your function. + required: + - name + - arguments + required: + - id + - type + - function + ChatCompletionMessageToolCallChunk: + type: object + properties: + index: + type: integer + id: + type: string + description: The ID of the tool call. + type: + type: string + enum: + - function + description: The type of the tool. Currently, only `function` is supported. + x-stainless-const: true + function: + type: object + properties: + name: + type: string + description: The name of the function to call. + arguments: + type: string + description: >- + The arguments to call the function with, as generated by the + model in JSON format. Note that the model does not always + generate valid JSON, and may hallucinate parameters not defined + by your function schema. Validate the arguments in your code + before calling your function. + required: + - index + ChatCompletionMessageToolCalls: + type: array + description: The tool calls generated by the model, such as function calls. + items: + oneOf: + - $ref: '#/components/schemas/ChatCompletionMessageToolCall' + - $ref: '#/components/schemas/ChatCompletionMessageCustomToolCall' + discriminator: + propertyName: type + ChatCompletionModalities: + anyOf: + - type: array + description: > + Output types that you would like the model to generate for this + request. + + Most models are capable of generating text, which is the default: + + + `["text"]` + + + The `gpt-4o-audio-preview` model can also be used to [generate + audio](/docs/guides/audio). To + + request that this model generate both text and audio responses, you + can + + use: + + + `["text", "audio"]` + items: + type: string + enum: + - text + - audio + - type: 'null' + ChatCompletionNamedToolChoice: + type: object + title: Function tool choice + description: >- + Specifies a tool the model should use. Use to force the model to call a + specific function. + properties: + type: + type: string + enum: + - function + description: For function calling, the type is always `function`. + x-stainless-const: true + function: + type: object + properties: + name: + type: string + description: The name of the function to call. + required: + - name + required: + - type + - function + ChatCompletionNamedToolChoiceCustom: + type: object + title: Custom tool choice + description: >- + Specifies a tool the model should use. Use to force the model to call a + specific custom tool. + properties: + type: + type: string + enum: + - custom + description: For custom tool calling, the type is always `custom`. + x-stainless-const: true + custom: + type: object + properties: + name: + type: string + description: The name of the custom tool to call. + required: + - name + required: + - type + - custom + ChatCompletionRequestAssistantMessage: + type: object + title: Assistant message + description: | + Messages sent by the model in response to user messages. + properties: + content: + anyOf: + - oneOf: + - type: string + description: The contents of the assistant message. + title: Text content + - type: array + description: >- + An array of content parts with a defined type. Can be one or + more of type `text`, or exactly one of type `refusal`. + title: Array of content parts + items: + $ref: >- + #/components/schemas/ChatCompletionRequestAssistantMessageContentPart + minItems: 1 + description: > + The contents of the assistant message. Required unless + `tool_calls` or `function_call` is specified. + - type: 'null' + refusal: + anyOf: + - type: string + description: The refusal message by the assistant. + - type: 'null' + role: + type: string + enum: + - assistant + description: The role of the messages author, in this case `assistant`. + x-stainless-const: true + name: + type: string + description: >- + An optional name for the participant. Provides the model information + to differentiate between participants of the same role. + audio: + anyOf: + - type: object + description: | + Data about a previous audio response from the model. + [Learn more](/docs/guides/audio). + required: + - id + properties: + id: + type: string + description: > + Unique identifier for a previous audio response from the + model. + - type: 'null' + tool_calls: + $ref: '#/components/schemas/ChatCompletionMessageToolCalls' + function_call: + anyOf: + - type: object + deprecated: true + description: >- + Deprecated and replaced by `tool_calls`. The name and arguments + of a function that should be called, as generated by the model. + properties: + arguments: + type: string + description: >- + The arguments to call the function with, as generated by the + model in JSON format. Note that the model does not always + generate valid JSON, and may hallucinate parameters not + defined by your function schema. Validate the arguments in + your code before calling your function. + name: + type: string + description: The name of the function to call. + required: + - arguments + - name + - type: 'null' + required: + - role + ChatCompletionRequestAssistantMessageContentPart: + oneOf: + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartRefusal' + discriminator: + propertyName: type + ChatCompletionRequestDeveloperMessage: + type: object + title: Developer message + description: > + Developer-provided instructions that the model should follow, regardless + of + + messages sent by the user. With o1 models and newer, `developer` + messages + + replace the previous `system` messages. + properties: + content: + description: The contents of the developer message. + oneOf: + - type: string + description: The contents of the developer message. + title: Text content + - type: array + description: >- + An array of content parts with a defined type. For developer + messages, only type `text` is supported. + title: Array of content parts + items: + $ref: >- + #/components/schemas/ChatCompletionRequestMessageContentPartText + minItems: 1 + role: + type: string + enum: + - developer + description: The role of the messages author, in this case `developer`. + x-stainless-const: true + name: + type: string + description: >- + An optional name for the participant. Provides the model information + to differentiate between participants of the same role. + required: + - content + - role + ChatCompletionRequestFunctionMessage: + type: object + title: Function message + deprecated: true + properties: + role: + type: string + enum: + - function + description: The role of the messages author, in this case `function`. + x-stainless-const: true + content: + anyOf: + - type: string + description: The contents of the function message. + - type: 'null' + name: + type: string + description: The name of the function to call. + required: + - role + - content + - name + ChatCompletionRequestMessage: + oneOf: + - $ref: '#/components/schemas/ChatCompletionRequestDeveloperMessage' + - $ref: '#/components/schemas/ChatCompletionRequestSystemMessage' + - $ref: '#/components/schemas/ChatCompletionRequestUserMessage' + - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' + - $ref: '#/components/schemas/ChatCompletionRequestToolMessage' + - $ref: '#/components/schemas/ChatCompletionRequestFunctionMessage' + discriminator: + propertyName: role + ChatCompletionRequestMessageContentPartAudio: + type: object + title: Audio content part + description: | + Learn about [audio inputs](/docs/guides/audio). + properties: + type: + type: string + enum: + - input_audio + description: The type of the content part. Always `input_audio`. + x-stainless-const: true + input_audio: + type: object + properties: + data: + type: string + description: Base64 encoded audio data. + format: + type: string + enum: + - wav + - mp3 + description: > + The format of the encoded audio data. Currently supports "wav" + and "mp3". + required: + - data + - format + required: + - type + - input_audio + ChatCompletionRequestMessageContentPartFile: + type: object + title: File content part + description: | + Learn about [file inputs](/docs/guides/text) for text generation. + properties: + type: + type: string + enum: + - file + description: The type of the content part. Always `file`. + x-stainless-const: true + file: + type: object + properties: + filename: + type: string + description: > + The name of the file, used when passing the file to the model as + a + + string. + file_data: + type: string + description: > + The base64 encoded file data, used when passing the file to the + model + + as a string. + file_id: + type: string + description: | + The ID of an uploaded file to use as input. + required: + - type + - file + ChatCompletionRequestMessageContentPartImage: + type: object + title: Image content part + description: | + Learn about [image inputs](/docs/guides/vision). + properties: + type: + type: string + enum: + - image_url + description: The type of the content part. + x-stainless-const: true + image_url: + type: object + properties: + url: + type: string + description: Either a URL of the image or the base64 encoded image data. + format: uri + detail: + type: string + description: >- + Specifies the detail level of the image. Learn more in the + [Vision + guide](/docs/guides/vision#low-or-high-fidelity-image-understanding). + enum: + - auto + - low + - high + default: auto + required: + - url + required: + - type + - image_url + ChatCompletionRequestMessageContentPartRefusal: + type: object + title: Refusal content part + properties: + type: + type: string + enum: + - refusal + description: The type of the content part. + x-stainless-const: true + refusal: + type: string + description: The refusal message generated by the model. + required: + - type + - refusal + ChatCompletionRequestMessageContentPartText: + type: object + title: Text content part + description: | + Learn about [text inputs](/docs/guides/text-generation). + properties: + type: + type: string + enum: + - text + description: The type of the content part. + x-stainless-const: true + text: + type: string + description: The text content. + required: + - type + - text + ChatCompletionRequestSystemMessage: + type: object + title: System message + description: > + Developer-provided instructions that the model should follow, regardless + of + + messages sent by the user. With o1 models and newer, use `developer` + messages + + for this purpose instead. + properties: + content: + description: The contents of the system message. + oneOf: + - type: string + description: The contents of the system message. + title: Text content + - type: array + description: >- + An array of content parts with a defined type. For system + messages, only type `text` is supported. + title: Array of content parts + items: + $ref: >- + #/components/schemas/ChatCompletionRequestSystemMessageContentPart + minItems: 1 + role: + type: string + enum: + - system + description: The role of the messages author, in this case `system`. + x-stainless-const: true + name: + type: string + description: >- + An optional name for the participant. Provides the model information + to differentiate between participants of the same role. + required: + - content + - role + ChatCompletionRequestSystemMessageContentPart: + oneOf: + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' + ChatCompletionRequestToolMessage: + type: object + title: Tool message + properties: + role: + type: string + enum: + - tool + description: The role of the messages author, in this case `tool`. + x-stainless-const: true + content: + oneOf: + - type: string + description: The contents of the tool message. + title: Text content + - type: array + description: >- + An array of content parts with a defined type. For tool + messages, only type `text` is supported. + title: Array of content parts + items: + $ref: >- + #/components/schemas/ChatCompletionRequestToolMessageContentPart + minItems: 1 + description: The contents of the tool message. + tool_call_id: + type: string + description: Tool call that this message is responding to. + required: + - role + - content + - tool_call_id + ChatCompletionRequestToolMessageContentPart: + oneOf: + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' + ChatCompletionRequestUserMessage: + type: object + title: User message + description: | + Messages sent by an end user, containing prompts or additional context + information. + properties: + content: + description: | + The contents of the user message. + oneOf: + - type: string + description: The text contents of the message. + title: Text content + - type: array + description: >- + An array of content parts with a defined type. Supported options + differ based on the [model](/docs/models) being used to generate + the response. Can contain text, image, or audio inputs. + title: Array of content parts + items: + $ref: >- + #/components/schemas/ChatCompletionRequestUserMessageContentPart + minItems: 1 + role: + type: string + enum: + - user + description: The role of the messages author, in this case `user`. + x-stainless-const: true + name: + type: string + description: >- + An optional name for the participant. Provides the model information + to differentiate between participants of the same role. + required: + - content + - role + ChatCompletionRequestUserMessageContentPart: + oneOf: + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartText' + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartImage' + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartAudio' + - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartFile' + ChatCompletionResponseMessage: + type: object + description: A chat completion message generated by the model. + properties: + content: + anyOf: + - type: string + description: The contents of the message. + - type: 'null' + refusal: + anyOf: + - type: string + description: The refusal message generated by the model. + - type: 'null' + tool_calls: + $ref: '#/components/schemas/ChatCompletionMessageToolCalls' + annotations: + type: array + description: | + Annotations for the message, when applicable, as when using the + [web search tool](/docs/guides/tools-web-search?api-mode=chat). + items: + type: object + description: | + A URL citation when using web search. + required: + - type + - url_citation + properties: + type: + type: string + description: The type of the URL citation. Always `url_citation`. + enum: + - url_citation + x-stainless-const: true + url_citation: + type: object + description: A URL citation when using web search. + required: + - end_index + - start_index + - url + - title + properties: + end_index: + type: integer + description: >- + The index of the last character of the URL citation in the + message. + start_index: + type: integer + description: >- + The index of the first character of the URL citation in + the message. + url: + type: string + description: The URL of the web resource. + title: + type: string + description: The title of the web resource. + role: + type: string + enum: + - assistant + description: The role of the author of this message. + x-stainless-const: true + function_call: + type: object + deprecated: true + description: >- + Deprecated and replaced by `tool_calls`. The name and arguments of a + function that should be called, as generated by the model. + properties: + arguments: + type: string + description: >- + The arguments to call the function with, as generated by the + model in JSON format. Note that the model does not always + generate valid JSON, and may hallucinate parameters not defined + by your function schema. Validate the arguments in your code + before calling your function. + name: + type: string + description: The name of the function to call. + required: + - name + - arguments + audio: + anyOf: + - type: object + description: > + If the audio output modality is requested, this object contains + data + + about the audio response from the model. [Learn + more](/docs/guides/audio). + required: + - id + - expires_at + - data + - transcript + properties: + id: + type: string + description: Unique identifier for this audio response. + expires_at: + type: integer + description: > + The Unix timestamp (in seconds) for when this audio response + will + + no longer be accessible on the server for use in multi-turn + + conversations. + data: + type: string + description: > + Base64 encoded audio bytes generated by the model, in the + format + + specified in the request. + transcript: + type: string + description: Transcript of the audio generated by the model. + - type: 'null' + required: + - role + - content + - refusal + ChatCompletionRole: + type: string + description: The role of the author of a message + enum: + - developer + - system + - user + - assistant + - tool + - function + ChatCompletionStreamOptions: + anyOf: + - description: > + Options for streaming response. Only set this when you set `stream: + true`. + type: object + default: null + properties: + include_usage: + type: boolean + description: > + If set, an additional chunk will be streamed before the `data: + [DONE]` + + message. The `usage` field on this chunk shows the token usage + statistics + + for the entire request, and the `choices` field will always be + an empty + + array. + + + All other chunks will also include a `usage` field, but with a + null + + value. **NOTE:** If the stream is interrupted, you may not + receive the + + final usage chunk which contains the total token usage for the + request. + include_obfuscation: + type: boolean + description: > + When true, stream obfuscation will be enabled. Stream + obfuscation adds + + random characters to an `obfuscation` field on streaming delta + events to + + normalize payload sizes as a mitigation to certain side-channel + attacks. + + These obfuscation fields are included by default, but add a + small amount + + of overhead to the data stream. You can set + `include_obfuscation` to + + false to optimize for bandwidth if you trust the network links + between + + your application and the OpenAI API. + - type: 'null' + ChatCompletionStreamResponseDelta: + type: object + description: A chat completion delta generated by streamed model responses. + properties: + content: + anyOf: + - type: string + description: The contents of the chunk message. + - type: 'null' + function_call: + deprecated: true + type: object + description: >- + Deprecated and replaced by `tool_calls`. The name and arguments of a + function that should be called, as generated by the model. + properties: + arguments: + type: string + description: >- + The arguments to call the function with, as generated by the + model in JSON format. Note that the model does not always + generate valid JSON, and may hallucinate parameters not defined + by your function schema. Validate the arguments in your code + before calling your function. + name: + type: string + description: The name of the function to call. + tool_calls: + type: array + items: + $ref: '#/components/schemas/ChatCompletionMessageToolCallChunk' + role: + type: string + enum: + - developer + - system + - user + - assistant + - tool + description: The role of the author of this message. + refusal: + anyOf: + - type: string + description: The refusal message generated by the model. + - type: 'null' + ChatCompletionTokenLogprob: + type: object + properties: + token: + description: The token. + type: string + logprob: + description: >- + The log probability of this token, if it is within the top 20 most + likely tokens. Otherwise, the value `-9999.0` is used to signify + that the token is very unlikely. + type: number + bytes: + anyOf: + - description: >- + A list of integers representing the UTF-8 bytes representation + of the token. Useful in instances where characters are + represented by multiple tokens and their byte representations + must be combined to generate the correct text representation. + Can be `null` if there is no bytes representation for the token. + type: array + items: + type: integer + - type: 'null' + top_logprobs: + description: >- + List of the most likely tokens and their log probability, at this + token position. In rare cases, there may be fewer than the number of + requested `top_logprobs` returned. + type: array + items: + type: object + properties: + token: + description: The token. + type: string + logprob: + description: >- + The log probability of this token, if it is within the top 20 + most likely tokens. Otherwise, the value `-9999.0` is used to + signify that the token is very unlikely. + type: number + bytes: + anyOf: + - description: >- + A list of integers representing the UTF-8 bytes + representation of the token. Useful in instances where + characters are represented by multiple tokens and their + byte representations must be combined to generate the + correct text representation. Can be `null` if there is no + bytes representation for the token. + type: array + items: + type: integer + - type: 'null' + required: + - token + - logprob + - bytes + required: + - token + - logprob + - bytes + - top_logprobs + ChatCompletionTool: + type: object + title: Function tool + description: | + A function tool that can be used to generate a response. + properties: + type: + type: string + enum: + - function + description: The type of the tool. Currently, only `function` is supported. + x-stainless-const: true + function: + $ref: '#/components/schemas/FunctionObject' + required: + - type + - function + ChatCompletionToolChoiceOption: + description: > + Controls which (if any) tool is called by the model. + + `none` means the model will not call any tool and instead generates a + message. + + `auto` means the model can pick between generating a message or calling + one or more tools. + + `required` means the model must call one or more tools. + + Specifying a particular tool via `{"type": "function", "function": + {"name": "my_function"}}` forces the model to call that tool. + + + `none` is the default when no tools are present. `auto` is the default + if tools are present. + oneOf: + - type: string + title: Tool choice mode + description: > + `none` means the model will not call any tool and instead generates + a message. `auto` means the model can pick between generating a + message or calling one or more tools. `required` means the model + must call one or more tools. + enum: + - none + - auto + - required + - $ref: '#/components/schemas/ChatCompletionAllowedToolsChoice' + - $ref: '#/components/schemas/ChatCompletionNamedToolChoice' + - $ref: '#/components/schemas/ChatCompletionNamedToolChoiceCustom' + ChunkingStrategyRequestParam: + type: object + description: >- + The chunking strategy used to chunk the file(s). If not set, will use + the `auto` strategy. + oneOf: + - $ref: '#/components/schemas/AutoChunkingStrategyRequestParam' + - $ref: '#/components/schemas/StaticChunkingStrategyRequestParam' + discriminator: + propertyName: type + CodeInterpreterFileOutput: + type: object + title: Code interpreter file output + description: | + The output of a code interpreter tool call that is a file. + properties: + type: + type: string + enum: + - files + description: | + The type of the code interpreter file output. Always `files`. + x-stainless-const: true + files: + type: array + items: + type: object + properties: + mime_type: + type: string + description: | + The MIME type of the file. + file_id: + type: string + description: | + The ID of the file. + required: + - mime_type + - file_id + required: + - type + - files + CodeInterpreterTextOutput: + type: object + title: Code interpreter text output + description: | + The output of a code interpreter tool call that is text. + properties: + type: + type: string + enum: + - logs + description: | + The type of the code interpreter text output. Always `logs`. + x-stainless-const: true + logs: + type: string + description: | + The logs of the code interpreter tool call. + required: + - type + - logs + CodeInterpreterTool: + type: object + title: Code interpreter + description: | + A tool that runs Python code to help generate a response to a prompt. + properties: + type: + type: string + enum: + - code_interpreter + description: | + The type of the code interpreter tool. Always `code_interpreter`. + x-stainless-const: true + container: + description: > + The code interpreter container. Can be a container ID or an object + that + + specifies uploaded file IDs to make available to your code, along + with an + + optional `memory_limit` setting. + oneOf: + - type: string + description: The container ID. + - $ref: '#/components/schemas/AutoCodeInterpreterToolParam' + required: + - type + - container + CodeInterpreterToolCall: + type: object + title: Code interpreter tool call + description: | + A tool call to run code. + properties: + type: + type: string + enum: + - code_interpreter_call + default: code_interpreter_call + x-stainless-const: true + description: > + The type of the code interpreter tool call. Always + `code_interpreter_call`. + id: + type: string + description: | + The unique ID of the code interpreter tool call. + status: + type: string + enum: + - in_progress + - completed + - incomplete + - interpreting + - failed + description: > + The status of the code interpreter tool call. Valid values are + `in_progress`, `completed`, `incomplete`, `interpreting`, and + `failed`. + container_id: + type: string + description: | + The ID of the container used to run the code. + code: + anyOf: + - type: string + description: | + The code to run, or null if not available. + - type: 'null' + outputs: + anyOf: + - type: array + items: + oneOf: + - $ref: '#/components/schemas/CodeInterpreterOutputLogs' + - $ref: '#/components/schemas/CodeInterpreterOutputImage' + discriminator: + propertyName: type + discriminator: + propertyName: type + description: > + The outputs generated by the code interpreter, such as logs or + images. + + Can be null if no outputs are available. + - type: 'null' + required: + - type + - id + - status + - container_id + - code + - outputs + ComparisonFilter: + type: object + additionalProperties: false + title: Comparison Filter + description: > + A filter used to compare a specified attribute key to a given value + using a defined comparison operation. + properties: + type: + type: string + default: eq + enum: + - eq + - ne + - gt + - gte + - lt + - lte + - in + - nin + description: > + Specifies the comparison operator: `eq`, `ne`, `gt`, `gte`, `lt`, + `lte`, `in`, `nin`. + + - `eq`: equals + + - `ne`: not equal + + - `gt`: greater than + + - `gte`: greater than or equal + + - `lt`: less than + + - `lte`: less than or equal + + - `in`: in + + - `nin`: not in + key: + type: string + description: The key to compare against the value. + value: + oneOf: + - type: string + - type: number + - type: boolean + - type: array + items: + oneOf: + - type: string + - type: number + description: >- + The value to compare against the attribute key; supports string, + number, or boolean types. + required: + - type + - key + - value + x-oaiMeta: + name: ComparisonFilter + CompleteUploadRequest: + type: object + additionalProperties: false + properties: + part_ids: + type: array + description: | + The ordered list of Part IDs. + items: + type: string + md5: + description: > + The optional md5 checksum for the file contents to verify if the + bytes uploaded matches what you expect. + type: string + required: + - part_ids + CompletionUsage: + type: object + description: Usage statistics for the completion request. + properties: + completion_tokens: + type: integer + default: 0 + description: Number of tokens in the generated completion. + prompt_tokens: + type: integer + default: 0 + description: Number of tokens in the prompt. + total_tokens: + type: integer + default: 0 + description: Total number of tokens used in the request (prompt + completion). + completion_tokens_details: + type: object + description: Breakdown of tokens used in a completion. + properties: + accepted_prediction_tokens: + type: integer + default: 0 + description: | + When using Predicted Outputs, the number of tokens in the + prediction that appeared in the completion. + audio_tokens: + type: integer + default: 0 + description: Audio input tokens generated by the model. + reasoning_tokens: + type: integer + default: 0 + description: Tokens generated by the model for reasoning. + rejected_prediction_tokens: + type: integer + default: 0 + description: > + When using Predicted Outputs, the number of tokens in the + + prediction that did not appear in the completion. However, like + + reasoning tokens, these tokens are still counted in the total + + completion tokens for purposes of billing, output, and context + window + + limits. + prompt_tokens_details: + type: object + description: Breakdown of tokens used in the prompt. + properties: + audio_tokens: + type: integer + default: 0 + description: Audio input tokens present in the prompt. + cached_tokens: + type: integer + default: 0 + description: Cached tokens present in the prompt. + required: + - prompt_tokens + - completion_tokens + - total_tokens + CompoundFilter: + $recursiveAnchor: true + type: object + additionalProperties: false + title: Compound Filter + description: Combine multiple filters using `and` or `or`. + properties: + type: + type: string + description: 'Type of operation: `and` or `or`.' + enum: + - and + - or + filters: + type: array + description: >- + Array of filters to combine. Items can be `ComparisonFilter` or + `CompoundFilter`. + items: + oneOf: + - $ref: '#/components/schemas/ComparisonFilter' + - $recursiveRef: '#' + discriminator: + propertyName: type + required: + - type + - filters + x-oaiMeta: + name: CompoundFilter + ComputerAction: + oneOf: + - $ref: '#/components/schemas/ClickParam' + - $ref: '#/components/schemas/DoubleClickAction' + - $ref: '#/components/schemas/DragParam' + - $ref: '#/components/schemas/KeyPressAction' + - $ref: '#/components/schemas/MoveParam' + - $ref: '#/components/schemas/ScreenshotParam' + - $ref: '#/components/schemas/ScrollParam' + - $ref: '#/components/schemas/TypeParam' + - $ref: '#/components/schemas/WaitParam' + discriminator: + propertyName: type + ComputerActionList: + title: Computer Action List + type: array + description: | + Flattened batched actions for `computer_use`. Each action includes an + `type` discriminator and action-specific fields. + items: + $ref: '#/components/schemas/ComputerAction' + ComputerScreenshotImage: + type: object + description: | + A computer screenshot image used with the computer use tool. + properties: + type: + type: string + enum: + - computer_screenshot + default: computer_screenshot + description: > + Specifies the event type. For a computer screenshot, this property + is + + always set to `computer_screenshot`. + x-stainless-const: true + image_url: + type: string + description: The URL of the screenshot image. + file_id: + type: string + description: The identifier of an uploaded file that contains the screenshot. + required: + - type + ComputerToolCall: + type: object + title: Computer tool call + description: > + A tool call to a computer use tool. See the + + [computer use guide](/docs/guides/tools-computer-use) for more + information. + properties: + type: + type: string + description: The type of the computer call. Always `computer_call`. + enum: + - computer_call + default: computer_call + id: + type: string + description: The unique ID of the computer call. + call_id: + type: string + description: | + An identifier used when responding to the tool call with output. + action: + $ref: '#/components/schemas/ComputerAction' + actions: + $ref: '#/components/schemas/ComputerActionList' + pending_safety_checks: + type: array + items: + $ref: '#/components/schemas/ComputerCallSafetyCheckParam' + description: | + The pending safety checks for the computer call. + status: + type: string + description: | + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + enum: + - in_progress + - completed + - incomplete + required: + - type + - id + - call_id + - pending_safety_checks + - status + ComputerToolCallOutput: + type: object + title: Computer tool call output + description: | + The output of a computer tool call. + properties: + type: + type: string + description: > + The type of the computer tool call output. Always + `computer_call_output`. + enum: + - computer_call_output + default: computer_call_output + x-stainless-const: true + id: + type: string + description: | + The ID of the computer tool call output. + call_id: + type: string + description: | + The ID of the computer tool call that produced the output. + acknowledged_safety_checks: + type: array + description: > + The safety checks reported by the API that have been acknowledged by + the + + developer. + items: + $ref: '#/components/schemas/ComputerCallSafetyCheckParam' + output: + $ref: '#/components/schemas/ComputerScreenshotImage' + status: + type: string + description: > + The status of the message input. One of `in_progress`, `completed`, + or + + `incomplete`. Populated when input items are returned via API. + enum: + - in_progress + - completed + - incomplete + required: + - type + - call_id + - output + ComputerToolCallOutputResource: + allOf: + - $ref: '#/components/schemas/ComputerToolCallOutput' + - type: object + properties: + id: + type: string + description: | + The unique ID of the computer call tool output. + status: + description: > + The status of the message input. One of `in_progress`, + `completed`, or + + `incomplete`. Populated when input items are returned via API. + $ref: '#/components/schemas/ComputerCallOutputStatus' + created_by: + type: string + description: | + The identifier of the actor that created the item. + required: + - id + - status + ContainerFileListResource: + type: object + properties: + object: + type: string + enum: + - list + description: The type of object returned, must be 'list'. + data: + type: array + description: A list of container files. + items: + $ref: '#/components/schemas/ContainerFileResource' + first_id: + type: string + description: The ID of the first file in the list. + last_id: + type: string + description: The ID of the last file in the list. + has_more: + type: boolean + description: Whether there are more files available. + required: + - object + - data + - first_id + - last_id + - has_more + ContainerFileResource: + type: object + title: The container file object + properties: + id: + type: string + description: Unique identifier for the file. + object: + type: string + description: The type of this object (`container.file`). + container_id: + type: string + description: The container this file belongs to. + created_at: + type: integer + description: Unix timestamp (in seconds) when the file was created. + bytes: + type: integer + description: Size of the file in bytes. + path: + type: string + description: Path of the file in the container. + source: + type: string + description: Source of the file (e.g., `user`, `assistant`). + required: + - id + - object + - created_at + - bytes + - container_id + - path + - source + x-oaiMeta: + name: The container file object + example: | + { + "id": "cfile_682e0e8a43c88191a7978f477a09bdf5", + "object": "container.file", + "created_at": 1747848842, + "bytes": 880, + "container_id": "cntr_682e0e7318108198aa783fd921ff305e08e78805b9fdbb04", + "path": "/mnt/data/88e12fa445d32636f190a0b33daed6cb-tsconfig.json", + "source": "user" + } + ContainerListResource: + type: object + properties: + object: + type: string + enum: + - list + description: The type of object returned, must be 'list'. + data: + type: array + description: A list of containers. + items: + $ref: '#/components/schemas/ContainerResource' + first_id: + type: string + description: The ID of the first container in the list. + last_id: + type: string + description: The ID of the last container in the list. + has_more: + type: boolean + description: Whether there are more containers available. + required: + - object + - data + - first_id + - last_id + - has_more + ContainerResource: + type: object + title: The container object + properties: + id: + type: string + description: Unique identifier for the container. + object: + type: string + description: The type of this object. + name: + type: string + description: Name of the container. + created_at: + type: integer + description: Unix timestamp (in seconds) when the container was created. + status: + type: string + description: Status of the container (e.g., active, deleted). + last_active_at: + type: integer + description: Unix timestamp (in seconds) when the container was last active. + expires_after: + type: object + description: > + The container will expire after this time period. + + The anchor is the reference point for the expiration. + + The minutes is the number of minutes after the anchor before the + container expires. + properties: + anchor: + type: string + description: The reference point for the expiration. + enum: + - last_active_at + minutes: + type: integer + description: >- + The number of minutes after the anchor before the container + expires. + memory_limit: + type: string + description: The memory limit configured for the container. + enum: + - 1g + - 4g + - 16g + - 64g + network_policy: + description: Network access policy for the container. + type: object + properties: + type: + type: string + description: The network policy mode. + enum: + - allowlist + - disabled + allowed_domains: + type: array + description: Allowed outbound domains when `type` is `allowlist`. + items: + type: string + required: + - type + required: + - id + - object + - name + - created_at + - status + - id + - name + - created_at + - status + x-oaiMeta: + name: The container object + example: | + { + "id": "cntr_682dfebaacac8198bbfe9c2474fb6f4a085685cbe3cb5863", + "object": "container", + "created_at": 1747844794, + "status": "running", + "expires_after": { + "anchor": "last_active_at", + "minutes": 20 + }, + "last_active_at": 1747844794, + "memory_limit": "1g", + "name": "My Container" + } + Content: + description: | + Multi-modal input and output contents. + oneOf: + - title: Input content types + $ref: '#/components/schemas/InputContent' + - title: Output content types + $ref: '#/components/schemas/OutputContent' + ConversationItem: + title: Conversation item + description: >- + A single item within a conversation. The set of possible types are the + same as the `output` type of a [Response + object](/docs/api-reference/responses/object#responses/object-output). + oneOf: + - $ref: '#/components/schemas/Message' + - $ref: '#/components/schemas/FunctionToolCallResource' + - $ref: '#/components/schemas/FunctionToolCallOutputResource' + - $ref: '#/components/schemas/FileSearchToolCall' + - $ref: '#/components/schemas/WebSearchToolCall' + - $ref: '#/components/schemas/ImageGenToolCall' + - $ref: '#/components/schemas/ComputerToolCall' + - $ref: '#/components/schemas/ComputerToolCallOutputResource' + - $ref: '#/components/schemas/ToolSearchCall' + - $ref: '#/components/schemas/ToolSearchOutput' + - $ref: '#/components/schemas/ReasoningItem' + - $ref: '#/components/schemas/CompactionBody' + - $ref: '#/components/schemas/CodeInterpreterToolCall' + - $ref: '#/components/schemas/LocalShellToolCall' + - $ref: '#/components/schemas/LocalShellToolCallOutput' + - $ref: '#/components/schemas/FunctionShellCall' + - $ref: '#/components/schemas/FunctionShellCallOutput' + - $ref: '#/components/schemas/ApplyPatchToolCall' + - $ref: '#/components/schemas/ApplyPatchToolCallOutput' + - $ref: '#/components/schemas/MCPListTools' + - $ref: '#/components/schemas/MCPApprovalRequest' + - $ref: '#/components/schemas/MCPApprovalResponseResource' + - $ref: '#/components/schemas/MCPToolCall' + - $ref: '#/components/schemas/CustomToolCall' + - $ref: '#/components/schemas/CustomToolCallOutput' + discriminator: + propertyName: type + ConversationItemList: + type: object + title: The conversation item list + description: A list of Conversation items. + properties: + object: + type: string + description: The type of object returned, must be `list`. + enum: + - list + x-stainless-const: true + data: + type: array + description: A list of conversation items. + items: + $ref: '#/components/schemas/ConversationItem' + has_more: + type: boolean + description: Whether there are more items available. + first_id: + type: string + description: The ID of the first item in the list. + last_id: + type: string + description: The ID of the last item in the list. + required: + - object + - data + - has_more + - first_id + - last_id + x-oaiMeta: + name: The item list + group: conversations + ConversationParam: + description: > + The conversation that this response belongs to. Items from this + conversation are prepended to `input_items` for this response request. + + Input items and output items from this response are automatically added + to this conversation after this response completes. + default: null + oneOf: + - type: string + title: Conversation ID + description: | + The unique ID of the conversation. + - $ref: '#/components/schemas/ConversationParam-2' + CostsResult: + type: object + description: The aggregated costs details of the specific time bucket. + properties: + object: + type: string + enum: + - organization.costs.result + x-stainless-const: true + amount: + type: object + description: The monetary value in its associated currency. + properties: + value: + type: number + description: The numeric value of the cost. + currency: + type: string + description: Lowercase ISO-4217 currency e.g. "usd" + line_item: + anyOf: + - type: string + description: >- + When `group_by=line_item`, this field provides the line item of + the grouped costs result. + - type: 'null' + project_id: + anyOf: + - type: string + description: >- + When `group_by=project_id`, this field provides the project ID + of the grouped costs result. + - type: 'null' + required: + - object + x-oaiMeta: + name: Costs object + example: | + { + "object": "organization.costs.result", + "amount": { + "value": 0.06, + "currency": "usd" + }, + "line_item": "Image models", + "project_id": "proj_abc" + } + CreateAssistantRequest: + type: object + additionalProperties: false + properties: + model: + description: > + ID of the model to use. You can use the [List + models](/docs/api-reference/models/list) API to see all of your + available models, or see our [Model overview](/docs/models) for + descriptions of them. + example: gpt-4o + anyOf: + - type: string + - $ref: '#/components/schemas/AssistantSupportedModels' + x-oaiTypeLabel: string + name: + anyOf: + - description: | + The name of the assistant. The maximum length is 256 characters. + type: string + maxLength: 256 + - type: 'null' + description: + anyOf: + - description: > + The description of the assistant. The maximum length is 512 + characters. + type: string + maxLength: 512 + - type: 'null' + instructions: + anyOf: + - description: > + The system instructions that the assistant uses. The maximum + length is 256,000 characters. + type: string + maxLength: 256000 + - type: 'null' + reasoning_effort: + $ref: '#/components/schemas/ReasoningEffort' + tools: + description: > + A list of tool enabled on the assistant. There can be a maximum of + 128 tools per assistant. Tools can be of types `code_interpreter`, + `file_search`, or `function`. + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: '#/components/schemas/AssistantToolsCode' + - $ref: '#/components/schemas/AssistantToolsFileSearch' + - $ref: '#/components/schemas/AssistantToolsFunction' + tool_resources: + anyOf: + - type: object + description: > + A set of resources that are used by the assistant's tools. The + resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the + `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: > + A list of [file](/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a + maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: > + The [vector + store](/docs/api-reference/vector-stores/object) + attached to this assistant. There can be a maximum of 1 + vector store attached to the assistant. + maxItems: 1 + items: + type: string + vector_stores: + type: array + description: > + A helper to create a [vector + store](/docs/api-reference/vector-stores/object) with + file_ids and attach it to this assistant. There can be a + maximum of 1 vector store attached to the assistant. + maxItems: 1 + items: + type: object + properties: + file_ids: + type: array + description: > + A list of [file](/docs/api-reference/files) IDs to + add to the vector store. For vector stores created + before Nov 2025, there can be a maximum of 10,000 + files in a vector store. For vector stores created + starting in Nov 2025, the limit is 100,000,000 + files. + maxItems: 100000000 + items: + type: string + chunking_strategy: + type: object + description: >- + The chunking strategy used to chunk the file(s). + If not set, will use the `auto` strategy. + oneOf: + - type: object + title: Auto Chunking Strategy + description: >- + The default strategy. This strategy currently + uses a `max_chunk_size_tokens` of `800` and + `chunk_overlap_tokens` of `400`. + additionalProperties: false + properties: + type: + type: string + description: Always `auto`. + enum: + - auto + x-stainless-const: true + required: + - type + - type: object + title: Static Chunking Strategy + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: + - static + x-stainless-const: true + static: + type: object + additionalProperties: false + properties: + max_chunk_size_tokens: + type: integer + minimum: 100 + maximum: 4096 + description: >- + The maximum number of tokens in each + chunk. The default value is `800`. The + minimum value is `100` and the maximum + value is `4096`. + chunk_overlap_tokens: + type: integer + description: > + The number of tokens that overlap + between chunks. The default value is + `400`. + + + Note that the overlap must not exceed + half of `max_chunk_size_tokens`. + required: + - max_chunk_size_tokens + - chunk_overlap_tokens + required: + - type + - static + metadata: + $ref: '#/components/schemas/Metadata' + oneOf: + - required: + - vector_store_ids + - required: + - vector_stores + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + temperature: + anyOf: + - description: > + What sampling temperature to use, between 0 and 2. Higher values + like 0.8 will make the output more random, while lower values + like 0.2 will make it more focused and deterministic. + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + - type: 'null' + top_p: + anyOf: + - type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + description: > + An alternative to sampling with temperature, called nucleus + sampling, where the model considers the results of the tokens + with top_p probability mass. So 0.1 means only the tokens + comprising the top 10% probability mass are considered. + + + We generally recommend altering this or temperature but not + both. + - type: 'null' + response_format: + anyOf: + - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' + - type: 'null' + required: + - model + CreateChatCompletionRequest: + allOf: + - $ref: '#/components/schemas/CreateModelResponseProperties' + - type: object + properties: + messages: + description: > + A list of messages comprising the conversation so far. Depending + on the + + [model](/docs/models) you use, different message types + (modalities) are + + supported, like [text](/docs/guides/text-generation), + + [images](/docs/guides/vision), and [audio](/docs/guides/audio). + type: array + minItems: 1 + items: + $ref: '#/components/schemas/ChatCompletionRequestMessage' + model: + description: > + Model ID used to generate the response, like `gpt-4o` or `o3`. + OpenAI + + offers a wide range of models with different capabilities, + performance + + characteristics, and price points. Refer to the [model + guide](/docs/models) + + to browse and compare available models. + $ref: '#/components/schemas/ModelIdsShared' + modalities: + $ref: '#/components/schemas/ResponseModalities' + verbosity: + $ref: '#/components/schemas/Verbosity' + reasoning_effort: + $ref: '#/components/schemas/ReasoningEffort' + max_completion_tokens: + description: > + An upper bound for the number of tokens that can be generated + for a completion, including visible output tokens and [reasoning + tokens](/docs/guides/reasoning). + type: integer + nullable: true + frequency_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: > + Number between -2.0 and 2.0. Positive values penalize new tokens + based on + + their existing frequency in the text so far, decreasing the + model's + + likelihood to repeat the same line verbatim. + presence_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: > + Number between -2.0 and 2.0. Positive values penalize new tokens + based on + + whether they appear in the text so far, increasing the model's + likelihood + + to talk about new topics. + web_search_options: + type: object + title: Web search + description: > + This tool searches the web for relevant results to use in a + response. + + Learn more about the [web search + tool](/docs/guides/tools-web-search?api-mode=chat). + properties: + user_location: + type: object + nullable: true + required: + - type + - approximate + description: | + Approximate location parameters for the search. + properties: + type: + type: string + description: > + The type of location approximation. Always + `approximate`. + enum: + - approximate + x-stainless-const: true + approximate: + $ref: '#/components/schemas/WebSearchLocation' + search_context_size: + $ref: '#/components/schemas/WebSearchContextSize' + top_logprobs: + description: > + An integer between 0 and 20 specifying the number of most likely + tokens to + + return at each token position, each with an associated log + probability. + + `logprobs` must be set to `true` if this parameter is used. + type: integer + minimum: 0 + maximum: 20 + nullable: true + response_format: + description: > + An object specifying the format that the model must output. + + + Setting to `{ "type": "json_schema", "json_schema": {...} }` + enables + + Structured Outputs which ensures the model will match your + supplied JSON + + schema. Learn more in the [Structured Outputs + + guide](/docs/guides/structured-outputs). + + + Setting to `{ "type": "json_object" }` enables the older JSON + mode, which + + ensures the message the model generates is valid JSON. Using + `json_schema` + + is preferred for models that support it. + oneOf: + - $ref: '#/components/schemas/ResponseFormatText' + - $ref: '#/components/schemas/ResponseFormatJsonSchema' + - $ref: '#/components/schemas/ResponseFormatJsonObject' + discriminator: + propertyName: type + audio: + type: object + nullable: true + description: > + Parameters for audio output. Required when audio output is + requested with + + `modalities: ["audio"]`. [Learn more](/docs/guides/audio). + required: + - voice + - format + properties: + voice: + $ref: '#/components/schemas/VoiceIdsOrCustomVoice' + description: > + The voice the model uses to respond. Supported built-in + voices are + + `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, `nova`, + `onyx`, + + `sage`, `shimmer`, `marin`, and `cedar`. You may also + provide a + + custom voice object with an `id`, for example `{ "id": + "voice_1234" }`. + format: + type: string + enum: + - wav + - aac + - mp3 + - flac + - opus + - pcm16 + description: > + Specifies the output audio format. Must be one of `wav`, + `mp3`, `flac`, + + `opus`, or `pcm16`. + store: + type: boolean + default: false + nullable: true + description: > + Whether or not to store the output of this chat completion + request for + + use in our [model distillation](/docs/guides/distillation) or + + [evals](/docs/guides/evals) products. + + + Supports text and image inputs. Note: image inputs over 8MB will + be dropped. + stream: + description: > + 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/chat/streaming) + + for more information, along with the [streaming + responses](/docs/guides/streaming-responses) + + guide for more information on how to handle the streaming + events. + type: boolean + nullable: true + default: false + stop: + $ref: '#/components/schemas/StopConfiguration' + logit_bias: + type: object + x-oaiTypeLabel: map + default: null + nullable: true + additionalProperties: + type: integer + description: > + Modify the likelihood of specified tokens appearing in the + completion. + + + Accepts a JSON object that maps tokens (specified by their token + ID in the + + tokenizer) to an associated bias value from -100 to 100. + Mathematically, + + the bias is added to the logits generated by the model prior to + sampling. + + The exact effect will vary per model, but values between -1 and + 1 should + + decrease or increase likelihood of selection; values like -100 + or 100 + + should result in a ban or exclusive selection of the relevant + token. + logprobs: + description: > + Whether to return log probabilities of the output tokens or not. + If true, + + returns the log probabilities of each output token returned in + the + + `content` of `message`. + type: boolean + default: false + nullable: true + max_tokens: + description: > + The maximum number of [tokens](/tokenizer) that can be generated + in the + + chat completion. This value can be used to control + + [costs](https://openai.com/api/pricing/) for text generated via + API. + + + This value is now deprecated in favor of + `max_completion_tokens`, and is + + not compatible with [o-series models](/docs/guides/reasoning). + type: integer + nullable: true + deprecated: true + 'n': + type: integer + minimum: 1 + maximum: 128 + default: 1 + example: 1 + nullable: true + description: >- + How many chat completion choices to generate for each input + message. Note that you will be charged based on the number of + generated tokens across all of the choices. Keep `n` as `1` to + minimize costs. + prediction: + nullable: true + description: > + Configuration for a [Predicted + Output](/docs/guides/predicted-outputs), + + which can greatly improve response times when large parts of the + model + + response are known ahead of time. This is most common when you + are + + regenerating a file with only minor changes to most of the + content. + oneOf: + - $ref: '#/components/schemas/PredictionContent' + seed: + type: integer + minimum: -922337203685477600 + maximum: 922337203685477600 + nullable: true + deprecated: true + description: > + This feature is in Beta. + + If specified, our system will make a best effort to sample + deterministically, such that repeated requests with the same + `seed` and parameters should return the same result. + + Determinism is not guaranteed, and you should refer to the + `system_fingerprint` response parameter to monitor changes in + the backend. + x-oaiMeta: + beta: true + stream_options: + $ref: '#/components/schemas/ChatCompletionStreamOptions' + tools: + type: array + description: | + A list of tools the model may call. You can provide either + [custom tools](/docs/guides/function-calling#custom-tools) or + [function tools](/docs/guides/function-calling). + items: + oneOf: + - $ref: '#/components/schemas/ChatCompletionTool' + - $ref: '#/components/schemas/CustomToolChatCompletions' + tool_choice: + $ref: '#/components/schemas/ChatCompletionToolChoiceOption' + parallel_tool_calls: + $ref: '#/components/schemas/ParallelToolCalls' + function_call: + deprecated: true + description: > + Deprecated in favor of `tool_choice`. + + + Controls which (if any) function is called by the model. + + + `none` means the model will not call a function and instead + generates a + + message. + + + `auto` means the model can pick between generating a message or + calling a + + function. + + + Specifying a particular function via `{"name": "my_function"}` + forces the + + model to call that function. + + + `none` is the default when no functions are present. `auto` is + the default + + if functions are present. + oneOf: + - type: string + description: > + `none` means the model will not call a function and instead + generates a message. `auto` means the model can pick between + generating a message or calling a function. + enum: + - none + - auto + - $ref: '#/components/schemas/ChatCompletionFunctionCallOption' + functions: + deprecated: true + description: | + Deprecated in favor of `tools`. + + A list of functions the model may generate JSON inputs for. + type: array + minItems: 1 + maxItems: 128 + items: + $ref: '#/components/schemas/ChatCompletionFunctions' + required: + - model + - messages + CreateChatCompletionResponse: + type: object + description: >- + Represents a chat completion response returned by model, based on the + provided input. + properties: + id: + type: string + description: A unique identifier for the chat completion. + choices: + type: array + description: >- + A list of chat completion choices. Can be more than one if `n` is + greater than 1. + items: + type: object + required: + - finish_reason + - index + - message + - logprobs + properties: + finish_reason: + type: string + description: > + The reason the model stopped generating tokens. This will be + `stop` if the model hit a natural stop point or a provided + stop sequence, + + `length` if the maximum number of tokens specified in the + request was reached, + + `content_filter` if content was omitted due to a flag from our + content filters, + + `tool_calls` if the model called a tool, or `function_call` + (deprecated) if the model called a function. + enum: + - stop + - length + - tool_calls + - content_filter + - function_call + index: + type: integer + description: The index of the choice in the list of choices. + message: + $ref: '#/components/schemas/ChatCompletionResponseMessage' + logprobs: + anyOf: + - description: Log probability information for the choice. + type: object + properties: + content: + anyOf: + - description: >- + A list of message content tokens with log + probability information. + type: array + items: + $ref: '#/components/schemas/ChatCompletionTokenLogprob' + - type: 'null' + refusal: + anyOf: + - description: >- + A list of message refusal tokens with log + probability information. + type: array + items: + $ref: '#/components/schemas/ChatCompletionTokenLogprob' + - type: 'null' + required: + - content + - refusal + - type: 'null' + created: + type: integer + description: >- + The Unix timestamp (in seconds) of when the chat completion was + created. + model: + type: string + description: The model used for the chat completion. + service_tier: + $ref: '#/components/schemas/ServiceTier' + system_fingerprint: + type: string + deprecated: true + description: > + This fingerprint represents the backend configuration that the model + runs with. + + + Can be used in conjunction with the `seed` request parameter to + understand when backend changes have been made that might impact + determinism. + object: + type: string + description: The object type, which is always `chat.completion`. + enum: + - chat.completion + x-stainless-const: true + usage: + $ref: '#/components/schemas/CompletionUsage' + required: + - choices + - created + - id + - model + - object + x-oaiMeta: + name: The chat completion object + group: chat + example: | + { + "id": "chatcmpl-B9MHDbslfkBeAs8l4bebGdFOJ6PeG", + "object": "chat.completion", + "created": 1741570283, + "model": "gpt-4o-2024-08-06", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": "The image shows a wooden boardwalk path running through a lush green field or meadow. The sky is bright blue with some scattered clouds, giving the scene a serene and peaceful atmosphere. Trees and shrubs are visible in the background.", + "refusal": null, + "annotations": [] + }, + "logprobs": null, + "finish_reason": "stop" + } + ], + "usage": { + "prompt_tokens": 1117, + "completion_tokens": 46, + "total_tokens": 1163, + "prompt_tokens_details": { + "cached_tokens": 0, + "audio_tokens": 0 + }, + "completion_tokens_details": { + "reasoning_tokens": 0, + "audio_tokens": 0, + "accepted_prediction_tokens": 0, + "rejected_prediction_tokens": 0 + } + }, + "service_tier": "default", + "system_fingerprint": "fp_fc9f1d7035" + } + CreateChatCompletionStreamResponse: + type: object + description: | + Represents a streamed chunk of a chat completion response returned + by the model, based on the provided input. + [Learn more](/docs/guides/streaming-responses). + properties: + id: + type: string + description: >- + A unique identifier for the chat completion. Each chunk has the same + ID. + choices: + type: array + description: > + A list of chat completion choices. Can contain more than one + elements if `n` is greater than 1. Can also be empty for the + + last chunk if you set `stream_options: {"include_usage": true}`. + items: + type: object + required: + - delta + - finish_reason + - index + properties: + delta: + $ref: '#/components/schemas/ChatCompletionStreamResponseDelta' + logprobs: + description: Log probability information for the choice. + type: object + nullable: true + properties: + content: + description: >- + A list of message content tokens with log probability + information. + type: array + items: + $ref: '#/components/schemas/ChatCompletionTokenLogprob' + nullable: true + refusal: + description: >- + A list of message refusal tokens with log probability + information. + type: array + items: + $ref: '#/components/schemas/ChatCompletionTokenLogprob' + nullable: true + required: + - content + - refusal + finish_reason: + type: string + description: > + The reason the model stopped generating tokens. This will be + `stop` if the model hit a natural stop point or a provided + stop sequence, + + `length` if the maximum number of tokens specified in the + request was reached, + + `content_filter` if content was omitted due to a flag from our + content filters, + + `tool_calls` if the model called a tool, or `function_call` + (deprecated) if the model called a function. + enum: + - stop + - length + - tool_calls + - content_filter + - function_call + nullable: true + index: + type: integer + description: The index of the choice in the list of choices. + created: + type: integer + description: >- + The Unix timestamp (in seconds) of when the chat completion was + created. Each chunk has the same timestamp. + model: + type: string + description: The model to generate the completion. + service_tier: + $ref: '#/components/schemas/ServiceTier' + system_fingerprint: + type: string + deprecated: true + description: > + This fingerprint represents the backend configuration that the model + runs with. + + Can be used in conjunction with the `seed` request parameter to + understand when backend changes have been made that might impact + determinism. + object: + type: string + description: The object type, which is always `chat.completion.chunk`. + enum: + - chat.completion.chunk + x-stainless-const: true + usage: + $ref: '#/components/schemas/CompletionUsage' + nullable: true + description: > + An optional field that will only be present when you set + + `stream_options: {"include_usage": true}` in your request. When + present, it + + contains a null value **except for the last chunk** which contains + the + + token usage statistics for the entire request. + + + **NOTE:** If the stream is interrupted or cancelled, you may not + + receive the final usage chunk which contains the total token usage + for + + the request. + required: + - choices + - created + - id + - model + - object + x-oaiMeta: + name: The chat completion chunk object + group: chat + example: > + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", + "system_fingerprint": "fp_44709d6fcb", + "choices":[{"index":0,"delta":{"role":"assistant","content":""},"logprobs":null,"finish_reason":null}]} + + + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", + "system_fingerprint": "fp_44709d6fcb", + "choices":[{"index":0,"delta":{"content":"Hello"},"logprobs":null,"finish_reason":null}]} + + + .... + + + {"id":"chatcmpl-123","object":"chat.completion.chunk","created":1694268190,"model":"gpt-4o-mini", + "system_fingerprint": "fp_44709d6fcb", + "choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} + CreateCompletionRequest: + type: object + properties: + model: + description: > + ID of the model to use. You can use the [List + models](/docs/api-reference/models/list) API to see all of your + available models, or see our [Model overview](/docs/models) for + descriptions of them. + anyOf: + - type: string + - type: string + enum: + - gpt-3.5-turbo-instruct + - davinci-002 + - babbage-002 + x-oaiTypeLabel: string + prompt: + description: > + The prompt(s) to generate completions for, encoded as a string, + array of strings, array of tokens, or array of token arrays. + + + Note that <|endoftext|> is the document separator that the model + sees during training, so if a prompt is not specified the model will + generate as if from the beginning of a new document. + default: <|endoftext|> + nullable: true + oneOf: + - type: string + default: '' + example: This is a test. + - type: array + items: + type: string + default: '' + example: This is a test. + - type: array + minItems: 1 + items: + type: integer + example: '[1212, 318, 257, 1332, 13]' + - type: array + minItems: 1 + items: + type: array + minItems: 1 + items: + type: integer + example: '[[1212, 318, 257, 1332, 13]]' + best_of: + type: integer + default: 1 + minimum: 0 + maximum: 20 + nullable: true + description: > + Generates `best_of` completions server-side and returns the "best" + (the one with the highest log probability per token). Results cannot + be streamed. + + + When used with `n`, `best_of` controls the number of candidate + completions and `n` specifies how many to return – `best_of` must be + greater than `n`. + + + **Note:** Because this parameter generates many completions, it can + quickly consume your token quota. Use carefully and ensure that you + have reasonable settings for `max_tokens` and `stop`. + echo: + type: boolean + default: false + nullable: true + description: | + Echo back the prompt in addition to the completion + frequency_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: > + Number between -2.0 and 2.0. Positive values penalize new tokens + based on their existing frequency in the text so far, decreasing the + model's likelihood to repeat the same line verbatim. + + + [See more information about frequency and presence + penalties.](/docs/guides/text-generation) + logit_bias: + type: object + x-oaiTypeLabel: map + default: null + nullable: true + additionalProperties: + type: integer + description: > + Modify the likelihood of specified tokens appearing in the + completion. + + + Accepts a JSON object that maps tokens (specified by their token ID + in the GPT tokenizer) to an associated bias value from -100 to 100. + You can use this [tokenizer tool](/tokenizer?view=bpe) to convert + text to token IDs. Mathematically, the bias is added to the logits + generated by the model prior to sampling. The exact effect will vary + per model, but values between -1 and 1 should decrease or increase + likelihood of selection; values like -100 or 100 should result in a + ban or exclusive selection of the relevant token. + + + As an example, you can pass `{"50256": -100}` to prevent the + <|endoftext|> token from being generated. + logprobs: + type: integer + minimum: 0 + maximum: 5 + default: null + nullable: true + description: > + Include the log probabilities on the `logprobs` most likely output + tokens, as well the chosen tokens. For example, if `logprobs` is 5, + the API will return a list of the 5 most likely tokens. The API will + always return the `logprob` of the sampled token, so there may be up + to `logprobs+1` elements in the response. + + + The maximum value for `logprobs` is 5. + max_tokens: + type: integer + minimum: 0 + default: 16 + example: 16 + nullable: true + description: > + The maximum number of [tokens](/tokenizer) that can be generated in + the completion. + + + The token count of your prompt plus `max_tokens` cannot exceed the + model's context length. [Example Python + code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. + 'n': + type: integer + minimum: 1 + maximum: 128 + default: 1 + example: 1 + nullable: true + description: > + How many completions to generate for each prompt. + + + **Note:** Because this parameter generates many completions, it can + quickly consume your token quota. Use carefully and ensure that you + have reasonable settings for `max_tokens` and `stop`. + presence_penalty: + type: number + default: 0 + minimum: -2 + maximum: 2 + nullable: true + description: > + Number between -2.0 and 2.0. Positive values penalize new tokens + based on whether they appear in the text so far, increasing the + model's likelihood to talk about new topics. + + + [See more information about frequency and presence + penalties.](/docs/guides/text-generation) + seed: + type: integer + format: int64 + nullable: true + description: > + If specified, our system will make a best effort to sample + deterministically, such that repeated requests with the same `seed` + and parameters should return the same result. + + + Determinism is not guaranteed, and you should refer to the + `system_fingerprint` response parameter to monitor changes in the + backend. + stop: + $ref: '#/components/schemas/StopConfiguration' + stream: + description: > + Whether to stream back partial progress. If set, tokens will be sent + as data-only [server-sent + events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) + as they become available, with the stream terminated by a `data: + [DONE]` message. [Example Python + code](https://cookbook.openai.com/examples/how_to_stream_completions). + type: boolean + nullable: true + default: false + stream_options: + $ref: '#/components/schemas/ChatCompletionStreamOptions' + suffix: + description: | + The suffix that comes after a completion of inserted text. + + This parameter is only supported for `gpt-3.5-turbo-instruct`. + default: null + nullable: true + type: string + example: test. + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: > + What sampling temperature to use, between 0 and 2. Higher values + like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + + + We generally recommend altering this or `top_p` but not both. + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: > + An alternative to sampling with temperature, called nucleus + sampling, where the model considers the results of the tokens with + top_p probability mass. So 0.1 means only the tokens comprising the + top 10% probability mass are considered. + + + We generally recommend altering this or `temperature` but not both. + user: + type: string + example: user-1234 + description: > + A unique identifier representing your end-user, which can help + OpenAI to monitor and detect abuse. [Learn + more](/docs/guides/safety-best-practices#end-user-ids). + required: + - model + - prompt + CreateCompletionResponse: + type: object + description: > + Represents a completion response from the API. Note: both the streamed + and non-streamed response objects share the same shape (unlike the chat + endpoint). + properties: + id: + type: string + description: A unique identifier for the completion. + choices: + type: array + description: >- + The list of completion choices the model generated for the input + prompt. + items: + type: object + required: + - finish_reason + - index + - logprobs + - text + properties: + finish_reason: + type: string + description: > + The reason the model stopped generating tokens. This will be + `stop` if the model hit a natural stop point or a provided + stop sequence, + + `length` if the maximum number of tokens specified in the + request was reached, + + or `content_filter` if content was omitted due to a flag from + our content filters. + enum: + - stop + - length + - content_filter + index: + type: integer + logprobs: + anyOf: + - type: object + properties: + text_offset: + type: array + items: + type: integer + token_logprobs: + type: array + items: + type: number + tokens: + type: array + items: + type: string + top_logprobs: + type: array + items: + type: object + additionalProperties: + type: number + - type: 'null' + text: + type: string + created: + type: integer + description: The Unix timestamp (in seconds) of when the completion was created. + model: + type: string + description: The model used for completion. + system_fingerprint: + type: string + description: > + This fingerprint represents the backend configuration that the model + runs with. + + + Can be used in conjunction with the `seed` request parameter to + understand when backend changes have been made that might impact + determinism. + object: + type: string + description: The object type, which is always "text_completion" + enum: + - text_completion + x-stainless-const: true + usage: + $ref: '#/components/schemas/CompletionUsage' + required: + - id + - object + - created + - model + - choices + x-oaiMeta: + name: The completion object + legacy: true + example: | + { + "id": "cmpl-uqkvlQyYK7bGYrRHQ0eXlWi7", + "object": "text_completion", + "created": 1589478378, + "model": "gpt-4-turbo", + "choices": [ + { + "text": "\n\nThis is indeed a test", + "index": 0, + "logprobs": null, + "finish_reason": "length" + } + ], + "usage": { + "prompt_tokens": 5, + "completion_tokens": 7, + "total_tokens": 12 + } + } + CreateContainerBody: + type: object + properties: + name: + type: string + description: Name of the container to create. + file_ids: + type: array + description: IDs of files to copy to the container. + items: + type: string + expires_after: + type: object + description: Container expiration time in seconds relative to the 'anchor' time. + properties: + anchor: + type: string + enum: + - last_active_at + description: >- + Time anchor for the expiration time. Currently only + 'last_active_at' is supported. + minutes: + type: integer + required: + - anchor + - minutes + skills: + type: array + description: An optional list of skills referenced by id or inline data. + items: + oneOf: + - $ref: '#/components/schemas/SkillReferenceParam' + - $ref: '#/components/schemas/InlineSkillParam' + discriminator: + propertyName: type + memory_limit: + type: string + enum: + - 1g + - 4g + - 16g + - 64g + description: Optional memory limit for the container. Defaults to "1g". + network_policy: + description: Network access policy for the container. + oneOf: + - $ref: '#/components/schemas/ContainerNetworkPolicyDisabledParam' + - $ref: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' + discriminator: + propertyName: type + required: + - name + CreateContainerFileBody: + type: object + properties: + file_id: + type: string + description: Name of the file to create. + file: + description: | + The File object (not file name) to be uploaded. + type: string + format: binary + required: [] + CreateEmbeddingRequest: + type: object + additionalProperties: false + properties: + input: + description: > + Input text to embed, encoded as a string or array of tokens. To + embed multiple inputs in a single request, pass an array of strings + or array of token arrays. The input must not exceed the max input + tokens for the model (8192 tokens for all embedding models), cannot + be an empty string, and any array must be 2048 dimensions or less. + [Example Python + code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) + for counting tokens. In addition to the per-input token limit, all + embedding models enforce a maximum of 300,000 tokens summed across + all inputs in a single request. + example: The quick brown fox jumped over the lazy dog + oneOf: + - type: string + title: string + description: The string that will be turned into an embedding. + default: '' + example: This is a test. + - type: array + title: array + description: The array of strings that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: string + default: '' + example: '[''This is a test.'']' + - type: array + title: array + description: The array of integers that will be turned into an embedding. + minItems: 1 + maxItems: 2048 + items: + type: integer + example: '[1212, 318, 257, 1332, 13]' + - type: array + title: array + description: >- + The array of arrays containing integers that will be turned into + an embedding. + minItems: 1 + maxItems: 2048 + items: + type: array + minItems: 1 + items: + type: integer + example: '[[1212, 318, 257, 1332, 13]]' + model: + description: > + ID of the model to use. You can use the [List + models](/docs/api-reference/models/list) API to see all of your + available models, or see our [Model overview](/docs/models) for + descriptions of them. + example: text-embedding-3-small + anyOf: + - type: string + - type: string + enum: + - text-embedding-ada-002 + - text-embedding-3-small + - text-embedding-3-large + x-oaiTypeLabel: string + encoding_format: + description: >- + The format to return the embeddings in. Can be either `float` or + [`base64`](https://pypi.org/project/pybase64/). + example: float + default: float + type: string + enum: + - float + - base64 + dimensions: + description: > + The number of dimensions the resulting output embeddings should + have. Only supported in `text-embedding-3` and later models. + type: integer + minimum: 1 + user: + type: string + example: user-1234 + description: > + A unique identifier representing your end-user, which can help + OpenAI to monitor and detect abuse. [Learn + more](/docs/guides/safety-best-practices#end-user-ids). + required: + - model + - input + CreateEmbeddingResponse: + type: object + properties: + data: + type: array + description: The list of embeddings generated by the model. + items: + $ref: '#/components/schemas/Embedding' + model: + type: string + description: The name of the model used to generate the embedding. + object: + type: string + description: The object type, which is always "list". + enum: + - list + x-stainless-const: true + usage: + type: object + description: The usage information for the request. + properties: + prompt_tokens: + type: integer + description: The number of tokens used by the prompt. + total_tokens: + type: integer + description: The total number of tokens used by the request. + required: + - prompt_tokens + - total_tokens + required: + - object + - model + - data + - usage + CreateEvalCompletionsRunDataSource: + type: object + title: CompletionsRunDataSource + description: > + A CompletionsRunDataSource object describing a model sampling + configuration. + properties: + type: + type: string + enum: + - completions + default: completions + description: The type of run data source. Always `completions`. + input_messages: + description: >- + Used when sampling from a model. Dictates the structure of the + messages passed into the model. Can either be a reference to a + prebuilt trajectory (ie, `item.input_trajectory`), or a template + with variable references to the `item` namespace. + oneOf: + - type: object + title: TemplateInputMessages + properties: + type: + type: string + enum: + - template + description: The type of input messages. Always `template`. + template: + type: array + description: >- + A list of chat messages forming the prompt or context. May + include variable references to the `item` namespace, ie + {{item.name}}. + items: + oneOf: + - $ref: '#/components/schemas/EasyInputMessage' + - $ref: '#/components/schemas/EvalItem' + required: + - type + - template + - type: object + title: ItemReferenceInputMessages + properties: + type: + type: string + enum: + - item_reference + description: The type of input messages. Always `item_reference`. + item_reference: + type: string + description: >- + A reference to a variable in the `item` namespace. Ie, + "item.input_trajectory" + required: + - type + - item_reference + sampling_params: + type: object + properties: + reasoning_effort: + $ref: '#/components/schemas/ReasoningEffort' + temperature: + type: number + description: A higher temperature increases randomness in the outputs. + default: 1 + max_completion_tokens: + type: integer + description: The maximum number of tokens in the generated output. + top_p: + type: number + description: >- + An alternative to temperature for nucleus sampling; 1.0 includes + all tokens. + default: 1 + seed: + type: integer + description: A seed value to initialize the randomness, during sampling. + default: 42 + response_format: + description: > + An object specifying the format that the model must output. + + + Setting to `{ "type": "json_schema", "json_schema": {...} }` + enables + + Structured Outputs which ensures the model will match your + supplied JSON + + schema. Learn more in the [Structured Outputs + + guide](/docs/guides/structured-outputs). + + + Setting to `{ "type": "json_object" }` enables the older JSON + mode, which + + ensures the message the model generates is valid JSON. Using + `json_schema` + + is preferred for models that support it. + oneOf: + - $ref: '#/components/schemas/ResponseFormatText' + - $ref: '#/components/schemas/ResponseFormatJsonSchema' + - $ref: '#/components/schemas/ResponseFormatJsonObject' + tools: + type: array + description: > + A list of tools the model may call. Currently, only functions + are supported as a tool. Use this to provide a list of functions + the model may generate JSON inputs for. A max of 128 functions + are supported. + items: + $ref: '#/components/schemas/ChatCompletionTool' + model: + type: string + description: >- + The name of the model to use for generating completions (e.g. + "o3-mini"). + source: + description: >- + Determines what populates the `item` namespace in this run's data + source. + oneOf: + - $ref: '#/components/schemas/EvalJsonlFileContentSource' + - $ref: '#/components/schemas/EvalJsonlFileIdSource' + - $ref: '#/components/schemas/EvalStoredCompletionsSource' + required: + - type + - source + x-oaiMeta: + name: The completions data source object used to configure an individual run + group: eval runs + example: | + { + "name": "gpt-4o-mini-2024-07-18", + "data_source": { + "type": "completions", + "input_messages": { + "type": "item_reference", + "item_reference": "item.input" + }, + "model": "gpt-4o-mini-2024-07-18", + "source": { + "type": "stored_completions", + "model": "gpt-4o-mini-2024-07-18" + } + } + } + CreateEvalCustomDataSourceConfig: + type: object + title: CustomDataSourceConfig + description: > + A CustomDataSourceConfig object that defines the schema for the data + source used for the evaluation runs. + + This schema is used to define the shape of the data that will be: + + - Used to define your testing criteria and + + - What data is required when creating a run + properties: + type: + type: string + enum: + - custom + default: custom + description: The type of data source. Always `custom`. + x-stainless-const: true + item_schema: + type: object + description: The json schema for each row in the data source. + additionalProperties: true + example: | + { + "type": "object", + "properties": { + "name": {"type": "string"}, + "age": {"type": "integer"} + }, + "required": ["name", "age"] + } + include_sample_schema: + type: boolean + default: false + description: >- + Whether the eval should expect you to populate the sample namespace + (ie, by generating responses off of your data source) + required: + - item_schema + - type + x-oaiMeta: + name: The eval file data source config object + group: evals + example: | + { + "type": "custom", + "item_schema": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "age": {"type": "integer"} + }, + "required": ["name", "age"] + }, + "include_sample_schema": true + } + CreateEvalItem: + title: CreateEvalItem + description: >- + A chat message that makes up the prompt or context. May include variable + references to the `item` namespace, ie {{item.name}}. + type: object + oneOf: + - type: object + title: SimpleInputMessage + properties: + role: + type: string + description: The role of the message (e.g. "system", "assistant", "user"). + content: + type: string + description: The content of the message. + required: + - role + - content + - $ref: '#/components/schemas/EvalItem' + x-oaiMeta: + name: The chat message object used to configure an individual run + CreateEvalJsonlRunDataSource: + type: object + title: JsonlRunDataSource + description: > + A JsonlRunDataSource object with that specifies a JSONL file that + matches the eval + properties: + type: + type: string + enum: + - jsonl + default: jsonl + description: The type of data source. Always `jsonl`. + x-stainless-const: true + source: + description: Determines what populates the `item` namespace in the data source. + oneOf: + - $ref: '#/components/schemas/EvalJsonlFileContentSource' + - $ref: '#/components/schemas/EvalJsonlFileIdSource' + required: + - type + - source + x-oaiMeta: + name: The file data source object for the eval run configuration + group: evals + example: | + { + "type": "jsonl", + "source": { + "type": "file_id", + "id": "file-9GYS6xbkWgWhmE7VoLUWFg" + } + } + CreateEvalLabelModelGrader: + type: object + title: LabelModelGrader + description: > + A LabelModelGrader object which uses a model to assign labels to each + item + + in the evaluation. + properties: + type: + description: The object type, which is always `label_model`. + type: string + enum: + - label_model + x-stainless-const: true + name: + type: string + description: The name of the grader. + model: + type: string + description: >- + The model to use for the evaluation. Must support structured + outputs. + input: + type: array + description: >- + A list of chat messages forming the prompt or context. May include + variable references to the `item` namespace, ie {{item.name}}. + items: + $ref: '#/components/schemas/CreateEvalItem' + labels: + type: array + items: + type: string + description: The labels to classify to each item in the evaluation. + passing_labels: + type: array + items: + type: string + description: >- + The labels that indicate a passing result. Must be a subset of + labels. + required: + - type + - model + - input + - passing_labels + - labels + - name + x-oaiMeta: + name: The eval label model grader object + group: evals + example: | + { + "type": "label_model", + "model": "gpt-4o-2024-08-06", + "input": [ + { + "role": "system", + "content": "Classify the sentiment of the following statement as one of 'positive', 'neutral', or 'negative'" + }, + { + "role": "user", + "content": "Statement: {{item.response}}" + } + ], + "passing_labels": ["positive"], + "labels": ["positive", "neutral", "negative"], + "name": "Sentiment label grader" + } + CreateEvalLogsDataSourceConfig: + type: object + title: LogsDataSourceConfig + description: > + A data source config which specifies the metadata property of your logs + query. + + This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, + etc. + properties: + type: + type: string + enum: + - logs + default: logs + description: The type of data source. Always `logs`. + x-stainless-const: true + metadata: + type: object + description: Metadata filters for the logs data source. + additionalProperties: true + example: | + { + "use_case": "customer_support_agent" + } + required: + - type + x-oaiMeta: + name: The logs data source object for evals + group: evals + example: | + { + "type": "logs", + "metadata": { + "use_case": "customer_support_agent" + } + } + CreateEvalRequest: + type: object + title: CreateEvalRequest + properties: + name: + type: string + description: The name of the evaluation. + metadata: + $ref: '#/components/schemas/Metadata' + data_source_config: + type: object + description: >- + The configuration for the data source used for the evaluation runs. + Dictates the schema of the data used in the evaluation. + oneOf: + - $ref: '#/components/schemas/CreateEvalCustomDataSourceConfig' + - $ref: '#/components/schemas/CreateEvalLogsDataSourceConfig' + - $ref: '#/components/schemas/CreateEvalStoredCompletionsDataSourceConfig' + testing_criteria: + type: array + description: >- + A list of graders for all eval runs in this group. Graders can + reference variables in the data source using double curly braces + notation, like `{{item.variable_name}}`. To reference the model's + output, use the `sample` namespace (ie, `{{sample.output_text}}`). + items: + oneOf: + - $ref: '#/components/schemas/CreateEvalLabelModelGrader' + - $ref: '#/components/schemas/EvalGraderStringCheck' + - $ref: '#/components/schemas/EvalGraderTextSimilarity' + - $ref: '#/components/schemas/EvalGraderPython' + - $ref: '#/components/schemas/EvalGraderScoreModel' + required: + - data_source_config + - testing_criteria + CreateEvalResponsesRunDataSource: + type: object + title: ResponsesRunDataSource + description: > + A ResponsesRunDataSource object describing a model sampling + configuration. + properties: + type: + type: string + enum: + - responses + default: responses + description: The type of run data source. Always `responses`. + input_messages: + description: >- + Used when sampling from a model. Dictates the structure of the + messages passed into the model. Can either be a reference to a + prebuilt trajectory (ie, `item.input_trajectory`), or a template + with variable references to the `item` namespace. + oneOf: + - type: object + title: InputMessagesTemplate + properties: + type: + type: string + enum: + - template + description: The type of input messages. Always `template`. + template: + type: array + description: >- + A list of chat messages forming the prompt or context. May + include variable references to the `item` namespace, ie + {{item.name}}. + items: + oneOf: + - type: object + title: ChatMessage + properties: + role: + type: string + description: >- + The role of the message (e.g. "system", + "assistant", "user"). + content: + type: string + description: The content of the message. + required: + - role + - content + - $ref: '#/components/schemas/EvalItem' + required: + - type + - template + - type: object + title: InputMessagesItemReference + properties: + type: + type: string + enum: + - item_reference + description: The type of input messages. Always `item_reference`. + item_reference: + type: string + description: >- + A reference to a variable in the `item` namespace. Ie, + "item.name" + required: + - type + - item_reference + sampling_params: + type: object + properties: + reasoning_effort: + $ref: '#/components/schemas/ReasoningEffort' + temperature: + type: number + description: A higher temperature increases randomness in the outputs. + default: 1 + max_completion_tokens: + type: integer + description: The maximum number of tokens in the generated output. + top_p: + type: number + description: >- + An alternative to temperature for nucleus sampling; 1.0 includes + all tokens. + default: 1 + seed: + type: integer + description: A seed value to initialize the randomness, during sampling. + default: 42 + tools: + type: array + description: > + An array of tools the model may call while generating a + response. You + + can specify which tool to use by setting the `tool_choice` + parameter. + + + The two categories of tools you can provide the model are: + + + - **Built-in tools**: Tools that are provided by OpenAI that + extend the + model's capabilities, like [web search](/docs/guides/tools-web-search) + or [file search](/docs/guides/tools-file-search). Learn more about + [built-in tools](/docs/guides/tools). + - **Function calls (custom tools)**: Functions that are defined + by you, + enabling the model to call your own code. Learn more about + [function calling](/docs/guides/function-calling). + items: + $ref: '#/components/schemas/Tool' + text: + type: object + description: > + Configuration options for a text response from the model. Can be + plain + + text or structured JSON data. Learn more: + + - [Text inputs and outputs](/docs/guides/text) + + - [Structured Outputs](/docs/guides/structured-outputs) + properties: + format: + $ref: '#/components/schemas/TextResponseFormatConfiguration' + model: + type: string + description: >- + The name of the model to use for generating completions (e.g. + "o3-mini"). + source: + description: >- + Determines what populates the `item` namespace in this run's data + source. + oneOf: + - $ref: '#/components/schemas/EvalJsonlFileContentSource' + - $ref: '#/components/schemas/EvalJsonlFileIdSource' + - $ref: '#/components/schemas/EvalResponsesSource' + required: + - type + - source + x-oaiMeta: + name: The completions data source object used to configure an individual run + group: eval runs + example: | + { + "name": "gpt-4o-mini-2024-07-18", + "data_source": { + "type": "responses", + "input_messages": { + "type": "item_reference", + "item_reference": "item.input" + }, + "model": "gpt-4o-mini-2024-07-18", + "source": { + "type": "responses", + "model": "gpt-4o-mini-2024-07-18" + } + } + } + CreateEvalRunRequest: + type: object + title: CreateEvalRunRequest + properties: + name: + type: string + description: The name of the run. + metadata: + $ref: '#/components/schemas/Metadata' + data_source: + type: object + description: Details about the run's data source. + oneOf: + - $ref: '#/components/schemas/CreateEvalJsonlRunDataSource' + - $ref: '#/components/schemas/CreateEvalCompletionsRunDataSource' + - $ref: '#/components/schemas/CreateEvalResponsesRunDataSource' + required: + - data_source + CreateEvalStoredCompletionsDataSourceConfig: + type: object + title: StoredCompletionsDataSourceConfig + description: | + Deprecated in favor of LogsDataSourceConfig. + properties: + type: + type: string + enum: + - stored_completions + default: stored_completions + description: The type of data source. Always `stored_completions`. + x-stainless-const: true + metadata: + type: object + description: Metadata filters for the stored completions data source. + additionalProperties: true + example: | + { + "use_case": "customer_support_agent" + } + required: + - type + deprecated: true + x-oaiMeta: + name: The stored completions data source object for evals + group: evals + example: | + { + "type": "stored_completions", + "metadata": { + "use_case": "customer_support_agent" + } + } + CreateFileRequest: + type: object + additionalProperties: false + properties: + file: + description: | + The File object (not file name) to be uploaded. + type: string + format: binary + purpose: + description: | + The intended purpose of the uploaded file. One of: + - `assistants`: Used in the Assistants API + - `batch`: Used in the Batch API + - `fine-tune`: Used for fine-tuning + - `vision`: Images used for vision fine-tuning + - `user_data`: Flexible file type for any purpose + - `evals`: Used for eval data sets + type: string + enum: + - assistants + - batch + - fine-tune + - vision + - user_data + - evals + expires_after: + $ref: '#/components/schemas/FileExpirationAfter' + required: + - file + - purpose + CreateFineTuningCheckpointPermissionRequest: + type: object + additionalProperties: false + properties: + project_ids: + type: array + description: The project identifiers to grant access to. + items: + type: string + required: + - project_ids + CreateFineTuningJobRequest: + type: object + properties: + model: + description: > + The name of the model to fine-tune. You can select one of the + + [supported + models](/docs/guides/fine-tuning#which-models-can-be-fine-tuned). + example: gpt-4o-mini + anyOf: + - type: string + - type: string + enum: + - babbage-002 + - davinci-002 + - gpt-3.5-turbo + - gpt-4o-mini + x-oaiTypeLabel: string + training_file: + description: > + The ID of an uploaded file that contains training data. + + + See [upload file](/docs/api-reference/files/create) for how to + upload a file. + + + Your dataset must be formatted as a JSONL file. Additionally, you + must upload your file with the purpose `fine-tune`. + + + The contents of the file should differ depending on if the model + uses the [chat](/docs/api-reference/fine-tuning/chat-input), + [completions](/docs/api-reference/fine-tuning/completions-input) + format, or if the fine-tuning method uses the + [preference](/docs/api-reference/fine-tuning/preference-input) + format. + + + See the [fine-tuning guide](/docs/guides/model-optimization) for + more details. + type: string + example: file-abc123 + hyperparameters: + type: object + description: > + The hyperparameters used for the fine-tuning job. + + This value is now deprecated in favor of `method`, and should be + passed in under the `method` parameter. + properties: + batch_size: + description: > + Number of examples in each batch. A larger batch size means that + model parameters + + are updated less frequently, but with lower variance. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 256 + default: auto + learning_rate_multiplier: + description: > + Scaling factor for the learning rate. A smaller learning rate + may be useful to avoid + + overfitting. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: number + minimum: 0 + exclusiveMinimum: 0 + default: auto + n_epochs: + description: > + The number of epochs to train the model for. An epoch refers to + one full cycle + + through the training dataset. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 50 + default: auto + deprecated: true + suffix: + description: > + A string of up to 64 characters that will be added to your + fine-tuned model name. + + + For example, a `suffix` of "custom-model-name" would produce a model + name like `ft:gpt-4o-mini:openai:custom-model-name:7p4lURel`. + type: string + minLength: 1 + maxLength: 64 + default: null + nullable: true + validation_file: + description: > + The ID of an uploaded file that contains validation data. + + + If you provide this file, the data is used to generate validation + + metrics periodically during fine-tuning. These metrics can be viewed + in + + the fine-tuning results file. + + The same data should not be present in both train and validation + files. + + + Your dataset must be formatted as a JSONL file. You must upload your + file with the purpose `fine-tune`. + + + See the [fine-tuning guide](/docs/guides/model-optimization) for + more details. + type: string + nullable: true + example: file-abc123 + integrations: + type: array + description: A list of integrations to enable for your fine-tuning job. + nullable: true + items: + type: object + required: + - type + - wandb + properties: + type: + description: > + The type of integration to enable. Currently, only "wandb" + (Weights and Biases) is supported. + oneOf: + - type: string + enum: + - wandb + x-stainless-const: true + wandb: + type: object + description: > + The settings for your integration with Weights and Biases. + This payload specifies the project that + + metrics will be sent to. Optionally, you can set an explicit + display name for your run, add tags + + to your run, and set a default entity (team, username, etc) to + be associated with your run. + required: + - project + properties: + project: + description: > + The name of the project that the new run will be created + under. + type: string + example: my-wandb-project + name: + description: > + A display name to set for the run. If not set, we will use + the Job ID as the name. + nullable: true + type: string + entity: + description: > + The entity to use for the run. This allows you to set the + team or username of the WandB user that you would + + like associated with the run. If not set, the default + entity for the registered WandB API key is used. + nullable: true + type: string + tags: + description: > + A list of tags to be attached to the newly created run. + These tags are passed through directly to WandB. Some + + default tags are generated by OpenAI: "openai/finetune", + "openai/{base-model}", "openai/{ftjob-abcdef}". + type: array + items: + type: string + example: custom-tag + seed: + description: > + The seed controls the reproducibility of the job. Passing in the + same seed and job parameters should produce the same results, but + may differ in rare cases. + + If a seed is not specified, one will be generated for you. + type: integer + nullable: true + minimum: 0 + maximum: 2147483647 + example: 42 + method: + $ref: '#/components/schemas/FineTuneMethod' + metadata: + $ref: '#/components/schemas/Metadata' + required: + - model + - training_file + CreateGroupBody: + type: object + description: Request payload for creating a new group in the organization. + properties: + name: + type: string + description: Human readable name for the group. + minLength: 1 + maxLength: 255 + required: + - name + x-oaiMeta: + example: | + { + "name": "Support Team" + } + CreateGroupUserBody: + type: object + description: Request payload for adding a user to a group. + properties: + user_id: + type: string + description: Identifier of the user to add to the group. + required: + - user_id + x-oaiMeta: + example: | + { + "user_id": "user_abc123" + } + CreateImageEditRequest: + type: object + properties: + image: + anyOf: + - type: string + format: binary + - type: array + maxItems: 16 + items: + type: string + format: binary + description: > + The image(s) to edit. Must be a supported image file or an array of + images. + + + For the GPT image models (`gpt-image-1`, `gpt-image-1-mini`, and + `gpt-image-1.5`), each image should be a `png`, `webp`, or `jpg` + + file less than 50MB. You can provide up to 16 images. + + `chatgpt-image-latest` follows the same input constraints as GPT + image models. + + + For `dall-e-2`, you can only provide one image, and it should be a + square + + `png` file less than 4MB. + prompt: + description: >- + A text description of the desired image(s). The maximum length is + 1000 characters for `dall-e-2`, and 32000 characters for the GPT + image models. + type: string + example: A cute baby sea otter wearing a beret + mask: + description: >- + An additional image whose fully transparent areas (e.g. where alpha + is zero) indicate where `image` should be edited. If there are + multiple images provided, the mask will be applied on the first + image. Must be a valid PNG file, less than 4MB, and have the same + dimensions as `image`. + type: string + format: binary + background: + type: string + enum: + - transparent + - opaque + - auto + default: auto + example: transparent + nullable: true + description: > + Allows to set transparency for the background of the generated + image(s). + + This parameter is only supported for the GPT image models. Must be + one of + + `transparent`, `opaque` or `auto` (default value). When `auto` is + used, the + + model will automatically determine the best background for the + image. + + + If `transparent`, the output format needs to support transparency, + so it + + should be set to either `png` (default value) or `webp`. + model: + anyOf: + - type: string + - type: string + enum: + - gpt-image-1.5 + - dall-e-2 + - gpt-image-1 + - gpt-image-1-mini + - chatgpt-image-latest + x-stainless-const: true + x-oaiTypeLabel: string + default: gpt-image-1.5 + example: gpt-image-1.5 + nullable: true + description: The model to use for image generation. Defaults to `gpt-image-1.5`. + 'n': + type: integer + minimum: 1 + maximum: 10 + default: 1 + example: 1 + nullable: true + description: The number of images to generate. Must be between 1 and 10. + size: + type: string + enum: + - 256x256 + - 512x512 + - 1024x1024 + - 1536x1024 + - 1024x1536 + - auto + default: 1024x1024 + example: 1024x1024 + nullable: true + description: >- + The size of the generated images. Must be one of `1024x1024`, + `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default + value) for the GPT image models, and one of `256x256`, `512x512`, or + `1024x1024` for `dall-e-2`. + response_format: + type: string + enum: + - url + - b64_json + example: url + nullable: true + description: >- + The format in which the generated images are returned. Must be one + of `url` or `b64_json`. URLs are only valid for 60 minutes after the + image has been generated. This parameter is only supported for + `dall-e-2` (default is `url` for `dall-e-2`), as GPT image models + always return base64-encoded images. + output_format: + type: string + enum: + - png + - jpeg + - webp + default: png + example: png + nullable: true + description: > + The format in which the generated images are returned. This + parameter is + + only supported for the GPT image models. Must be one of `png`, + `jpeg`, or `webp`. + + The default value is `png`. + output_compression: + type: integer + default: 100 + example: 100 + nullable: true + description: > + The compression level (0-100%) for the generated images. This + parameter + + is only supported for the GPT image models with the `webp` or `jpeg` + output + + formats, and defaults to 100. + user: + type: string + example: user-1234 + description: > + A unique identifier representing your end-user, which can help + OpenAI to monitor and detect abuse. [Learn + more](/docs/guides/safety-best-practices#end-user-ids). + input_fidelity: + anyOf: + - $ref: '#/components/schemas/InputFidelity' + - type: 'null' + stream: + type: boolean + default: false + example: false + nullable: true + description: > + Edit the image in streaming mode. Defaults to `false`. See the + + [Image generation guide](/docs/guides/image-generation) for more + information. + partial_images: + $ref: '#/components/schemas/PartialImages' + quality: + type: string + enum: + - standard + - low + - medium + - high + - auto + default: auto + example: high + nullable: true + description: > + The quality of the image that will be generated for GPT image + models. Defaults to `auto`. + required: + - prompt + - image + CreateImageRequest: + type: object + properties: + prompt: + description: >- + A text description of the desired image(s). The maximum length is + 32000 characters for the GPT image models, 1000 characters for + `dall-e-2` and 4000 characters for `dall-e-3`. + type: string + example: A cute baby sea otter + model: + anyOf: + - type: string + - type: string + enum: + - gpt-image-1.5 + - dall-e-2 + - dall-e-3 + - gpt-image-1 + - gpt-image-1-mini + x-oaiTypeLabel: string + default: dall-e-2 + example: gpt-image-1.5 + nullable: true + description: >- + The model to use for image generation. One of `dall-e-2`, + `dall-e-3`, or a GPT image model (`gpt-image-1`, `gpt-image-1-mini`, + `gpt-image-1.5`). Defaults to `dall-e-2` unless a parameter specific + to the GPT image models is used. + 'n': + type: integer + minimum: 1 + maximum: 10 + default: 1 + example: 1 + nullable: true + description: >- + The number of images to generate. Must be between 1 and 10. For + `dall-e-3`, only `n=1` is supported. + quality: + type: string + enum: + - standard + - hd + - low + - medium + - high + - auto + default: auto + example: medium + nullable: true + description: > + The quality of the image that will be generated. + + + - `auto` (default value) will automatically select the best quality + for the given model. + + - `high`, `medium` and `low` are supported for the GPT image models. + + - `hd` and `standard` are supported for `dall-e-3`. + + - `standard` is the only option for `dall-e-2`. + response_format: + type: string + enum: + - url + - b64_json + default: url + example: url + nullable: true + description: >- + The format in which generated images with `dall-e-2` and `dall-e-3` + are returned. Must be one of `url` or `b64_json`. URLs are only + valid for 60 minutes after the image has been generated. This + parameter isn't supported for the GPT image models, which always + return base64-encoded images. + output_format: + type: string + enum: + - png + - jpeg + - webp + default: png + example: png + nullable: true + description: >- + The format in which the generated images are returned. This + parameter is only supported for the GPT image models. Must be one of + `png`, `jpeg`, or `webp`. + output_compression: + type: integer + default: 100 + example: 100 + nullable: true + description: >- + The compression level (0-100%) for the generated images. This + parameter is only supported for the GPT image models with the `webp` + or `jpeg` output formats, and defaults to 100. + stream: + type: boolean + default: false + example: false + nullable: true + description: > + Generate the image in streaming mode. Defaults to `false`. See the + + [Image generation guide](/docs/guides/image-generation) for more + information. + + This parameter is only supported for the GPT image models. + partial_images: + $ref: '#/components/schemas/PartialImages' + size: + type: string + enum: + - auto + - 1024x1024 + - 1536x1024 + - 1024x1536 + - 256x256 + - 512x512 + - 1792x1024 + - 1024x1792 + default: auto + example: 1024x1024 + nullable: true + description: >- + The size of the generated images. Must be one of `1024x1024`, + `1536x1024` (landscape), `1024x1536` (portrait), or `auto` (default + value) for the GPT image models, one of `256x256`, `512x512`, or + `1024x1024` for `dall-e-2`, and one of `1024x1024`, `1792x1024`, or + `1024x1792` for `dall-e-3`. + moderation: + type: string + enum: + - low + - auto + default: auto + example: low + nullable: true + description: >- + Control the content-moderation level for images generated by the GPT + image models. Must be either `low` for less restrictive filtering or + `auto` (default value). + background: + type: string + enum: + - transparent + - opaque + - auto + default: auto + example: transparent + nullable: true + description: > + Allows to set transparency for the background of the generated + image(s). + + This parameter is only supported for the GPT image models. Must be + one of + + `transparent`, `opaque` or `auto` (default value). When `auto` is + used, the + + model will automatically determine the best background for the + image. + + + If `transparent`, the output format needs to support transparency, + so it + + should be set to either `png` (default value) or `webp`. + style: + type: string + enum: + - vivid + - natural + default: vivid + example: vivid + nullable: true + description: >- + The style of the generated images. This parameter is only supported + for `dall-e-3`. Must be one of `vivid` or `natural`. Vivid causes + the model to lean towards generating hyper-real and dramatic images. + Natural causes the model to produce more natural, less hyper-real + looking images. + user: + type: string + example: user-1234 + description: > + A unique identifier representing your end-user, which can help + OpenAI to monitor and detect abuse. [Learn + more](/docs/guides/safety-best-practices#end-user-ids). + required: + - prompt + CreateImageVariationRequest: + type: object + properties: + image: + description: >- + The image to use as the basis for the variation(s). Must be a valid + PNG file, less than 4MB, and square. + type: string + format: binary + model: + anyOf: + - type: string + - type: string + enum: + - dall-e-2 + x-stainless-const: true + x-oaiTypeLabel: string + default: dall-e-2 + example: dall-e-2 + nullable: true + description: >- + The model to use for image generation. Only `dall-e-2` is supported + at this time. + 'n': + type: integer + minimum: 1 + maximum: 10 + default: 1 + example: 1 + nullable: true + description: The number of images to generate. Must be between 1 and 10. + response_format: + type: string + enum: + - url + - b64_json + default: url + example: url + nullable: true + description: >- + The format in which the generated images are returned. Must be one + of `url` or `b64_json`. URLs are only valid for 60 minutes after the + image has been generated. + size: + type: string + enum: + - 256x256 + - 512x512 + - 1024x1024 + default: 1024x1024 + example: 1024x1024 + nullable: true + description: >- + The size of the generated images. Must be one of `256x256`, + `512x512`, or `1024x1024`. + user: + type: string + example: user-1234 + description: > + A unique identifier representing your end-user, which can help + OpenAI to monitor and detect abuse. [Learn + more](/docs/guides/safety-best-practices#end-user-ids). + required: + - image + CreateMessageRequest: + type: object + additionalProperties: false + required: + - role + - content + properties: + role: + type: string + enum: + - user + - assistant + description: > + The role of the entity that is creating the message. Allowed values + include: + + - `user`: Indicates the message is sent by an actual user and should + be used in most cases to represent user-generated messages. + + - `assistant`: Indicates the message is generated by the assistant. + Use this value to insert messages from the assistant into the + conversation. + content: + oneOf: + - type: string + description: The text contents of the message. + title: Text content + - type: array + description: >- + An array of content parts with a defined type, each can be of + type `text` or images can be passed with `image_url` or + `image_file`. Image types are only supported on + [Vision-compatible models](/docs/models). + title: Array of content parts + items: + oneOf: + - $ref: '#/components/schemas/MessageContentImageFileObject' + - $ref: '#/components/schemas/MessageContentImageUrlObject' + - $ref: '#/components/schemas/MessageRequestContentTextObject' + minItems: 1 + attachments: + anyOf: + - type: array + items: + type: object + properties: + file_id: + type: string + description: The ID of the file to attach to the message. + tools: + description: The tools to add this file to. + type: array + items: + oneOf: + - $ref: '#/components/schemas/AssistantToolsCode' + - $ref: >- + #/components/schemas/AssistantToolsFileSearchTypeOnly + description: >- + A list of files attached to the message, and the tools they + should be added to. + required: + - file_id + - tools + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + CreateModelResponseProperties: + allOf: + - $ref: '#/components/schemas/ModelResponseProperties' + - type: object + properties: + top_logprobs: + description: > + An integer between 0 and 20 specifying the number of most likely + tokens to + + return at each token position, each with an associated log + probability. + type: integer + minimum: 0 + maximum: 20 + CreateModerationRequest: + type: object + properties: + input: + description: > + Input (or inputs) to classify. Can be a single string, an array of + strings, or + + an array of multi-modal input objects similar to other models. + oneOf: + - type: string + description: A string of text to classify for moderation. + default: '' + example: I want to kill them. + - type: array + description: An array of strings to classify for moderation. + items: + type: string + default: '' + example: I want to kill them. + - type: array + description: An array of multi-modal inputs to the moderation model. + items: + oneOf: + - type: object + description: An object describing an image to classify. + properties: + type: + description: Always `image_url`. + type: string + enum: + - image_url + x-stainless-const: true + image_url: + type: object + description: >- + Contains either an image URL or a data URL for a + base64 encoded image. + properties: + url: + type: string + description: >- + Either a URL of the image or the base64 encoded + image data. + format: uri + example: https://example.com/image.jpg + required: + - url + required: + - type + - image_url + - type: object + description: An object describing text to classify. + properties: + type: + description: Always `text`. + type: string + enum: + - text + x-stainless-const: true + text: + description: A string of text to classify. + type: string + example: I want to kill them + required: + - type + - text + model: + description: | + The content moderation model you would like to use. Learn more in + [the moderation guide](/docs/guides/moderation), and learn about + available models [here](/docs/models#moderation). + nullable: false + default: omni-moderation-latest + example: omni-moderation-2024-09-26 + anyOf: + - type: string + - type: string + enum: + - omni-moderation-latest + - omni-moderation-2024-09-26 + - text-moderation-latest + - text-moderation-stable + x-oaiTypeLabel: string + required: + - input + CreateModerationResponse: + type: object + description: Represents if a given text input is potentially harmful. + properties: + id: + type: string + description: The unique identifier for the moderation request. + model: + type: string + description: The model used to generate the moderation results. + results: + type: array + description: A list of moderation objects. + items: + type: object + properties: + flagged: + type: boolean + description: Whether any of the below categories are flagged. + categories: + type: object + description: A list of the categories, and whether they are flagged or not. + properties: + hate: + type: boolean + description: >- + Content that expresses, incites, or promotes hate based on + race, gender, ethnicity, religion, nationality, sexual + orientation, disability status, or caste. Hateful content + aimed at non-protected groups (e.g., chess players) is + harassment. + hate/threatening: + type: boolean + description: >- + Hateful content that also includes violence or serious + harm towards the targeted group based on race, gender, + ethnicity, religion, nationality, sexual orientation, + disability status, or caste. + harassment: + type: boolean + description: >- + Content that expresses, incites, or promotes harassing + language towards any target. + harassment/threatening: + type: boolean + description: >- + Harassment content that also includes violence or serious + harm towards any target. + illicit: + anyOf: + - type: boolean + description: >- + Content that includes instructions or advice that + facilitate the planning or execution of wrongdoing, or + that gives advice or instruction on how to commit + illicit acts. For example, "how to shoplift" would fit + this category. + - type: 'null' + illicit/violent: + anyOf: + - type: boolean + description: >- + Content that includes instructions or advice that + facilitate the planning or execution of wrongdoing + that also includes violence, or that gives advice or + instruction on the procurement of any weapon. + - type: 'null' + self-harm: + type: boolean + description: >- + Content that promotes, encourages, or depicts acts of + self-harm, such as suicide, cutting, and eating disorders. + self-harm/intent: + type: boolean + description: >- + Content where the speaker expresses that they are engaging + or intend to engage in acts of self-harm, such as suicide, + cutting, and eating disorders. + self-harm/instructions: + type: boolean + description: >- + Content that encourages performing acts of self-harm, such + as suicide, cutting, and eating disorders, or that gives + instructions or advice on how to commit such acts. + sexual: + type: boolean + description: >- + Content meant to arouse sexual excitement, such as the + description of sexual activity, or that promotes sexual + services (excluding sex education and wellness). + sexual/minors: + type: boolean + description: >- + Sexual content that includes an individual who is under 18 + years old. + violence: + type: boolean + description: Content that depicts death, violence, or physical injury. + violence/graphic: + type: boolean + description: >- + Content that depicts death, violence, or physical injury + in graphic detail. + required: + - hate + - hate/threatening + - harassment + - harassment/threatening + - illicit + - illicit/violent + - self-harm + - self-harm/intent + - self-harm/instructions + - sexual + - sexual/minors + - violence + - violence/graphic + category_scores: + type: object + description: >- + A list of the categories along with their scores as predicted + by model. + properties: + hate: + type: number + description: The score for the category 'hate'. + hate/threatening: + type: number + description: The score for the category 'hate/threatening'. + harassment: + type: number + description: The score for the category 'harassment'. + harassment/threatening: + type: number + description: The score for the category 'harassment/threatening'. + illicit: + type: number + description: The score for the category 'illicit'. + illicit/violent: + type: number + description: The score for the category 'illicit/violent'. + self-harm: + type: number + description: The score for the category 'self-harm'. + self-harm/intent: + type: number + description: The score for the category 'self-harm/intent'. + self-harm/instructions: + type: number + description: The score for the category 'self-harm/instructions'. + sexual: + type: number + description: The score for the category 'sexual'. + sexual/minors: + type: number + description: The score for the category 'sexual/minors'. + violence: + type: number + description: The score for the category 'violence'. + violence/graphic: + type: number + description: The score for the category 'violence/graphic'. + required: + - hate + - hate/threatening + - harassment + - harassment/threatening + - illicit + - illicit/violent + - self-harm + - self-harm/intent + - self-harm/instructions + - sexual + - sexual/minors + - violence + - violence/graphic + category_applied_input_types: + type: object + description: >- + A list of the categories along with the input type(s) that the + score applies to. + properties: + hate: + type: array + description: The applied input type(s) for the category 'hate'. + items: + type: string + enum: + - text + x-stainless-const: true + hate/threatening: + type: array + description: >- + The applied input type(s) for the category + 'hate/threatening'. + items: + type: string + enum: + - text + x-stainless-const: true + harassment: + type: array + description: The applied input type(s) for the category 'harassment'. + items: + type: string + enum: + - text + x-stainless-const: true + harassment/threatening: + type: array + description: >- + The applied input type(s) for the category + 'harassment/threatening'. + items: + type: string + enum: + - text + x-stainless-const: true + illicit: + type: array + description: The applied input type(s) for the category 'illicit'. + items: + type: string + enum: + - text + x-stainless-const: true + illicit/violent: + type: array + description: >- + The applied input type(s) for the category + 'illicit/violent'. + items: + type: string + enum: + - text + x-stainless-const: true + self-harm: + type: array + description: The applied input type(s) for the category 'self-harm'. + items: + type: string + enum: + - text + - image + self-harm/intent: + type: array + description: >- + The applied input type(s) for the category + 'self-harm/intent'. + items: + type: string + enum: + - text + - image + self-harm/instructions: + type: array + description: >- + The applied input type(s) for the category + 'self-harm/instructions'. + items: + type: string + enum: + - text + - image + sexual: + type: array + description: The applied input type(s) for the category 'sexual'. + items: + type: string + enum: + - text + - image + sexual/minors: + type: array + description: >- + The applied input type(s) for the category + 'sexual/minors'. + items: + type: string + enum: + - text + x-stainless-const: true + violence: + type: array + description: The applied input type(s) for the category 'violence'. + items: + type: string + enum: + - text + - image + violence/graphic: + type: array + description: >- + The applied input type(s) for the category + 'violence/graphic'. + items: + type: string + enum: + - text + - image + required: + - hate + - hate/threatening + - harassment + - harassment/threatening + - illicit + - illicit/violent + - self-harm + - self-harm/intent + - self-harm/instructions + - sexual + - sexual/minors + - violence + - violence/graphic + required: + - flagged + - categories + - category_scores + - category_applied_input_types + required: + - id + - model + - results + x-oaiMeta: + name: The moderation object + example: | + { + "id": "modr-0d9740456c391e43c445bf0f010940c7", + "model": "omni-moderation-latest", + "results": [ + { + "flagged": true, + "categories": { + "harassment": true, + "harassment/threatening": true, + "sexual": false, + "hate": false, + "hate/threatening": false, + "illicit": false, + "illicit/violent": false, + "self-harm/intent": false, + "self-harm/instructions": false, + "self-harm": false, + "sexual/minors": false, + "violence": true, + "violence/graphic": true + }, + "category_scores": { + "harassment": 0.8189693396524255, + "harassment/threatening": 0.804985420696006, + "sexual": 1.573112165348997e-6, + "hate": 0.007562942636942845, + "hate/threatening": 0.004208854591835476, + "illicit": 0.030535955153511665, + "illicit/violent": 0.008925306722380033, + "self-harm/intent": 0.00023023930975076432, + "self-harm/instructions": 0.0002293869201073356, + "self-harm": 0.012598046106750154, + "sexual/minors": 2.212566909570261e-8, + "violence": 0.9999992735124786, + "violence/graphic": 0.843064871157054 + }, + "category_applied_input_types": { + "harassment": [ + "text" + ], + "harassment/threatening": [ + "text" + ], + "sexual": [ + "text", + "image" + ], + "hate": [ + "text" + ], + "hate/threatening": [ + "text" + ], + "illicit": [ + "text" + ], + "illicit/violent": [ + "text" + ], + "self-harm/intent": [ + "text", + "image" + ], + "self-harm/instructions": [ + "text", + "image" + ], + "self-harm": [ + "text", + "image" + ], + "sexual/minors": [ + "text" + ], + "violence": [ + "text", + "image" + ], + "violence/graphic": [ + "text", + "image" + ] + } + } + ] + } + CreateResponse: + allOf: + - $ref: '#/components/schemas/CreateModelResponseProperties' + - $ref: '#/components/schemas/ResponseProperties' + - type: object + properties: + input: + $ref: '#/components/schemas/InputParam' + include: + anyOf: + - type: array + description: >- + 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). + items: + $ref: '#/components/schemas/IncludeEnum' + - type: 'null' + parallel_tool_calls: + anyOf: + - type: boolean + description: | + Whether to allow the model to run tool calls in parallel. + default: true + - type: 'null' + store: + anyOf: + - type: boolean + description: > + Whether to store the generated model response for later + retrieval via + + API. + default: true + - type: 'null' + instructions: + anyOf: + - type: string + description: > + 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. + - type: 'null' + stream: + anyOf: + - description: > + 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. + type: boolean + default: false + - type: 'null' + stream_options: + $ref: '#/components/schemas/ResponseStreamOptions' + conversation: + anyOf: + - $ref: '#/components/schemas/ConversationParam' + - type: 'null' + context_management: + anyOf: + - type: array + description: | + Context management configuration for this request. + minItems: 1 + items: + $ref: '#/components/schemas/ContextManagementParam' + - type: 'null' + max_output_tokens: + anyOf: + - description: > + An upper bound for the number of tokens that can be + generated for a response, including visible output tokens + and [reasoning tokens](/docs/guides/reasoning). + type: integer + minimum: 16 + - type: 'null' + CreateRunRequest: + type: object + additionalProperties: false + properties: + assistant_id: + description: >- + The ID of the [assistant](/docs/api-reference/assistants) to use to + execute this run. + type: string + model: + description: >- + The ID of the [Model](/docs/api-reference/models) to be used to + execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated + with the assistant will be used. + example: gpt-4o + anyOf: + - type: string + - $ref: '#/components/schemas/AssistantSupportedModels' + x-oaiTypeLabel: string + nullable: true + reasoning_effort: + $ref: '#/components/schemas/ReasoningEffort' + instructions: + description: >- + Overrides the + [instructions](/docs/api-reference/assistants/createAssistant) of + the assistant. This is useful for modifying the behavior on a + per-run basis. + type: string + nullable: true + additional_instructions: + description: >- + Appends additional instructions at the end of the instructions for + the run. This is useful for modifying the behavior on a per-run + basis without overriding other instructions. + type: string + nullable: true + additional_messages: + description: Adds additional messages to the thread before creating the run. + type: array + items: + $ref: '#/components/schemas/CreateMessageRequest' + nullable: true + tools: + description: >- + Override the tools the assistant can use for this run. This is + useful for modifying the behavior on a per-run basis. + nullable: true + type: array + maxItems: 20 + items: + oneOf: + - $ref: '#/components/schemas/AssistantToolsCode' + - $ref: '#/components/schemas/AssistantToolsFileSearch' + - $ref: '#/components/schemas/AssistantToolsFunction' + metadata: + $ref: '#/components/schemas/Metadata' + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: > + What sampling temperature to use, between 0 and 2. Higher values + like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: > + An alternative to sampling with temperature, called nucleus + sampling, where the model considers the results of the tokens with + top_p probability mass. So 0.1 means only the tokens comprising the + top 10% probability mass are considered. + + + We generally recommend altering this or temperature but not both. + stream: + type: boolean + nullable: true + description: > + If `true`, returns a stream of events that happen during the Run as + server-sent events, terminating when the Run enters a terminal state + with a `data: [DONE]` message. + max_prompt_tokens: + type: integer + nullable: true + description: > + The maximum number of prompt tokens that may be used over the course + of the run. The run will make a best effort to use only the number + of prompt tokens specified, across multiple turns of the run. If the + run exceeds the number of prompt tokens specified, the run will end + with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: > + The maximum number of completion tokens that may be used over the + course of the run. The run will make a best effort to use only the + number of completion tokens specified, across multiple turns of the + run. If the run exceeds the number of completion tokens specified, + the run will end with status `incomplete`. See `incomplete_details` + for more info. + minimum: 256 + truncation_strategy: + allOf: + - $ref: '#/components/schemas/TruncationObject' + - nullable: true + tool_choice: + allOf: + - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' + - nullable: true + parallel_tool_calls: + $ref: '#/components/schemas/ParallelToolCalls' + response_format: + $ref: '#/components/schemas/AssistantsApiResponseFormatOption' + nullable: true + required: + - assistant_id + CreateSpeechRequest: + type: object + additionalProperties: false + properties: + model: + description: > + One of the available [TTS models](/docs/models#tts): `tts-1`, + `tts-1-hd`, `gpt-4o-mini-tts`, or `gpt-4o-mini-tts-2025-12-15`. + anyOf: + - type: string + - type: string + enum: + - tts-1 + - tts-1-hd + - gpt-4o-mini-tts + - gpt-4o-mini-tts-2025-12-15 + x-oaiTypeLabel: string + input: + type: string + description: >- + The text to generate audio for. The maximum length is 4096 + characters. + maxLength: 4096 + instructions: + type: string + description: >- + Control the voice of your generated audio with additional + instructions. Does not work with `tts-1` or `tts-1-hd`. + maxLength: 4096 + voice: + description: >- + The voice to use when generating the audio. Supported built-in + voices are `alloy`, `ash`, `ballad`, `coral`, `echo`, `fable`, + `onyx`, `nova`, `sage`, `shimmer`, `verse`, `marin`, and `cedar`. + You may also provide a custom voice object with an `id`, for example + `{ "id": "voice_1234" }`. Previews of the voices are available in + the [Text to speech + guide](/docs/guides/text-to-speech#voice-options). + $ref: '#/components/schemas/VoiceIdsOrCustomVoice' + response_format: + description: >- + The format to audio in. Supported formats are `mp3`, `opus`, `aac`, + `flac`, `wav`, and `pcm`. + default: mp3 + type: string + enum: + - mp3 + - opus + - aac + - flac + - wav + - pcm + speed: + description: >- + The speed of the generated audio. Select a value from `0.25` to + `4.0`. `1.0` is the default. + type: number + default: 1 + minimum: 0.25 + maximum: 4 + stream_format: + description: >- + The format to stream the audio in. Supported formats are `sse` and + `audio`. `sse` is not supported for `tts-1` or `tts-1-hd`. + type: string + default: audio + enum: + - sse + - audio + required: + - model + - input + - voice + CreateSpeechResponseStreamEvent: + anyOf: + - $ref: '#/components/schemas/SpeechAudioDeltaEvent' + - $ref: '#/components/schemas/SpeechAudioDoneEvent' + discriminator: + propertyName: type + CreateThreadAndRunRequest: + type: object + additionalProperties: false + properties: + assistant_id: + description: >- + The ID of the [assistant](/docs/api-reference/assistants) to use to + execute this run. + type: string + thread: + $ref: '#/components/schemas/CreateThreadRequest' + model: + description: >- + The ID of the [Model](/docs/api-reference/models) to be used to + execute this run. If a value is provided here, it will override the + model associated with the assistant. If not, the model associated + with the assistant will be used. + example: gpt-4o + anyOf: + - type: string + - type: string + enum: + - gpt-5 + - gpt-5-mini + - gpt-5-nano + - gpt-5-2025-08-07 + - gpt-5-mini-2025-08-07 + - gpt-5-nano-2025-08-07 + - gpt-4.1 + - gpt-4.1-mini + - gpt-4.1-nano + - gpt-4.1-2025-04-14 + - gpt-4.1-mini-2025-04-14 + - gpt-4.1-nano-2025-04-14 + - gpt-4o + - gpt-4o-2024-11-20 + - gpt-4o-2024-08-06 + - gpt-4o-2024-05-13 + - gpt-4o-mini + - gpt-4o-mini-2024-07-18 + - gpt-4.5-preview + - gpt-4.5-preview-2025-02-27 + - gpt-4-turbo + - gpt-4-turbo-2024-04-09 + - gpt-4-0125-preview + - gpt-4-turbo-preview + - gpt-4-1106-preview + - gpt-4-vision-preview + - gpt-4 + - gpt-4-0314 + - gpt-4-0613 + - gpt-4-32k + - gpt-4-32k-0314 + - gpt-4-32k-0613 + - gpt-3.5-turbo + - gpt-3.5-turbo-16k + - gpt-3.5-turbo-0613 + - gpt-3.5-turbo-1106 + - gpt-3.5-turbo-0125 + - gpt-3.5-turbo-16k-0613 + x-oaiTypeLabel: string + nullable: true + instructions: + description: >- + Override the default system message of the assistant. This is useful + for modifying the behavior on a per-run basis. + type: string + nullable: true + tools: + description: >- + Override the tools the assistant can use for this run. This is + useful for modifying the behavior on a per-run basis. + nullable: true + type: array + maxItems: 20 + items: + oneOf: + - $ref: '#/components/schemas/AssistantToolsCode' + - $ref: '#/components/schemas/AssistantToolsFileSearch' + - $ref: '#/components/schemas/AssistantToolsFunction' + tool_resources: + type: object + description: > + A set of resources that are used by the assistant's tools. The + resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the + `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: > + A list of [file](/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a + maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: > + The ID of the [vector + store](/docs/api-reference/vector-stores/object) attached to + this assistant. There can be a maximum of 1 vector store + attached to the assistant. + maxItems: 1 + items: + type: string + nullable: true + metadata: + $ref: '#/components/schemas/Metadata' + temperature: + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + nullable: true + description: > + What sampling temperature to use, between 0 and 2. Higher values + like 0.8 will make the output more random, while lower values like + 0.2 will make it more focused and deterministic. + top_p: + type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + nullable: true + description: > + An alternative to sampling with temperature, called nucleus + sampling, where the model considers the results of the tokens with + top_p probability mass. So 0.1 means only the tokens comprising the + top 10% probability mass are considered. + + + We generally recommend altering this or temperature but not both. + stream: + type: boolean + nullable: true + description: > + If `true`, returns a stream of events that happen during the Run as + server-sent events, terminating when the Run enters a terminal state + with a `data: [DONE]` message. + max_prompt_tokens: + type: integer + nullable: true + description: > + The maximum number of prompt tokens that may be used over the course + of the run. The run will make a best effort to use only the number + of prompt tokens specified, across multiple turns of the run. If the + run exceeds the number of prompt tokens specified, the run will end + with status `incomplete`. See `incomplete_details` for more info. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: > + The maximum number of completion tokens that may be used over the + course of the run. The run will make a best effort to use only the + number of completion tokens specified, across multiple turns of the + run. If the run exceeds the number of completion tokens specified, + the run will end with status `incomplete`. See `incomplete_details` + for more info. + minimum: 256 + truncation_strategy: + allOf: + - $ref: '#/components/schemas/TruncationObject' + - nullable: true + tool_choice: + allOf: + - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' + - nullable: true + parallel_tool_calls: + $ref: '#/components/schemas/ParallelToolCalls' + response_format: + $ref: '#/components/schemas/AssistantsApiResponseFormatOption' + nullable: true + required: + - assistant_id + CreateThreadRequest: + type: object + description: | + Options to create a new thread. If no thread is provided when running a + request, an empty thread will be created. + additionalProperties: false + properties: + messages: + description: >- + A list of [messages](/docs/api-reference/messages) to start the + thread with. + type: array + items: + $ref: '#/components/schemas/CreateMessageRequest' + tool_resources: + anyOf: + - type: object + description: > + A set of resources that are made available to the assistant's + tools in this thread. The resources are specific to the type of + tool. For example, the `code_interpreter` tool requires a list + of file IDs, while the `file_search` tool requires a list of + vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: > + A list of [file](/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a + maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: > + The [vector + store](/docs/api-reference/vector-stores/object) + attached to this thread. There can be a maximum of 1 + vector store attached to the thread. + maxItems: 1 + items: + type: string + vector_stores: + type: array + description: > + A helper to create a [vector + store](/docs/api-reference/vector-stores/object) with + file_ids and attach it to this thread. There can be a + maximum of 1 vector store attached to the thread. + maxItems: 1 + items: + type: object + properties: + file_ids: + type: array + description: > + A list of [file](/docs/api-reference/files) IDs to + add to the vector store. For vector stores created + before Nov 2025, there can be a maximum of 10,000 + files in a vector store. For vector stores created + starting in Nov 2025, the limit is 100,000,000 + files. + maxItems: 100000000 + items: + type: string + chunking_strategy: + type: object + description: >- + The chunking strategy used to chunk the file(s). + If not set, will use the `auto` strategy. + oneOf: + - type: object + title: Auto Chunking Strategy + description: >- + The default strategy. This strategy currently + uses a `max_chunk_size_tokens` of `800` and + `chunk_overlap_tokens` of `400`. + additionalProperties: false + properties: + type: + type: string + description: Always `auto`. + enum: + - auto + x-stainless-const: true + required: + - type + - type: object + title: Static Chunking Strategy + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: + - static + x-stainless-const: true + static: + type: object + additionalProperties: false + properties: + max_chunk_size_tokens: + type: integer + minimum: 100 + maximum: 4096 + description: >- + The maximum number of tokens in each + chunk. The default value is `800`. The + minimum value is `100` and the maximum + value is `4096`. + chunk_overlap_tokens: + type: integer + description: > + The number of tokens that overlap + between chunks. The default value is + `400`. + + + Note that the overlap must not exceed + half of `max_chunk_size_tokens`. + required: + - max_chunk_size_tokens + - chunk_overlap_tokens + required: + - type + - static + metadata: + $ref: '#/components/schemas/Metadata' + oneOf: + - required: + - vector_store_ids + - required: + - vector_stores + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + CreateTranscriptionRequest: + type: object + additionalProperties: false + properties: + file: + description: > + The audio file object (not file name) to transcribe, in one of these + formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + type: string + x-oaiTypeLabel: file + format: binary + model: + description: > + ID of the model to use. The options are `gpt-4o-transcribe`, + `gpt-4o-mini-transcribe`, `gpt-4o-mini-transcribe-2025-12-15`, + `whisper-1` (which is powered by our open source Whisper V2 model), + and `gpt-4o-transcribe-diarize`. + example: gpt-4o-transcribe + anyOf: + - type: string + - type: string + enum: + - whisper-1 + - gpt-4o-transcribe + - gpt-4o-mini-transcribe + - gpt-4o-mini-transcribe-2025-12-15 + - gpt-4o-transcribe-diarize + x-stainless-const: true + x-oaiTypeLabel: string + language: + description: > + The language of the input audio. Supplying the input language in + [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) + (e.g. `en`) format will improve accuracy and latency. + type: string + prompt: + description: > + An optional text to guide the model's style or continue a previous + audio segment. The [prompt](/docs/guides/speech-to-text#prompting) + should match the audio language. This field is not supported when + using `gpt-4o-transcribe-diarize`. + type: string + response_format: + $ref: '#/components/schemas/AudioResponseFormat' + temperature: + description: > + The sampling temperature, between 0 and 1. Higher values like 0.8 + will make the output more random, while lower values like 0.2 will + make it more focused and deterministic. If set to 0, the model will + use [log probability](https://en.wikipedia.org/wiki/Log_probability) + to automatically increase the temperature until certain thresholds + are hit. + type: number + default: 0 + include: + description: > + Additional information to include in the transcription response. + + `logprobs` will return the log probabilities of the tokens in the + + response to understand the model's confidence in the transcription. + + `logprobs` only works with response_format set to `json` and only + with + + the models `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and + `gpt-4o-mini-transcribe-2025-12-15`. This field is not supported + when using `gpt-4o-transcribe-diarize`. + type: array + items: + $ref: '#/components/schemas/TranscriptionInclude' + timestamp_granularities: + description: > + The timestamp granularities to populate for this transcription. + `response_format` must be set `verbose_json` to use timestamp + granularities. Either or both of these options are supported: + `word`, or `segment`. Note: There is no additional latency for + segment timestamps, but generating word timestamps incurs additional + latency. + + This option is not available for `gpt-4o-transcribe-diarize`. + type: array + items: + type: string + enum: + - word + - segment + default: + - segment + stream: + anyOf: + - description: > + 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 of the Speech-to-Text + guide](/docs/guides/speech-to-text?lang=curl#streaming-transcriptions) + + for more information. + + + Note: Streaming is not supported for the `whisper-1` model and + will be ignored. + type: boolean + default: false + - type: 'null' + chunking_strategy: + anyOf: + - description: >- + Controls how the audio is cut into chunks. When set to `"auto"`, + the server first normalizes loudness and then uses voice + activity detection (VAD) to choose boundaries. `server_vad` + object can be provided to tweak VAD detection parameters + manually. If unset, the audio is transcribed as a single block. + Required when using `gpt-4o-transcribe-diarize` for inputs + longer than 30 seconds. + anyOf: + - type: string + enum: + - auto + default: auto + description: > + Automatically set chunking parameters based on the audio. + Must be set to `"auto"`. + x-stainless-const: true + - $ref: '#/components/schemas/VadConfig' + x-oaiTypeLabel: string + - type: 'null' + known_speaker_names: + description: > + Optional list of speaker names that correspond to the audio samples + provided in `known_speaker_references[]`. Each entry should be a + short identifier (for example `customer` or `agent`). Up to 4 + speakers are supported. + type: array + maxItems: 4 + items: + type: string + known_speaker_references: + description: > + Optional list of audio samples (as [data + URLs](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Data_URLs)) + that contain known speaker references matching + `known_speaker_names[]`. Each sample must be between 2 and 10 + seconds, and can use any of the same input audio formats supported + by `file`. + type: array + maxItems: 4 + items: + type: string + required: + - file + - model + CreateTranscriptionResponseDiarizedJson: + type: object + description: > + Represents a diarized transcription response returned by the model, + including the combined transcript and speaker-segment annotations. + properties: + task: + type: string + description: The type of task that was run. Always `transcribe`. + enum: + - transcribe + x-stainless-const: true + duration: + type: number + description: Duration of the input audio in seconds. + text: + type: string + description: The concatenated transcript text for the entire audio input. + segments: + type: array + description: >- + Segments of the transcript annotated with timestamps and speaker + labels. + items: + $ref: '#/components/schemas/TranscriptionDiarizedSegment' + usage: + type: object + description: Token or duration usage statistics for the request. + oneOf: + - $ref: '#/components/schemas/TranscriptTextUsageTokens' + title: Token Usage + - $ref: '#/components/schemas/TranscriptTextUsageDuration' + title: Duration Usage + discriminator: + propertyName: type + required: + - task + - duration + - text + - segments + x-oaiMeta: + name: The transcription object (Diarized JSON) + group: audio + example: | + { + "task": "transcribe", + "duration": 42.7, + "text": "Agent: Thanks for calling OpenAI support.\nCustomer: Hi, I need help with diarization.", + "segments": [ + { + "type": "transcript.text.segment", + "id": "seg_001", + "start": 0.0, + "end": 5.2, + "text": "Thanks for calling OpenAI support.", + "speaker": "agent" + }, + { + "type": "transcript.text.segment", + "id": "seg_002", + "start": 5.2, + "end": 12.8, + "text": "Hi, I need help with diarization.", + "speaker": "A" + } + ], + "usage": { + "type": "duration", + "seconds": 43 + } + } + CreateTranscriptionResponseJson: + type: object + description: >- + Represents a transcription response returned by model, based on the + provided input. + properties: + text: + type: string + description: The transcribed text. + logprobs: + type: array + optional: true + description: > + The log probabilities of the tokens in the transcription. Only + returned with the models `gpt-4o-transcribe` and + `gpt-4o-mini-transcribe` if `logprobs` is added to the `include` + array. + items: + type: object + properties: + token: + type: string + description: The token in the transcription. + logprob: + type: number + description: The log probability of the token. + bytes: + type: array + items: + type: number + description: The bytes of the token. + usage: + type: object + description: Token usage statistics for the request. + oneOf: + - $ref: '#/components/schemas/TranscriptTextUsageTokens' + title: Token Usage + - $ref: '#/components/schemas/TranscriptTextUsageDuration' + title: Duration Usage + required: + - text + x-oaiMeta: + name: The transcription object (JSON) + group: audio + example: | + { + "text": "Imagine the wildest idea that you've ever had, and you're curious about how it might scale to something that's a 100, a 1,000 times bigger. This is a place where you can get to do that.", + "usage": { + "type": "tokens", + "input_tokens": 14, + "input_token_details": { + "text_tokens": 10, + "audio_tokens": 4 + }, + "output_tokens": 101, + "total_tokens": 115 + } + } + CreateTranscriptionResponseStreamEvent: + anyOf: + - $ref: '#/components/schemas/TranscriptTextSegmentEvent' + - $ref: '#/components/schemas/TranscriptTextDeltaEvent' + - $ref: '#/components/schemas/TranscriptTextDoneEvent' + discriminator: + propertyName: type + CreateTranscriptionResponseVerboseJson: + type: object + description: >- + Represents a verbose json transcription response returned by model, + based on the provided input. + properties: + language: + type: string + description: The language of the input audio. + duration: + type: number + description: The duration of the input audio. + text: + type: string + description: The transcribed text. + words: + type: array + description: Extracted words and their corresponding timestamps. + items: + $ref: '#/components/schemas/TranscriptionWord' + segments: + type: array + description: Segments of the transcribed text and their corresponding details. + items: + $ref: '#/components/schemas/TranscriptionSegment' + usage: + $ref: '#/components/schemas/TranscriptTextUsageDuration' + required: + - language + - duration + - text + x-oaiMeta: + name: The transcription object (Verbose JSON) + group: audio + example: | + { + "task": "transcribe", + "language": "english", + "duration": 8.470000267028809, + "text": "The beach was a popular spot on a hot summer day. People were swimming in the ocean, building sandcastles, and playing beach volleyball.", + "segments": [ + { + "id": 0, + "seek": 0, + "start": 0.0, + "end": 3.319999933242798, + "text": " The beach was a popular spot on a hot summer day.", + "tokens": [ + 50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530 + ], + "temperature": 0.0, + "avg_logprob": -0.2860786020755768, + "compression_ratio": 1.2363636493682861, + "no_speech_prob": 0.00985979475080967 + }, + ... + ], + "usage": { + "type": "duration", + "seconds": 9 + } + } + CreateTranslationRequest: + type: object + additionalProperties: false + properties: + file: + description: > + The audio file object (not file name) translate, in one of these + formats: flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. + type: string + x-oaiTypeLabel: file + format: binary + model: + description: > + ID of the model to use. Only `whisper-1` (which is powered by our + open source Whisper V2 model) is currently available. + example: whisper-1 + anyOf: + - type: string + - type: string + enum: + - whisper-1 + x-stainless-const: true + x-oaiTypeLabel: string + prompt: + description: > + An optional text to guide the model's style or continue a previous + audio segment. The [prompt](/docs/guides/speech-to-text#prompting) + should be in English. + type: string + response_format: + description: > + The format of the output, in one of these options: `json`, `text`, + `srt`, `verbose_json`, or `vtt`. + type: string + enum: + - json + - text + - srt + - verbose_json + - vtt + default: json + temperature: + description: > + The sampling temperature, between 0 and 1. Higher values like 0.8 + will make the output more random, while lower values like 0.2 will + make it more focused and deterministic. If set to 0, the model will + use [log probability](https://en.wikipedia.org/wiki/Log_probability) + to automatically increase the temperature until certain thresholds + are hit. + type: number + default: 0 + required: + - file + - model + CreateTranslationResponseJson: + type: object + properties: + text: + type: string + required: + - text + CreateTranslationResponseVerboseJson: + type: object + properties: + language: + type: string + description: The language of the output translation (always `english`). + duration: + type: number + description: The duration of the input audio. + text: + type: string + description: The translated text. + segments: + type: array + description: Segments of the translated text and their corresponding details. + items: + $ref: '#/components/schemas/TranscriptionSegment' + required: + - language + - duration + - text + CreateUploadRequest: + type: object + additionalProperties: false + properties: + filename: + description: | + The name of the file to upload. + type: string + purpose: + description: | + The intended purpose of the uploaded file. + + See the [documentation on File + purposes](/docs/api-reference/files/create#files-create-purpose). + type: string + enum: + - assistants + - batch + - fine-tune + - vision + bytes: + description: | + The number of bytes in the file you are uploading. + type: integer + mime_type: + description: > + The MIME type of the file. + + + + This must fall within the supported MIME types for your file + purpose. See + + the supported MIME types for assistants and vision. + type: string + expires_after: + $ref: '#/components/schemas/FileExpirationAfter' + required: + - filename + - purpose + - bytes + - mime_type + CreateVectorStoreFileBatchRequest: + type: object + additionalProperties: false + properties: + file_ids: + description: >- + A list of [File](/docs/api-reference/files) IDs that the vector + store should use. Useful for tools like `file_search` that can + access files. If `attributes` or `chunking_strategy` are provided, + they will be applied to all files in the batch. The maximum batch + size is 2000 files. This endpoint is recommended for multi-file + ingestion and helps reduce per-vector-store write request pressure. + Mutually exclusive with `files`. + type: array + minItems: 1 + maxItems: 2000 + items: + type: string + files: + description: >- + A list of objects that each include a `file_id` plus optional + `attributes` or `chunking_strategy`. Use this when you need to + override metadata for specific files. The global `attributes` or + `chunking_strategy` will be ignored and must be specified for each + file. The maximum batch size is 2000 files. This endpoint is + recommended for multi-file ingestion and helps reduce + per-vector-store write request pressure. Mutually exclusive with + `file_ids`. + type: array + minItems: 1 + maxItems: 2000 + items: + $ref: '#/components/schemas/CreateVectorStoreFileRequest' + chunking_strategy: + $ref: '#/components/schemas/ChunkingStrategyRequestParam' + attributes: + $ref: '#/components/schemas/VectorStoreFileAttributes' + anyOf: + - required: + - file_ids + - required: + - files + CreateVectorStoreFileRequest: + type: object + additionalProperties: false + properties: + file_id: + description: >- + A [File](/docs/api-reference/files) ID that the vector store should + use. Useful for tools like `file_search` that can access files. For + multi-file ingestion, we recommend + [`file_batches`](/docs/api-reference/vector-stores-file-batches/createBatch) + to minimize per-vector-store write requests. + type: string + chunking_strategy: + $ref: '#/components/schemas/ChunkingStrategyRequestParam' + attributes: + $ref: '#/components/schemas/VectorStoreFileAttributes' + required: + - file_id + CreateVectorStoreRequest: + type: object + additionalProperties: false + properties: + file_ids: + description: >- + A list of [File](/docs/api-reference/files) IDs that the vector + store should use. Useful for tools like `file_search` that can + access files. + type: array + maxItems: 500 + items: + type: string + name: + description: The name of the vector store. + type: string + description: + description: >- + A description for the vector store. Can be used to describe the + vector store's purpose. + type: string + expires_after: + $ref: '#/components/schemas/VectorStoreExpirationAfter' + chunking_strategy: + type: object + description: >- + The chunking strategy used to chunk the file(s). If not set, will + use the `auto` strategy. Only applicable if `file_ids` is non-empty. + oneOf: + - $ref: '#/components/schemas/AutoChunkingStrategyRequestParam' + - $ref: '#/components/schemas/StaticChunkingStrategyRequestParam' + metadata: + $ref: '#/components/schemas/Metadata' + CreateVoiceConsentRequest: + type: object + additionalProperties: false + properties: + name: + type: string + description: The label to use for this consent recording. + recording: + type: string + format: binary + x-oaiTypeLabel: file + description: > + The consent audio recording file. Maximum size is 10 MiB. + + + Supported MIME types: + + `audio/mpeg`, `audio/wav`, `audio/x-wav`, `audio/ogg`, `audio/aac`, + `audio/flac`, `audio/webm`, `audio/mp4`. + language: + type: string + description: >- + The BCP 47 language tag for the consent phrase (for example, + `en-US`). + required: + - name + - recording + - language + CreateVoiceRequest: + type: object + additionalProperties: false + properties: + name: + type: string + description: The name of the new voice. + audio_sample: + type: string + format: binary + x-oaiTypeLabel: file + description: > + The sample audio recording file. Maximum size is 10 MiB. + + + Supported MIME types: + + `audio/mpeg`, `audio/wav`, `audio/x-wav`, `audio/ogg`, `audio/aac`, + `audio/flac`, `audio/webm`, `audio/mp4`. + consent: + type: string + description: The consent recording ID (for example, `cons_1234`). + required: + - name + - audio_sample + - consent + CustomToolCall: + type: object + title: Custom tool call + description: | + A call to a custom tool created by the model. + properties: + type: + type: string + enum: + - custom_tool_call + x-stainless-const: true + description: | + The type of the custom tool call. Always `custom_tool_call`. + id: + type: string + description: | + The unique ID of the custom tool call in the OpenAI platform. + call_id: + type: string + description: > + An identifier used to map this custom tool call to a tool call + output. + namespace: + type: string + description: | + The namespace of the custom tool being called. + name: + type: string + description: | + The name of the custom tool being called. + input: + type: string + description: | + The input for the custom tool call generated by the model. + required: + - type + - call_id + - name + - input + CustomToolCallOutput: + type: object + title: Custom tool call output + description: > + The output of a custom tool call from your code, being sent back to the + model. + properties: + type: + type: string + enum: + - custom_tool_call_output + x-stainless-const: true + description: > + The type of the custom tool call output. Always + `custom_tool_call_output`. + id: + type: string + description: | + The unique ID of the custom tool call output in the OpenAI platform. + call_id: + type: string + description: > + The call ID, used to map this custom tool call output to a custom + tool call. + output: + description: | + The output from the custom tool call generated by your code. + Can be a string or an list of output content. + oneOf: + - type: string + description: | + A string of the output of the custom tool call. + title: string output + - type: array + items: + $ref: '#/components/schemas/FunctionAndCustomToolCallOutput' + title: output content list + description: | + Text, image, or file output of the custom tool call. + required: + - type + - call_id + - output + CustomToolCallOutputResource: + title: ResponseCustomToolCallOutputItem + allOf: + - $ref: '#/components/schemas/CustomToolCallOutput' + - type: object + properties: + id: + type: string + description: | + The unique ID of the custom tool call output item. + status: + description: | + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + $ref: '#/components/schemas/FunctionCallOutputStatusEnum' + created_by: + type: string + description: | + The identifier of the actor that created the item. + required: + - id + - status + CustomToolCallResource: + title: ResponseCustomToolCallItem + allOf: + - $ref: '#/components/schemas/CustomToolCall' + - type: object + properties: + id: + type: string + description: | + The unique ID of the custom tool call item. + status: + description: | + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + $ref: '#/components/schemas/FunctionCallStatus' + created_by: + type: string + description: | + The identifier of the actor that created the item. + required: + - id + - status + CustomToolChatCompletions: + type: object + title: Custom tool + description: | + A custom tool that processes input using a specified format. + properties: + type: + type: string + enum: + - custom + description: The type of the custom tool. Always `custom`. + x-stainless-const: true + custom: + type: object + title: Custom tool properties + description: | + Properties of the custom tool. + properties: + name: + type: string + description: The name of the custom tool, used to identify it in tool calls. + description: + type: string + description: > + Optional description of the custom tool, used to provide more + context. + format: + description: > + The input format for the custom tool. Default is unconstrained + text. + oneOf: + - type: object + title: Text format + description: Unconstrained free-form text. + properties: + type: + type: string + enum: + - text + description: Unconstrained text format. Always `text`. + x-stainless-const: true + required: + - type + additionalProperties: false + - type: object + title: Grammar format + description: A grammar defined by the user. + properties: + type: + type: string + enum: + - grammar + description: Grammar format. Always `grammar`. + x-stainless-const: true + grammar: + type: object + title: Grammar format + description: Your chosen grammar. + properties: + definition: + type: string + description: The grammar definition. + syntax: + type: string + description: >- + The syntax of the grammar definition. One of `lark` + or `regex`. + enum: + - lark + - regex + required: + - definition + - syntax + required: + - type + - grammar + additionalProperties: false + required: + - name + required: + - type + - custom + DeleteAssistantResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: + - assistant.deleted + x-stainless-const: true + required: + - id + - object + - deleted + DeleteCertificateResponse: + type: object + properties: + object: + type: string + description: The object type, must be `certificate.deleted`. + enum: + - certificate.deleted + x-stainless-const: true + id: + type: string + description: The ID of the certificate that was deleted. + required: + - object + - id + DeleteFileResponse: + type: object + properties: + id: + type: string + object: + type: string + enum: + - file + x-stainless-const: true + deleted: + type: boolean + required: + - id + - object + - deleted + DeleteFineTuningCheckpointPermissionResponse: + type: object + properties: + id: + type: string + description: >- + The ID of the fine-tuned model checkpoint permission that was + deleted. + object: + type: string + description: The object type, which is always "checkpoint.permission". + enum: + - checkpoint.permission + x-stainless-const: true + deleted: + type: boolean + description: >- + Whether the fine-tuned model checkpoint permission was successfully + deleted. + required: + - id + - object + - deleted + DeleteMessageResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: + - thread.message.deleted + x-stainless-const: true + required: + - id + - object + - deleted + DeleteModelResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + required: + - id + - object + - deleted + DeleteThreadResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: + - thread.deleted + x-stainless-const: true + required: + - id + - object + - deleted + DeleteVectorStoreFileResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: + - vector_store.file.deleted + x-stainless-const: true + required: + - id + - object + - deleted + DeleteVectorStoreResponse: + type: object + properties: + id: + type: string + deleted: + type: boolean + object: + type: string + enum: + - vector_store.deleted + x-stainless-const: true + required: + - id + - object + - deleted + DeletedConversation: + title: The deleted conversation object + allOf: + - $ref: '#/components/schemas/DeletedConversationResource' + x-oaiMeta: + name: The deleted conversation object + group: conversations + DeletedRoleAssignmentResource: + type: object + description: Confirmation payload returned after unassigning a role. + properties: + object: + type: string + description: >- + Identifier for the deleted assignment, such as `group.role.deleted` + or `user.role.deleted`. + deleted: + type: boolean + description: Whether the assignment was removed. + required: + - object + - deleted + x-oaiMeta: + name: Role assignment deletion confirmation + example: | + { + "object": "group.role.deleted", + "deleted": true + } + DoneEvent: + type: object + properties: + event: + type: string + enum: + - done + x-stainless-const: true + data: + type: string + enum: + - '[DONE]' + x-stainless-const: true + required: + - event + - data + description: Occurs when a stream ends. + x-oaiMeta: + dataDescription: '`data` is `[DONE]`' + EasyInputMessage: + type: object + title: Input message + description: > + A message input to the model with a role indicating instruction + following + + hierarchy. Instructions given with the `developer` or `system` role take + + precedence over instructions given with the `user` role. Messages with + the + + `assistant` role are presumed to have been generated by the model in + previous + + interactions. + properties: + role: + type: string + description: > + The role of the message input. One of `user`, `assistant`, `system`, + or + + `developer`. + enum: + - user + - assistant + - system + - developer + content: + description: > + Text, image, or audio input to the model, used to generate a + response. + + Can also contain previous assistant responses. + oneOf: + - type: string + title: Text input + description: | + A text input to the model. + - $ref: '#/components/schemas/InputMessageContentList' + phase: + anyOf: + - $ref: '#/components/schemas/MessagePhase' + - type: 'null' + type: + type: string + description: | + The type of the message input. Always `message`. + enum: + - message + x-stainless-const: true + required: + - role + - content + EditImageBodyJsonParam: + type: object + description: > + JSON request body for image edits. + + + Use `images` (array of `ImageRefParam`) instead of multipart `image` + uploads. + + You can reference images via external URLs, data URLs, or uploaded file + IDs. + + JSON edits support GPT image models only; DALL-E edits require multipart + (`dall-e-2` only). + properties: + model: + anyOf: + - type: string + - type: string + enum: + - gpt-image-1.5 + - gpt-image-1 + - gpt-image-1-mini + - chatgpt-image-latest + - type: 'null' + x-oaiTypeLabel: string + default: gpt-image-1.5 + example: gpt-image-1.5 + description: The model to use for image editing. + images: + type: array + minItems: 1 + maxItems: 16 + description: | + Input image references to edit. + For GPT image models, you can provide up to 16 images. + items: + $ref: '#/components/schemas/ImageRefParam' + mask: + $ref: '#/components/schemas/ImageRefParam' + prompt: + type: string + minLength: 1 + maxLength: 32000 + example: Add a watercolor effect and keep the subject centered + description: A text description of the desired image edit. + 'n': + anyOf: + - type: integer + minimum: 1 + maximum: 10 + - type: 'null' + default: 1 + example: 1 + description: The number of edited images to generate. + quality: + anyOf: + - type: string + enum: + - low + - medium + - high + - auto + - type: 'null' + default: auto + example: high + description: | + Output quality for GPT image models. + input_fidelity: + anyOf: + - type: string + enum: + - high + - low + - type: 'null' + description: Controls fidelity to the original input image(s). + size: + anyOf: + - type: string + enum: + - auto + - 1024x1024 + - 1536x1024 + - 1024x1536 + - type: 'null' + default: auto + example: 1024x1024 + description: Requested output image size. + user: + type: string + example: user-1234 + description: > + A unique identifier representing your end-user, which can help + OpenAI + + monitor and detect abuse. + output_format: + anyOf: + - type: string + enum: + - png + - jpeg + - webp + - type: 'null' + default: png + example: png + description: Output image format. Supported for GPT image models. + output_compression: + anyOf: + - type: integer + minimum: 0 + maximum: 100 + - type: 'null' + example: 100 + description: Compression level for `jpeg` or `webp` output. + moderation: + anyOf: + - type: string + enum: + - low + - auto + - type: 'null' + default: auto + example: auto + description: Moderation level for GPT image models. + background: + anyOf: + - type: string + enum: + - transparent + - opaque + - auto + - type: 'null' + default: auto + example: transparent + description: Background behavior for generated image output. + stream: + anyOf: + - type: boolean + - type: 'null' + default: false + example: false + description: Stream partial image results as events. + partial_images: + $ref: '#/components/schemas/PartialImages' + required: + - images + - prompt + Embedding: + type: object + description: | + Represents an embedding vector returned by embedding endpoint. + properties: + index: + type: integer + description: The index of the embedding in the list of embeddings. + embedding: + type: array + description: > + The embedding vector, which is a list of floats. The length of + vector depends on the model as listed in the [embedding + guide](/docs/guides/embeddings). + items: + type: number + format: float + object: + type: string + description: The object type, which is always "embedding". + enum: + - embedding + x-stainless-const: true + required: + - index + - object + - embedding + x-oaiMeta: + name: The embedding object + example: | + { + "object": "embedding", + "embedding": [ + 0.0023064255, + -0.009327292, + .... (1536 floats total for ada-002) + -0.0028842222, + ], + "index": 0 + } + Error: + type: object + properties: + code: + anyOf: + - type: string + - type: 'null' + message: + type: string + param: + anyOf: + - type: string + - type: 'null' + type: + type: string + required: + - type + - message + - param + - code + ErrorEvent: + type: object + properties: + event: + type: string + enum: + - error + x-stainless-const: true + data: + $ref: '#/components/schemas/Error' + required: + - event + - data + description: >- + Occurs when an [error](/docs/guides/error-codes#api-errors) occurs. This + can happen due to an internal server error or a timeout. + x-oaiMeta: + dataDescription: '`data` is an [error](/docs/guides/error-codes#api-errors)' + ErrorResponse: + type: object + properties: + error: + $ref: '#/components/schemas/Error' + required: + - error + Eval: + type: object + title: Eval + description: | + An Eval object with a data source config and testing criteria. + An Eval represents a task to be done for your LLM integration. + Like: + - Improve the quality of my chatbot + - See how well my chatbot handles customer support + - Check if o4-mini is better at my usecase than gpt-4o + properties: + object: + type: string + enum: + - eval + default: eval + description: The object type. + x-stainless-const: true + id: + type: string + description: Unique identifier for the evaluation. + name: + type: string + description: The name of the evaluation. + example: Chatbot effectiveness Evaluation + data_source_config: + type: object + description: Configuration of data sources used in runs of the evaluation. + oneOf: + - $ref: '#/components/schemas/EvalCustomDataSourceConfig' + - $ref: '#/components/schemas/EvalLogsDataSourceConfig' + - $ref: '#/components/schemas/EvalStoredCompletionsDataSourceConfig' + testing_criteria: + default: eval + description: A list of testing criteria. + type: array + items: + oneOf: + - $ref: '#/components/schemas/EvalGraderLabelModel' + - $ref: '#/components/schemas/EvalGraderStringCheck' + - $ref: '#/components/schemas/EvalGraderTextSimilarity' + - $ref: '#/components/schemas/EvalGraderPython' + - $ref: '#/components/schemas/EvalGraderScoreModel' + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the eval was created. + metadata: + $ref: '#/components/schemas/Metadata' + required: + - id + - data_source_config + - object + - testing_criteria + - name + - created_at + - metadata + x-oaiMeta: + name: The eval object + group: evals + example: | + { + "object": "eval", + "id": "eval_67abd54d9b0081909a86353f6fb9317a", + "data_source_config": { + "type": "custom", + "item_schema": { + "type": "object", + "properties": { + "label": {"type": "string"}, + }, + "required": ["label"] + }, + "include_sample_schema": true + }, + "testing_criteria": [ + { + "name": "My string check grader", + "type": "string_check", + "input": "{{sample.output_text}}", + "reference": "{{item.label}}", + "operation": "eq", + } + ], + "name": "External Data Eval", + "created_at": 1739314509, + "metadata": { + "test": "synthetics", + } + } + EvalApiError: + type: object + title: EvalApiError + description: | + An object representing an error response from the Eval API. + properties: + code: + type: string + description: The error code. + message: + type: string + description: The error message. + required: + - code + - message + x-oaiMeta: + name: The API error object + group: evals + example: | + { + "code": "internal_error", + "message": "The eval run failed due to an internal error." + } + EvalCustomDataSourceConfig: + type: object + title: CustomDataSourceConfig + description: > + A CustomDataSourceConfig which specifies the schema of your `item` and + optionally `sample` namespaces. + + The response schema defines the shape of the data that will be: + + - Used to define your testing criteria and + + - What data is required when creating a run + properties: + type: + type: string + enum: + - custom + default: custom + description: The type of data source. Always `custom`. + x-stainless-const: true + schema: + type: object + description: | + The json schema for the run data source items. + Learn how to build JSON schemas [here](https://json-schema.org/). + additionalProperties: true + example: | + { + "type": "object", + "properties": { + "item": { + "type": "object", + "properties": { + "label": {"type": "string"}, + }, + "required": ["label"] + } + }, + "required": ["item"] + } + required: + - type + - schema + x-oaiMeta: + name: The eval custom data source config object + group: evals + example: | + { + "type": "custom", + "schema": { + "type": "object", + "properties": { + "item": { + "type": "object", + "properties": { + "label": {"type": "string"}, + }, + "required": ["label"] + } + }, + "required": ["item"] + } + } + EvalGraderLabelModel: + type: object + title: LabelModelGrader + allOf: + - $ref: '#/components/schemas/GraderLabelModel' + EvalGraderPython: + type: object + title: PythonGrader + allOf: + - $ref: '#/components/schemas/GraderPython' + - type: object + properties: + pass_threshold: + type: number + description: The threshold for the score. + x-oaiMeta: + name: Eval Python Grader + group: graders + example: | + { + "type": "python", + "name": "Example python grader", + "image_tag": "2025-05-08", + "source": """ + def grade(sample: dict, item: dict) -> float: + \""" + Returns 1.0 if `output_text` equals `label`, otherwise 0.0. + \""" + output = sample.get("output_text") + label = item.get("label") + return 1.0 if output == label else 0.0 + """, + "pass_threshold": 0.8 + } + EvalGraderScoreModel: + type: object + title: ScoreModelGrader + allOf: + - $ref: '#/components/schemas/GraderScoreModel' + - type: object + properties: + pass_threshold: + type: number + description: The threshold for the score. + EvalGraderStringCheck: + type: object + title: StringCheckGrader + allOf: + - $ref: '#/components/schemas/GraderStringCheck' + EvalGraderTextSimilarity: + type: object + title: TextSimilarityGrader + allOf: + - $ref: '#/components/schemas/GraderTextSimilarity' + - type: object + properties: + pass_threshold: + type: number + description: The threshold for the score. + required: + - pass_threshold + x-oaiMeta: + name: Text Similarity Grader + group: graders + example: | + { + "type": "text_similarity", + "name": "Example text similarity grader", + "input": "{{sample.output_text}}", + "reference": "{{item.label}}", + "pass_threshold": 0.8, + "evaluation_metric": "fuzzy_match" + } + EvalItem: + type: object + title: Eval message object + description: > + A message input to the model with a role indicating instruction + following + + hierarchy. Instructions given with the `developer` or `system` role take + + precedence over instructions given with the `user` role. Messages with + the + + `assistant` role are presumed to have been generated by the model in + previous + + interactions. + properties: + role: + type: string + description: > + The role of the message input. One of `user`, `assistant`, `system`, + or + + `developer`. + enum: + - user + - assistant + - system + - developer + content: + $ref: '#/components/schemas/EvalItemContent' + type: + type: string + description: | + The type of the message input. Always `message`. + enum: + - message + x-stainless-const: true + required: + - role + - content + EvalItemContent: + title: Eval content + description: > + Inputs to the model - can contain template strings. Supports text, + output text, input images, and input audio, either as a single item or + an array of items. + oneOf: + - $ref: '#/components/schemas/EvalItemContentItem' + - $ref: '#/components/schemas/EvalItemContentArray' + EvalItemContentArray: + type: array + title: An array of Input text, Output text, Input image, and Input audio + description: > + A list of inputs, each of which may be either an input text, output + text, input + + image, or input audio object. + items: + $ref: '#/components/schemas/EvalItemContentItem' + EvalItemContentItem: + title: Eval content item + description: > + A single content item: input text, output text, input image, or input + audio. + oneOf: + - $ref: '#/components/schemas/EvalItemContentText' + - $ref: '#/components/schemas/InputTextContent' + - $ref: '#/components/schemas/EvalItemContentOutputText' + - $ref: '#/components/schemas/EvalItemInputImage' + - $ref: '#/components/schemas/InputAudio' + EvalItemContentOutputText: + type: object + title: Output text + description: | + A text output from the model. + properties: + type: + type: string + description: | + The type of the output text. Always `output_text`. + enum: + - output_text + x-stainless-const: true + text: + type: string + description: | + The text output from the model. + required: + - type + - text + EvalItemContentText: + type: string + title: Text input + description: | + A text input to the model. + EvalItemInputImage: + title: Input image + description: An image input block used within EvalItem content arrays. + type: object + properties: + type: + type: string + description: | + The type of the image input. Always `input_image`. + enum: + - input_image + x-stainless-const: true + image_url: + type: string + description: | + The URL of the image input. + detail: + type: string + description: > + The detail level of the image to be sent to the model. One of + `high`, `low`, or `auto`. Defaults to `auto`. + required: + - type + - image_url + EvalJsonlFileContentSource: + type: object + title: EvalJsonlFileContentSource + properties: + type: + type: string + enum: + - file_content + default: file_content + description: The type of jsonl source. Always `file_content`. + x-stainless-const: true + content: + type: array + items: + type: object + properties: + item: + type: object + additionalProperties: true + sample: + type: object + additionalProperties: true + required: + - item + description: The content of the jsonl file. + required: + - type + - content + EvalJsonlFileIdSource: + type: object + title: EvalJsonlFileIdSource + properties: + type: + type: string + enum: + - file_id + default: file_id + description: The type of jsonl source. Always `file_id`. + x-stainless-const: true + id: + type: string + description: The identifier of the file. + required: + - type + - id + EvalList: + type: object + title: EvalList + description: | + An object representing a list of evals. + properties: + object: + type: string + enum: + - list + default: list + description: | + The type of this object. It is always set to "list". + x-stainless-const: true + data: + type: array + description: | + An array of eval objects. + items: + $ref: '#/components/schemas/Eval' + first_id: + type: string + description: The identifier of the first eval in the data array. + last_id: + type: string + description: The identifier of the last eval in the data array. + has_more: + type: boolean + description: Indicates whether there are more evals available. + required: + - object + - data + - first_id + - last_id + - has_more + x-oaiMeta: + name: The eval list object + group: evals + example: | + { + "object": "list", + "data": [ + { + "object": "eval", + "id": "eval_67abd54d9b0081909a86353f6fb9317a", + "data_source_config": { + "type": "custom", + "schema": { + "type": "object", + "properties": { + "item": { + "type": "object", + "properties": { + "input": { + "type": "string" + }, + "ground_truth": { + "type": "string" + } + }, + "required": [ + "input", + "ground_truth" + ] + } + }, + "required": [ + "item" + ] + } + }, + "testing_criteria": [ + { + "name": "String check", + "id": "String check-2eaf2d8d-d649-4335-8148-9535a7ca73c2", + "type": "string_check", + "input": "{{item.input}}", + "reference": "{{item.ground_truth}}", + "operation": "eq" + } + ], + "name": "External Data Eval", + "created_at": 1739314509, + "metadata": {}, + } + ], + "first_id": "eval_67abd54d9b0081909a86353f6fb9317a", + "last_id": "eval_67abd54d9b0081909a86353f6fb9317a", + "has_more": true + } + EvalLogsDataSourceConfig: + type: object + title: LogsDataSourceConfig + description: > + A LogsDataSourceConfig which specifies the metadata property of your + logs query. + + This is usually metadata like `usecase=chatbot` or `prompt-version=v2`, + etc. + + The schema returned by this data source config is used to defined what + variables are available in your evals. + + `item` and `sample` are both defined when using this data source config. + properties: + type: + type: string + enum: + - logs + default: logs + description: The type of data source. Always `logs`. + x-stainless-const: true + metadata: + $ref: '#/components/schemas/Metadata' + schema: + type: object + description: | + The json schema for the run data source items. + Learn how to build JSON schemas [here](https://json-schema.org/). + additionalProperties: true + required: + - type + - schema + x-oaiMeta: + name: The logs data source object for evals + group: evals + example: | + { + "type": "logs", + "metadata": { + "language": "english" + }, + "schema": { + "type": "object", + "properties": { + "item": { + "type": "object" + }, + "sample": { + "type": "object" + } + }, + "required": [ + "item", + "sample" + } + } + EvalResponsesSource: + type: object + title: EvalResponsesSource + description: | + A EvalResponsesSource object describing a run data source configuration. + properties: + type: + type: string + enum: + - responses + description: The type of run data source. Always `responses`. + metadata: + anyOf: + - type: object + description: >- + Metadata filter for the responses. This is a query parameter + used to select responses. + - type: 'null' + model: + anyOf: + - type: string + description: >- + The name of the model to find responses for. This is a query + parameter used to select responses. + - type: 'null' + instructions_search: + anyOf: + - type: string + description: >- + Optional string to search the 'instructions' field. This is a + query parameter used to select responses. + - type: 'null' + created_after: + anyOf: + - type: integer + minimum: 0 + description: >- + Only include items created after this timestamp (inclusive). + This is a query parameter used to select responses. + - type: 'null' + created_before: + anyOf: + - type: integer + minimum: 0 + description: >- + Only include items created before this timestamp (inclusive). + This is a query parameter used to select responses. + - type: 'null' + reasoning_effort: + anyOf: + - $ref: '#/components/schemas/ReasoningEffort' + description: >- + Optional reasoning effort parameter. This is a query parameter + used to select responses. + - type: 'null' + temperature: + anyOf: + - type: number + description: >- + Sampling temperature. This is a query parameter used to select + responses. + - type: 'null' + top_p: + anyOf: + - type: number + description: >- + Nucleus sampling parameter. This is a query parameter used to + select responses. + - type: 'null' + users: + anyOf: + - type: array + items: + type: string + description: >- + List of user identifiers. This is a query parameter used to + select responses. + - type: 'null' + tools: + anyOf: + - type: array + items: + type: string + description: >- + List of tool names. This is a query parameter used to select + responses. + - type: 'null' + required: + - type + x-oaiMeta: + name: The run data source object used to configure an individual run + group: eval runs + example: | + { + "type": "responses", + "model": "gpt-4o-mini-2024-07-18", + "temperature": 0.7, + "top_p": 1.0, + "users": ["user1", "user2"], + "tools": ["tool1", "tool2"], + "instructions_search": "You are a coding assistant" + } + EvalRun: + type: object + title: EvalRun + description: | + A schema representing an evaluation run. + properties: + object: + type: string + enum: + - eval.run + default: eval.run + description: The type of the object. Always "eval.run". + x-stainless-const: true + id: + type: string + description: Unique identifier for the evaluation run. + eval_id: + type: string + description: The identifier of the associated evaluation. + status: + type: string + description: The status of the evaluation run. + model: + type: string + description: The model that is evaluated, if applicable. + name: + type: string + description: The name of the evaluation run. + created_at: + type: integer + description: Unix timestamp (in seconds) when the evaluation run was created. + report_url: + type: string + description: The URL to the rendered evaluation run report on the UI dashboard. + result_counts: + type: object + description: Counters summarizing the outcomes of the evaluation run. + properties: + total: + type: integer + description: Total number of executed output items. + errored: + type: integer + description: Number of output items that resulted in an error. + failed: + type: integer + description: Number of output items that failed to pass the evaluation. + passed: + type: integer + description: Number of output items that passed the evaluation. + required: + - total + - errored + - failed + - passed + per_model_usage: + type: array + description: Usage statistics for each model during the evaluation run. + items: + type: object + properties: + model_name: + type: string + description: The name of the model. + invocation_count: + type: integer + description: The number of invocations. + prompt_tokens: + type: integer + description: The number of prompt tokens used. + completion_tokens: + type: integer + description: The number of completion tokens generated. + total_tokens: + type: integer + description: The total number of tokens used. + cached_tokens: + type: integer + description: The number of tokens retrieved from cache. + required: + - model_name + - invocation_count + - prompt_tokens + - completion_tokens + - total_tokens + - cached_tokens + per_testing_criteria_results: + type: array + description: Results per testing criteria applied during the evaluation run. + items: + type: object + properties: + testing_criteria: + type: string + description: A description of the testing criteria. + passed: + type: integer + description: Number of tests passed for this criteria. + failed: + type: integer + description: Number of tests failed for this criteria. + required: + - testing_criteria + - passed + - failed + data_source: + type: object + description: Information about the run's data source. + oneOf: + - $ref: '#/components/schemas/CreateEvalJsonlRunDataSource' + - $ref: '#/components/schemas/CreateEvalCompletionsRunDataSource' + - $ref: '#/components/schemas/CreateEvalResponsesRunDataSource' + metadata: + $ref: '#/components/schemas/Metadata' + error: + $ref: '#/components/schemas/EvalApiError' + required: + - object + - id + - eval_id + - status + - model + - name + - created_at + - report_url + - result_counts + - per_model_usage + - per_testing_criteria_results + - data_source + - metadata + - error + x-oaiMeta: + name: The eval run object + group: evals + example: | + { + "object": "eval.run", + "id": "evalrun_67e57965b480819094274e3a32235e4c", + "eval_id": "eval_67e579652b548190aaa83ada4b125f47", + "report_url": "https://platform.openai.com/evaluations/eval_67e579652b548190aaa83ada4b125f47?run_id=evalrun_67e57965b480819094274e3a32235e4c", + "status": "queued", + "model": "gpt-4o-mini", + "name": "gpt-4o-mini", + "created_at": 1743092069, + "result_counts": { + "total": 0, + "errored": 0, + "failed": 0, + "passed": 0 + }, + "per_model_usage": null, + "per_testing_criteria_results": null, + "data_source": { + "type": "completions", + "source": { + "type": "file_content", + "content": [ + { + "item": { + "input": "Tech Company Launches Advanced Artificial Intelligence Platform", + "ground_truth": "Technology" + } + }, + { + "item": { + "input": "Central Bank Increases Interest Rates Amid Inflation Concerns", + "ground_truth": "Markets" + } + }, + { + "item": { + "input": "International Summit Addresses Climate Change Strategies", + "ground_truth": "World" + } + }, + { + "item": { + "input": "Major Retailer Reports Record-Breaking Holiday Sales", + "ground_truth": "Business" + } + }, + { + "item": { + "input": "National Team Qualifies for World Championship Finals", + "ground_truth": "Sports" + } + }, + { + "item": { + "input": "Stock Markets Rally After Positive Economic Data Released", + "ground_truth": "Markets" + } + }, + { + "item": { + "input": "Global Manufacturer Announces Merger with Competitor", + "ground_truth": "Business" + } + }, + { + "item": { + "input": "Breakthrough in Renewable Energy Technology Unveiled", + "ground_truth": "Technology" + } + }, + { + "item": { + "input": "World Leaders Sign Historic Climate Agreement", + "ground_truth": "World" + } + }, + { + "item": { + "input": "Professional Athlete Sets New Record in Championship Event", + "ground_truth": "Sports" + } + }, + { + "item": { + "input": "Financial Institutions Adapt to New Regulatory Requirements", + "ground_truth": "Business" + } + }, + { + "item": { + "input": "Tech Conference Showcases Advances in Artificial Intelligence", + "ground_truth": "Technology" + } + }, + { + "item": { + "input": "Global Markets Respond to Oil Price Fluctuations", + "ground_truth": "Markets" + } + }, + { + "item": { + "input": "International Cooperation Strengthened Through New Treaty", + "ground_truth": "World" + } + }, + { + "item": { + "input": "Sports League Announces Revised Schedule for Upcoming Season", + "ground_truth": "Sports" + } + } + ] + }, + "input_messages": { + "type": "template", + "template": [ + { + "type": "message", + "role": "developer", + "content": { + "type": "input_text", + "text": "Categorize a given news headline into one of the following topics: Technology, Markets, World, Business, or Sports.\n\n# Steps\n\n1. Analyze the content of the news headline to understand its primary focus.\n2. Extract the subject matter, identifying any key indicators or keywords.\n3. Use the identified indicators to determine the most suitable category out of the five options: Technology, Markets, World, Business, or Sports.\n4. Ensure only one category is selected per headline.\n\n# Output Format\n\nRespond with the chosen category as a single word. For instance: \"Technology\", \"Markets\", \"World\", \"Business\", or \"Sports\".\n\n# Examples\n\n**Input**: \"Apple Unveils New iPhone Model, Featuring Advanced AI Features\" \n**Output**: \"Technology\"\n\n**Input**: \"Global Stocks Mixed as Investors Await Central Bank Decisions\" \n**Output**: \"Markets\"\n\n**Input**: \"War in Ukraine: Latest Updates on Negotiation Status\" \n**Output**: \"World\"\n\n**Input**: \"Microsoft in Talks to Acquire Gaming Company for $2 Billion\" \n**Output**: \"Business\"\n\n**Input**: \"Manchester United Secures Win in Premier League Football Match\" \n**Output**: \"Sports\" \n\n# Notes\n\n- If the headline appears to fit into more than one category, choose the most dominant theme.\n- Keywords or phrases such as \"stocks\", \"company acquisition\", \"match\", or technological brands can be good indicators for classification.\n" + } + }, + { + "type": "message", + "role": "user", + "content": { + "type": "input_text", + "text": "{{item.input}}" + } + } + ] + }, + "model": "gpt-4o-mini", + "sampling_params": { + "seed": 42, + "temperature": 1.0, + "top_p": 1.0, + "max_completions_tokens": 2048 + } + }, + "error": null, + "metadata": {} + } + EvalRunList: + type: object + title: EvalRunList + description: | + An object representing a list of runs for an evaluation. + properties: + object: + type: string + enum: + - list + default: list + description: | + The type of this object. It is always set to "list". + x-stainless-const: true + data: + type: array + description: | + An array of eval run objects. + items: + $ref: '#/components/schemas/EvalRun' + first_id: + type: string + description: The identifier of the first eval run in the data array. + last_id: + type: string + description: The identifier of the last eval run in the data array. + has_more: + type: boolean + description: Indicates whether there are more evals available. + required: + - object + - data + - first_id + - last_id + - has_more + x-oaiMeta: + name: The eval run list object + group: evals + example: | + { + "object": "list", + "data": [ + { + "object": "eval.run", + "id": "evalrun_67b7fbdad46c819092f6fe7a14189620", + "eval_id": "eval_67b7fa9a81a88190ab4aa417e397ea21", + "report_url": "https://platform.openai.com/evaluations/eval_67b7fa9a81a88190ab4aa417e397ea21?run_id=evalrun_67b7fbdad46c819092f6fe7a14189620", + "status": "completed", + "model": "o3-mini", + "name": "Academic Assistant", + "created_at": 1740110812, + "result_counts": { + "total": 171, + "errored": 0, + "failed": 80, + "passed": 91 + }, + "per_model_usage": null, + "per_testing_criteria_results": [ + { + "testing_criteria": "String check grader", + "passed": 91, + "failed": 80 + } + ], + "run_data_source": { + "type": "completions", + "template_messages": [ + { + "type": "message", + "role": "system", + "content": { + "type": "input_text", + "text": "You are a helpful assistant." + } + }, + { + "type": "message", + "role": "user", + "content": { + "type": "input_text", + "text": "Hello, can you help me with my homework?" + } + } + ], + "datasource_reference": null, + "model": "o3-mini", + "max_completion_tokens": null, + "seed": null, + "temperature": null, + "top_p": null + }, + "error": null, + "metadata": {"test": "synthetics"} + } + ], + "first_id": "evalrun_67abd54d60ec8190832b46859da808f7", + "last_id": "evalrun_67abd54d60ec8190832b46859da808f7", + "has_more": false + } + EvalRunOutputItem: + type: object + title: EvalRunOutputItem + description: | + A schema representing an evaluation run output item. + properties: + object: + type: string + enum: + - eval.run.output_item + default: eval.run.output_item + description: The type of the object. Always "eval.run.output_item". + x-stainless-const: true + id: + type: string + description: Unique identifier for the evaluation run output item. + run_id: + type: string + description: >- + The identifier of the evaluation run associated with this output + item. + eval_id: + type: string + description: The identifier of the evaluation group. + created_at: + type: integer + description: Unix timestamp (in seconds) when the evaluation run was created. + status: + type: string + description: The status of the evaluation run. + datasource_item_id: + type: integer + description: The identifier for the data source item. + datasource_item: + type: object + description: Details of the input data source item. + additionalProperties: true + results: + type: array + description: A list of grader results for this output item. + items: + $ref: '#/components/schemas/EvalRunOutputItemResult' + sample: + type: object + description: A sample containing the input and output of the evaluation run. + properties: + input: + type: array + description: An array of input messages. + items: + type: object + description: An input message. + properties: + role: + type: string + description: >- + The role of the message sender (e.g., system, user, + developer). + content: + type: string + description: The content of the message. + required: + - role + - content + output: + type: array + description: An array of output messages. + items: + type: object + properties: + role: + type: string + description: >- + The role of the message (e.g. "system", "assistant", + "user"). + content: + type: string + description: The content of the message. + finish_reason: + type: string + description: The reason why the sample generation was finished. + model: + type: string + description: The model used for generating the sample. + usage: + type: object + description: Token usage details for the sample. + properties: + total_tokens: + type: integer + description: The total number of tokens used. + completion_tokens: + type: integer + description: The number of completion tokens generated. + prompt_tokens: + type: integer + description: The number of prompt tokens used. + cached_tokens: + type: integer + description: The number of tokens retrieved from cache. + required: + - total_tokens + - completion_tokens + - prompt_tokens + - cached_tokens + error: + $ref: '#/components/schemas/EvalApiError' + temperature: + type: number + description: The sampling temperature used. + max_completion_tokens: + type: integer + description: The maximum number of tokens allowed for completion. + top_p: + type: number + description: The top_p value used for sampling. + seed: + type: integer + description: The seed used for generating the sample. + required: + - input + - output + - finish_reason + - model + - usage + - error + - temperature + - max_completion_tokens + - top_p + - seed + required: + - object + - id + - run_id + - eval_id + - created_at + - status + - datasource_item_id + - datasource_item + - results + - sample + x-oaiMeta: + name: The eval run output item object + group: evals + example: | + { + "object": "eval.run.output_item", + "id": "outputitem_67abd55eb6548190bb580745d5644a33", + "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", + "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", + "created_at": 1739314509, + "status": "pass", + "datasource_item_id": 137, + "datasource_item": { + "teacher": "To grade essays, I only check for style, content, and grammar.", + "student": "I am a student who is trying to write the best essay." + }, + "results": [ + { + "name": "String Check Grader", + "type": "string-check-grader", + "score": 1.0, + "passed": true, + } + ], + "sample": { + "input": [ + { + "role": "system", + "content": "You are an evaluator bot..." + }, + { + "role": "user", + "content": "You are assessing..." + } + ], + "output": [ + { + "role": "assistant", + "content": "The rubric is not clear nor concise." + } + ], + "finish_reason": "stop", + "model": "gpt-4o-2024-08-06", + "usage": { + "total_tokens": 521, + "completion_tokens": 2, + "prompt_tokens": 519, + "cached_tokens": 0 + }, + "error": null, + "temperature": 1.0, + "max_completion_tokens": 2048, + "top_p": 1.0, + "seed": 42 + } + } + EvalRunOutputItemList: + type: object + title: EvalRunOutputItemList + description: | + An object representing a list of output items for an evaluation run. + properties: + object: + type: string + enum: + - list + default: list + description: | + The type of this object. It is always set to "list". + x-stainless-const: true + data: + type: array + description: | + An array of eval run output item objects. + items: + $ref: '#/components/schemas/EvalRunOutputItem' + first_id: + type: string + description: The identifier of the first eval run output item in the data array. + last_id: + type: string + description: The identifier of the last eval run output item in the data array. + has_more: + type: boolean + description: Indicates whether there are more eval run output items available. + required: + - object + - data + - first_id + - last_id + - has_more + x-oaiMeta: + name: The eval run output item list object + group: evals + example: | + { + "object": "list", + "data": [ + { + "object": "eval.run.output_item", + "id": "outputitem_67abd55eb6548190bb580745d5644a33", + "run_id": "evalrun_67abd54d60ec8190832b46859da808f7", + "eval_id": "eval_67abd54d9b0081909a86353f6fb9317a", + "created_at": 1739314509, + "status": "pass", + "datasource_item_id": 137, + "datasource_item": { + "teacher": "To grade essays, I only check for style, content, and grammar.", + "student": "I am a student who is trying to write the best essay." + }, + "results": [ + { + "name": "String Check Grader", + "type": "string-check-grader", + "score": 1.0, + "passed": true, + } + ], + "sample": { + "input": [ + { + "role": "system", + "content": "You are an evaluator bot..." + }, + { + "role": "user", + "content": "You are assessing..." + } + ], + "output": [ + { + "role": "assistant", + "content": "The rubric is not clear nor concise." + } + ], + "finish_reason": "stop", + "model": "gpt-4o-2024-08-06", + "usage": { + "total_tokens": 521, + "completion_tokens": 2, + "prompt_tokens": 519, + "cached_tokens": 0 + }, + "error": null, + "temperature": 1.0, + "max_completion_tokens": 2048, + "top_p": 1.0, + "seed": 42 + } + }, + ], + "first_id": "outputitem_67abd55eb6548190bb580745d5644a33", + "last_id": "outputitem_67abd55eb6548190bb580745d5644a33", + "has_more": false + } + EvalRunOutputItemResult: + type: object + title: EvalRunOutputItemResult + description: | + A single grader result for an evaluation run output item. + properties: + name: + type: string + description: The name of the grader. + type: + type: string + description: The grader type (for example, "string-check-grader"). + score: + type: number + description: The numeric score produced by the grader. + passed: + type: boolean + description: Whether the grader considered the output a pass. + sample: + anyOf: + - type: object + additionalProperties: true + - type: 'null' + description: Optional sample or intermediate data produced by the grader. + additionalProperties: true + required: + - name + - score + - passed + EvalStoredCompletionsDataSourceConfig: + type: object + title: StoredCompletionsDataSourceConfig + description: | + Deprecated in favor of LogsDataSourceConfig. + properties: + type: + type: string + enum: + - stored_completions + default: stored_completions + description: The type of data source. Always `stored_completions`. + x-stainless-const: true + metadata: + $ref: '#/components/schemas/Metadata' + schema: + type: object + description: | + The json schema for the run data source items. + Learn how to build JSON schemas [here](https://json-schema.org/). + additionalProperties: true + required: + - type + - schema + deprecated: true + x-oaiMeta: + name: The stored completions data source object for evals + group: evals + example: | + { + "type": "stored_completions", + "metadata": { + "language": "english" + }, + "schema": { + "type": "object", + "properties": { + "item": { + "type": "object" + }, + "sample": { + "type": "object" + } + }, + "required": [ + "item", + "sample" + } + } + EvalStoredCompletionsSource: + type: object + title: StoredCompletionsRunDataSource + description: > + A StoredCompletionsRunDataSource configuration describing a set of + filters + properties: + type: + type: string + enum: + - stored_completions + default: stored_completions + description: The type of source. Always `stored_completions`. + x-stainless-const: true + metadata: + $ref: '#/components/schemas/Metadata' + model: + anyOf: + - type: string + description: An optional model to filter by (e.g., 'gpt-4o'). + - type: 'null' + created_after: + anyOf: + - type: integer + description: >- + An optional Unix timestamp to filter items created after this + time. + - type: 'null' + created_before: + anyOf: + - type: integer + description: >- + An optional Unix timestamp to filter items created before this + time. + - type: 'null' + limit: + anyOf: + - type: integer + description: An optional maximum number of items to return. + - type: 'null' + required: + - type + x-oaiMeta: + name: >- + The stored completions data source object used to configure an + individual run + group: eval runs + example: | + { + "type": "stored_completions", + "model": "gpt-4o", + "created_after": 1668124800, + "created_before": 1668124900, + "limit": 100, + "metadata": {} + } + FileExpirationAfter: + type: object + title: File expiration policy + description: >- + The expiration policy for a file. By default, files with `purpose=batch` + expire after 30 days and all other files are persisted until they are + manually deleted. + properties: + anchor: + description: >- + Anchor timestamp after which the expiration policy applies. + Supported anchors: `created_at`. + type: string + enum: + - created_at + x-stainless-const: true + seconds: + description: >- + The number of seconds after the anchor time that the file will + expire. Must be between 3600 (1 hour) and 2592000 (30 days). + type: integer + minimum: 3600 + maximum: 2592000 + required: + - anchor + - seconds + FilePath: + type: object + title: File path + description: | + A path to a file. + properties: + type: + type: string + description: | + The type of the file path. Always `file_path`. + enum: + - file_path + x-stainless-const: true + file_id: + type: string + description: | + The ID of the file. + index: + type: integer + description: | + The index of the file in the list of files. + required: + - type + - file_id + - index + FileSearchRanker: + type: string + description: >- + The ranker to use for the file search. If not specified will use the + `auto` ranker. + enum: + - auto + - default_2024_08_21 + FileSearchRankingOptions: + title: File search tool call ranking options + type: object + description: > + The ranking options for the file search. If not specified, the file + search tool will use the `auto` ranker and a score_threshold of 0. + + + See the [file search tool + documentation](/docs/assistants/tools/file-search#customizing-file-search-settings) + for more information. + properties: + ranker: + $ref: '#/components/schemas/FileSearchRanker' + score_threshold: + type: number + description: >- + The score threshold for the file search. All values must be a + floating point number between 0 and 1. + minimum: 0 + maximum: 1 + required: + - score_threshold + FileSearchToolCall: + type: object + title: File search tool call + description: > + The results of a file search tool call. See the + + [file search guide](/docs/guides/tools-file-search) for more + information. + properties: + id: + type: string + description: | + The unique ID of the file search tool call. + type: + type: string + enum: + - file_search_call + description: | + The type of the file search tool call. Always `file_search_call`. + x-stainless-const: true + status: + type: string + description: | + The status of the file search tool call. One of `in_progress`, + `searching`, `incomplete` or `failed`, + enum: + - in_progress + - searching + - completed + - incomplete + - failed + queries: + type: array + items: + type: string + description: | + The queries used to search for files. + results: + anyOf: + - type: array + description: | + The results of the file search tool call. + items: + type: object + properties: + file_id: + type: string + description: | + The unique ID of the file. + text: + type: string + description: | + The text that was retrieved from the file. + filename: + type: string + description: | + The name of the file. + attributes: + $ref: '#/components/schemas/VectorStoreFileAttributes' + score: + type: number + format: float + description: | + The relevance score of the file - a value between 0 and 1. + - type: 'null' + required: + - id + - type + - status + - queries + FineTuneChatCompletionRequestAssistantMessage: + allOf: + - type: object + title: Assistant message + deprecated: false + properties: + weight: + type: integer + enum: + - 0 + - 1 + description: >- + Controls whether the assistant message is trained against (0 or + 1) + - $ref: '#/components/schemas/ChatCompletionRequestAssistantMessage' + required: + - role + FineTuneDPOHyperparameters: + type: object + description: The hyperparameters used for the DPO fine-tuning job. + properties: + beta: + description: > + The beta value for the DPO method. A higher beta value will increase + the weight of the penalty between the policy and reference model. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: number + minimum: 0 + maximum: 2 + exclusiveMinimum: 0 + default: auto + batch_size: + description: > + Number of examples in each batch. A larger batch size means that + model parameters are updated less frequently, but with lower + variance. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 256 + default: auto + learning_rate_multiplier: + description: > + Scaling factor for the learning rate. A smaller learning rate may be + useful to avoid overfitting. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: number + minimum: 0 + exclusiveMinimum: 0 + default: auto + n_epochs: + description: > + The number of epochs to train the model for. An epoch refers to one + full cycle through the training dataset. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 50 + default: auto + FineTuneDPOMethod: + type: object + description: Configuration for the DPO fine-tuning method. + properties: + hyperparameters: + $ref: '#/components/schemas/FineTuneDPOHyperparameters' + FineTuneMethod: + type: object + description: The method used for fine-tuning. + properties: + type: + type: string + description: >- + The type of method. Is either `supervised`, `dpo`, or + `reinforcement`. + enum: + - supervised + - dpo + - reinforcement + supervised: + $ref: '#/components/schemas/FineTuneSupervisedMethod' + dpo: + $ref: '#/components/schemas/FineTuneDPOMethod' + reinforcement: + $ref: '#/components/schemas/FineTuneReinforcementMethod' + required: + - type + FineTuneReinforcementHyperparameters: + type: object + description: The hyperparameters used for the reinforcement fine-tuning job. + properties: + batch_size: + description: > + Number of examples in each batch. A larger batch size means that + model parameters are updated less frequently, but with lower + variance. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 256 + default: auto + learning_rate_multiplier: + description: > + Scaling factor for the learning rate. A smaller learning rate may be + useful to avoid overfitting. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: number + minimum: 0 + exclusiveMinimum: 0 + default: auto + n_epochs: + description: > + The number of epochs to train the model for. An epoch refers to one + full cycle through the training dataset. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 50 + default: auto + reasoning_effort: + description: | + Level of reasoning effort. + type: string + enum: + - default + - low + - medium + - high + default: default + compute_multiplier: + description: > + Multiplier on amount of compute used for exploring search space + during training. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: number + minimum: 0.00001 + maximum: 10 + exclusiveMinimum: 10 + default: auto + eval_interval: + description: | + The number of training steps between evaluation runs. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + default: auto + eval_samples: + description: | + Number of evaluation samples to generate per training step. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + default: auto + FineTuneReinforcementMethod: + type: object + description: Configuration for the reinforcement fine-tuning method. + properties: + grader: + type: object + description: The grader used for the fine-tuning job. + oneOf: + - $ref: '#/components/schemas/GraderStringCheck' + - $ref: '#/components/schemas/GraderTextSimilarity' + - $ref: '#/components/schemas/GraderPython' + - $ref: '#/components/schemas/GraderScoreModel' + - $ref: '#/components/schemas/GraderMulti' + hyperparameters: + $ref: '#/components/schemas/FineTuneReinforcementHyperparameters' + required: + - grader + FineTuneSupervisedHyperparameters: + type: object + description: The hyperparameters used for the fine-tuning job. + properties: + batch_size: + description: > + Number of examples in each batch. A larger batch size means that + model parameters are updated less frequently, but with lower + variance. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 256 + default: auto + learning_rate_multiplier: + description: > + Scaling factor for the learning rate. A smaller learning rate may be + useful to avoid overfitting. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: number + minimum: 0 + exclusiveMinimum: 0 + default: auto + n_epochs: + description: > + The number of epochs to train the model for. An epoch refers to one + full cycle through the training dataset. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 50 + default: auto + FineTuneSupervisedMethod: + type: object + description: Configuration for the supervised fine-tuning method. + properties: + hyperparameters: + $ref: '#/components/schemas/FineTuneSupervisedHyperparameters' + FineTuningCheckpointPermission: + type: object + title: FineTuningCheckpointPermission + description: > + The `checkpoint.permission` object represents a permission for a + fine-tuned model checkpoint. + properties: + id: + type: string + description: >- + The permission identifier, which can be referenced in the API + endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the permission was created. + project_id: + type: string + description: The project identifier that the permission is for. + object: + type: string + description: The object type, which is always "checkpoint.permission". + enum: + - checkpoint.permission + x-stainless-const: true + required: + - created_at + - id + - object + - project_id + x-oaiMeta: + name: The fine-tuned model checkpoint permission object + example: | + { + "object": "checkpoint.permission", + "id": "cp_zc4Q7MP6XxulcVzj4MZdwsAB", + "created_at": 1712211699, + "project_id": "proj_abGMw1llN8IrBb6SvvY5A1iH" + } + FineTuningIntegration: + type: object + title: Fine-Tuning Job Integration + required: + - type + - wandb + properties: + type: + type: string + description: The type of the integration being enabled for the fine-tuning job + enum: + - wandb + x-stainless-const: true + wandb: + type: object + description: > + The settings for your integration with Weights and Biases. This + payload specifies the project that + + metrics will be sent to. Optionally, you can set an explicit display + name for your run, add tags + + to your run, and set a default entity (team, username, etc) to be + associated with your run. + required: + - project + properties: + project: + description: | + The name of the project that the new run will be created under. + type: string + example: my-wandb-project + name: + anyOf: + - description: > + A display name to set for the run. If not set, we will use + the Job ID as the name. + type: string + - type: 'null' + entity: + anyOf: + - description: > + The entity to use for the run. This allows you to set the + team or username of the WandB user that you would + + like associated with the run. If not set, the default entity + for the registered WandB API key is used. + type: string + - type: 'null' + tags: + description: > + A list of tags to be attached to the newly created run. These + tags are passed through directly to WandB. Some + + default tags are generated by OpenAI: "openai/finetune", + "openai/{base-model}", "openai/{ftjob-abcdef}". + type: array + items: + type: string + example: custom-tag + FineTuningJob: + type: object + title: FineTuningJob + description: > + The `fine_tuning.job` object represents a fine-tuning job that has been + created through the API. + properties: + id: + type: string + description: The object identifier, which can be referenced in the API endpoints. + created_at: + type: integer + description: >- + The Unix timestamp (in seconds) for when the fine-tuning job was + created. + error: + anyOf: + - type: object + description: >- + For fine-tuning jobs that have `failed`, this will contain more + information on the cause of the failure. + properties: + code: + type: string + description: A machine-readable error code. + message: + type: string + description: A human-readable error message. + param: + anyOf: + - type: string + description: >- + The parameter that was invalid, usually `training_file` + or `validation_file`. This field will be null if the + failure was not parameter-specific. + - type: 'null' + required: + - code + - message + - param + - type: 'null' + fine_tuned_model: + anyOf: + - type: string + description: >- + The name of the fine-tuned model that is being created. The + value will be null if the fine-tuning job is still running. + - type: 'null' + finished_at: + anyOf: + - type: integer + description: >- + The Unix timestamp (in seconds) for when the fine-tuning job was + finished. The value will be null if the fine-tuning job is still + running. + - type: 'null' + hyperparameters: + type: object + description: >- + The hyperparameters used for the fine-tuning job. This value will + only be returned when running `supervised` jobs. + properties: + batch_size: + anyOf: + - description: > + Number of examples in each batch. A larger batch size means + that model parameters + + are updated less frequently, but with lower variance. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 256 + default: auto + - type: 'null' + learning_rate_multiplier: + description: > + Scaling factor for the learning rate. A smaller learning rate + may be useful to avoid + + overfitting. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: number + minimum: 0 + exclusiveMinimum: 0 + default: auto + n_epochs: + description: > + The number of epochs to train the model for. An epoch refers to + one full cycle + + through the training dataset. + oneOf: + - type: string + enum: + - auto + x-stainless-const: true + - type: integer + minimum: 1 + maximum: 50 + default: auto + model: + type: string + description: The base model that is being fine-tuned. + object: + type: string + description: The object type, which is always "fine_tuning.job". + enum: + - fine_tuning.job + x-stainless-const: true + organization_id: + type: string + description: The organization that owns the fine-tuning job. + result_files: + type: array + description: >- + The compiled results file ID(s) for the fine-tuning job. You can + retrieve the results with the [Files + API](/docs/api-reference/files/retrieve-contents). + items: + type: string + example: file-abc123 + status: + type: string + description: >- + The current status of the fine-tuning job, which can be either + `validating_files`, `queued`, `running`, `succeeded`, `failed`, or + `cancelled`. + enum: + - validating_files + - queued + - running + - succeeded + - failed + - cancelled + trained_tokens: + anyOf: + - type: integer + description: >- + The total number of billable tokens processed by this + fine-tuning job. The value will be null if the fine-tuning job + is still running. + - type: 'null' + training_file: + type: string + description: >- + The file ID used for training. You can retrieve the training data + with the [Files API](/docs/api-reference/files/retrieve-contents). + validation_file: + anyOf: + - type: string + description: >- + The file ID used for validation. You can retrieve the validation + results with the [Files + API](/docs/api-reference/files/retrieve-contents). + - type: 'null' + integrations: + anyOf: + - type: array + description: A list of integrations to enable for this fine-tuning job. + maxItems: 5 + items: + oneOf: + - $ref: '#/components/schemas/FineTuningIntegration' + - type: 'null' + seed: + type: integer + description: The seed used for the fine-tuning job. + estimated_finish: + anyOf: + - type: integer + description: >- + The Unix timestamp (in seconds) for when the fine-tuning job is + estimated to finish. The value will be null if the fine-tuning + job is not running. + - type: 'null' + method: + $ref: '#/components/schemas/FineTuneMethod' + metadata: + $ref: '#/components/schemas/Metadata' + required: + - created_at + - error + - finished_at + - fine_tuned_model + - hyperparameters + - id + - model + - object + - organization_id + - result_files + - status + - trained_tokens + - training_file + - validation_file + - seed + x-oaiMeta: + name: The fine-tuning job object + example: | + { + "object": "fine_tuning.job", + "id": "ftjob-abc123", + "model": "davinci-002", + "created_at": 1692661014, + "finished_at": 1692661190, + "fine_tuned_model": "ft:davinci-002:my-org:custom_suffix:7q8mpxmy", + "organization_id": "org-123", + "result_files": [ + "file-abc123" + ], + "status": "succeeded", + "validation_file": null, + "training_file": "file-abc123", + "hyperparameters": { + "n_epochs": 4, + "batch_size": 1, + "learning_rate_multiplier": 1.0 + }, + "trained_tokens": 5768, + "integrations": [], + "seed": 0, + "estimated_finish": 0, + "method": { + "type": "supervised", + "supervised": { + "hyperparameters": { + "n_epochs": 4, + "batch_size": 1, + "learning_rate_multiplier": 1.0 + } + } + }, + "metadata": { + "key": "value" + } + } + FineTuningJobCheckpoint: + type: object + title: FineTuningJobCheckpoint + description: > + The `fine_tuning.job.checkpoint` object represents a model checkpoint + for a fine-tuning job that is ready to use. + properties: + id: + type: string + description: >- + The checkpoint identifier, which can be referenced in the API + endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the checkpoint was created. + fine_tuned_model_checkpoint: + type: string + description: The name of the fine-tuned checkpoint model that is created. + step_number: + type: integer + description: The step number that the checkpoint was created at. + metrics: + type: object + description: Metrics at the step number during the fine-tuning job. + properties: + step: + type: number + train_loss: + type: number + train_mean_token_accuracy: + type: number + valid_loss: + type: number + valid_mean_token_accuracy: + type: number + full_valid_loss: + type: number + full_valid_mean_token_accuracy: + type: number + fine_tuning_job_id: + type: string + description: >- + The name of the fine-tuning job that this checkpoint was created + from. + object: + type: string + description: The object type, which is always "fine_tuning.job.checkpoint". + enum: + - fine_tuning.job.checkpoint + x-stainless-const: true + required: + - created_at + - fine_tuning_job_id + - fine_tuned_model_checkpoint + - id + - metrics + - object + - step_number + x-oaiMeta: + name: The fine-tuning job checkpoint object + example: | + { + "object": "fine_tuning.job.checkpoint", + "id": "ftckpt_qtZ5Gyk4BLq1SfLFWp3RtO3P", + "created_at": 1712211699, + "fine_tuned_model_checkpoint": "ft:gpt-4o-mini-2024-07-18:my-org:custom_suffix:9ABel2dg:ckpt-step-88", + "fine_tuning_job_id": "ftjob-fpbNQ3H1GrMehXRf8cO97xTN", + "metrics": { + "step": 88, + "train_loss": 0.478, + "train_mean_token_accuracy": 0.924, + "valid_loss": 10.112, + "valid_mean_token_accuracy": 0.145, + "full_valid_loss": 0.567, + "full_valid_mean_token_accuracy": 0.944 + }, + "step_number": 88 + } + FineTuningJobEvent: + type: object + description: Fine-tuning job event object + properties: + object: + type: string + description: The object type, which is always "fine_tuning.job.event". + enum: + - fine_tuning.job.event + x-stainless-const: true + id: + type: string + description: The object identifier. + created_at: + type: integer + description: >- + The Unix timestamp (in seconds) for when the fine-tuning job was + created. + level: + type: string + description: The log level of the event. + enum: + - info + - warn + - error + message: + type: string + description: The message of the event. + type: + type: string + description: The type of event. + enum: + - message + - metrics + data: + type: object + description: The data associated with the event. + required: + - id + - object + - created_at + - level + - message + x-oaiMeta: + name: The fine-tuning job event object + example: | + { + "object": "fine_tuning.job.event", + "id": "ftevent-abc123" + "created_at": 1677610602, + "level": "info", + "message": "Created fine-tuning job", + "data": {}, + "type": "message" + } + FunctionAndCustomToolCallOutput: + oneOf: + - $ref: '#/components/schemas/InputTextContent' + - $ref: '#/components/schemas/InputImageContent' + - $ref: '#/components/schemas/InputFileContent' + discriminator: + propertyName: type + FunctionObject: + type: object + properties: + description: + type: string + description: >- + A description of what the function does, used by the model to choose + when and how to call the function. + name: + type: string + description: >- + The name of the function to be called. Must be a-z, A-Z, 0-9, or + contain underscores and dashes, with a maximum length of 64. + parameters: + $ref: '#/components/schemas/FunctionParameters' + strict: + anyOf: + - type: boolean + default: false + description: >- + Whether to enable strict schema adherence when generating the + function call. If set to true, the model will follow the exact + schema defined in the `parameters` field. Only a subset of JSON + Schema is supported when `strict` is `true`. Learn more about + Structured Outputs in the [function calling + guide](/docs/guides/function-calling). + - type: 'null' + required: + - name + FunctionParameters: + type: object + description: >- + The parameters the functions accepts, described as a JSON Schema object. + See the [guide](/docs/guides/function-calling) for examples, and the + [JSON Schema + reference](https://json-schema.org/understanding-json-schema/) for + documentation about the format. + + + Omitting `parameters` defines a function with an empty parameter list. + additionalProperties: true + FunctionToolCall: + type: object + title: Function tool call + description: > + A tool call to run a function. See the + + [function calling guide](/docs/guides/function-calling) for more + information. + properties: + id: + type: string + description: | + The unique ID of the function tool call. + type: + type: string + enum: + - function_call + description: | + The type of the function tool call. Always `function_call`. + x-stainless-const: true + call_id: + type: string + description: | + The unique ID of the function tool call generated by the model. + namespace: + type: string + description: | + The namespace of the function to run. + name: + type: string + description: | + The name of the function to run. + arguments: + type: string + description: | + A JSON string of the arguments to pass to the function. + status: + type: string + description: | + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + enum: + - in_progress + - completed + - incomplete + required: + - type + - call_id + - name + - arguments + FunctionToolCallOutput: + type: object + title: Function tool call output + description: | + The output of a function tool call. + properties: + id: + type: string + description: > + The unique ID of the function tool call output. Populated when this + item + + is returned via API. + type: + type: string + enum: + - function_call_output + description: > + The type of the function tool call output. Always + `function_call_output`. + x-stainless-const: true + call_id: + type: string + description: | + The unique ID of the function tool call generated by the model. + output: + description: | + The output from the function call generated by your code. + Can be a string or an list of output content. + oneOf: + - type: string + description: | + A string of the output of the function call. + title: string output + - type: array + items: + $ref: '#/components/schemas/FunctionAndCustomToolCallOutput' + title: output content list + description: | + Text, image, or file output of the function call. + status: + type: string + description: | + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + enum: + - in_progress + - completed + - incomplete + required: + - type + - call_id + - output + FunctionToolCallOutputResource: + allOf: + - $ref: '#/components/schemas/FunctionToolCallOutput' + - type: object + properties: + id: + type: string + description: | + The unique ID of the function call tool output. + status: + description: | + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + $ref: '#/components/schemas/FunctionCallOutputStatusEnum' + created_by: + type: string + description: | + The identifier of the actor that created the item. + required: + - id + - status + FunctionToolCallResource: + allOf: + - $ref: '#/components/schemas/FunctionToolCall' + - type: object + properties: + id: + type: string + description: | + The unique ID of the function tool call. + status: + description: | + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + $ref: '#/components/schemas/FunctionCallStatus' + created_by: + type: string + description: | + The identifier of the actor that created the item. + required: + - id + - status + GraderLabelModel: + type: object + title: LabelModelGrader + description: > + A LabelModelGrader object which uses a model to assign labels to each + item + + in the evaluation. + properties: + type: + description: The object type, which is always `label_model`. + type: string + enum: + - label_model + x-stainless-const: true + name: + type: string + description: The name of the grader. + model: + type: string + description: >- + The model to use for the evaluation. Must support structured + outputs. + input: + type: array + items: + $ref: '#/components/schemas/EvalItem' + labels: + type: array + items: + type: string + description: The labels to assign to each item in the evaluation. + passing_labels: + type: array + items: + type: string + description: >- + The labels that indicate a passing result. Must be a subset of + labels. + required: + - type + - model + - input + - passing_labels + - labels + - name + x-oaiMeta: + name: Label Model Grader + group: graders + example: | + { + "name": "First label grader", + "type": "label_model", + "model": "gpt-4o-2024-08-06", + "input": [ + { + "type": "message", + "role": "system", + "content": { + "type": "input_text", + "text": "Classify the sentiment of the following statement as one of positive, neutral, or negative" + } + }, + { + "type": "message", + "role": "user", + "content": { + "type": "input_text", + "text": "Statement: {{item.response}}" + } + } + ], + "passing_labels": [ + "positive" + ], + "labels": [ + "positive", + "neutral", + "negative" + ] + } + GraderMulti: + type: object + title: MultiGrader + description: >- + A MultiGrader object combines the output of multiple graders to produce + a single score. + properties: + type: + type: string + enum: + - multi + default: multi + description: The object type, which is always `multi`. + x-stainless-const: true + name: + type: string + description: The name of the grader. + graders: + oneOf: + - $ref: '#/components/schemas/GraderStringCheck' + - $ref: '#/components/schemas/GraderTextSimilarity' + - $ref: '#/components/schemas/GraderPython' + - $ref: '#/components/schemas/GraderScoreModel' + - $ref: '#/components/schemas/GraderLabelModel' + calculate_output: + type: string + description: A formula to calculate the output based on grader results. + required: + - name + - type + - graders + - calculate_output + x-oaiMeta: + name: Multi Grader + group: graders + example: | + { + "type": "multi", + "name": "example multi grader", + "graders": [ + { + "type": "text_similarity", + "name": "example text similarity grader", + "input": "The graded text", + "reference": "The reference text", + "evaluation_metric": "fuzzy_match" + }, + { + "type": "string_check", + "name": "Example string check grader", + "input": "{{sample.output_text}}", + "reference": "{{item.label}}", + "operation": "eq" + } + ], + "calculate_output": "0.5 * text_similarity_score + 0.5 * string_check_score)" + } + GraderPython: + type: object + title: PythonGrader + description: | + A PythonGrader object that runs a python script on the input. + properties: + type: + type: string + enum: + - python + description: The object type, which is always `python`. + x-stainless-const: true + name: + type: string + description: The name of the grader. + source: + type: string + description: The source code of the python script. + image_tag: + type: string + description: The image tag to use for the python script. + required: + - type + - name + - source + x-oaiMeta: + name: Python Grader + group: graders + example: | + { + "type": "python", + "name": "Example python grader", + "image_tag": "2025-05-08", + "source": """ + def grade(sample: dict, item: dict) -> float: + \""" + Returns 1.0 if `output_text` equals `label`, otherwise 0.0. + \""" + output = sample.get("output_text") + label = item.get("label") + return 1.0 if output == label else 0.0 + """, + } + GraderScoreModel: + type: object + title: ScoreModelGrader + description: > + A ScoreModelGrader object that uses a model to assign a score to the + input. + properties: + type: + type: string + enum: + - score_model + description: The object type, which is always `score_model`. + x-stainless-const: true + name: + type: string + description: The name of the grader. + model: + type: string + description: The model to use for the evaluation. + sampling_params: + type: object + description: The sampling parameters for the model. + properties: + seed: + anyOf: + - type: integer + description: | + A seed value to initialize the randomness, during sampling. + - type: 'null' + top_p: + anyOf: + - type: number + default: 1 + example: 1 + description: > + An alternative to temperature for nucleus sampling; 1.0 + includes all tokens. + - type: 'null' + temperature: + anyOf: + - type: number + description: | + A higher temperature increases randomness in the outputs. + - type: 'null' + max_completions_tokens: + anyOf: + - type: integer + minimum: 1 + description: > + The maximum number of tokens the grader model may generate + in its response. + - type: 'null' + reasoning_effort: + $ref: '#/components/schemas/ReasoningEffort' + input: + type: array + items: + $ref: '#/components/schemas/EvalItem' + description: > + The input messages evaluated by the grader. Supports text, output + text, input image, and input audio content blocks, and may include + template strings. + range: + type: array + items: + type: number + min_items: 2 + max_items: 2 + description: The range of the score. Defaults to `[0, 1]`. + required: + - type + - name + - input + - model + x-oaiMeta: + name: Score Model Grader + group: graders + example: | + { + "type": "score_model", + "name": "Example score model grader", + "input": [ + { + "role": "user", + "content": [ + { + "type": "input_text", + "text": ( + "Score how close the reference answer is to the model answer. Score 1.0 if they are the same and 0.0 if they are different." + " Return just a floating point score\n\n" + " Reference answer: {{item.label}}\n\n" + " Model answer: {{sample.output_text}}" + ) + }, + { + "type": "input_image", + "image_url": "https://example.com/reference.png", + "file_id": null, + "detail": "auto" + } + ], + } + ], + "model": "gpt-5-mini", + "sampling_params": { + "temperature": 1, + "top_p": 1, + "seed": 42, + "max_completions_tokens": 32768, + "reasoning_effort": "medium" + }, + } + GraderStringCheck: + type: object + title: StringCheckGrader + description: > + A StringCheckGrader object that performs a string comparison between + input and reference using a specified operation. + properties: + type: + type: string + enum: + - string_check + description: The object type, which is always `string_check`. + x-stainless-const: true + name: + type: string + description: The name of the grader. + input: + type: string + description: The input text. This may include template strings. + reference: + type: string + description: The reference text. This may include template strings. + operation: + type: string + enum: + - eq + - ne + - like + - ilike + description: >- + The string check operation to perform. One of `eq`, `ne`, `like`, or + `ilike`. + required: + - type + - name + - input + - reference + - operation + x-oaiMeta: + name: String Check Grader + group: graders + example: | + { + "type": "string_check", + "name": "Example string check grader", + "input": "{{sample.output_text}}", + "reference": "{{item.label}}", + "operation": "eq" + } + GraderTextSimilarity: + type: object + title: TextSimilarityGrader + description: > + A TextSimilarityGrader object which grades text based on similarity + metrics. + properties: + type: + type: string + enum: + - text_similarity + default: text_similarity + description: The type of grader. + x-stainless-const: true + name: + type: string + description: The name of the grader. + input: + type: string + description: The text being graded. + reference: + type: string + description: The text being graded against. + evaluation_metric: + type: string + enum: + - cosine + - fuzzy_match + - bleu + - gleu + - meteor + - rouge_1 + - rouge_2 + - rouge_3 + - rouge_4 + - rouge_5 + - rouge_l + description: > + The evaluation metric to use. One of `cosine`, `fuzzy_match`, + `bleu`, + + `gleu`, `meteor`, `rouge_1`, `rouge_2`, `rouge_3`, `rouge_4`, + `rouge_5`, + + or `rouge_l`. + required: + - type + - name + - input + - reference + - evaluation_metric + x-oaiMeta: + name: Text Similarity Grader + group: graders + example: | + { + "type": "text_similarity", + "name": "Example text similarity grader", + "input": "{{sample.output_text}}", + "reference": "{{item.label}}", + "evaluation_metric": "fuzzy_match" + } + Group: + type: object + description: Summary information about a group returned in role assignment responses. + properties: + object: + type: string + enum: + - group + description: Always `group`. + x-stainless-const: true + id: + type: string + description: Identifier for the group. + name: + type: string + description: Display name of the group. + created_at: + type: integer + format: int64 + description: Unix timestamp (in seconds) when the group was created. + scim_managed: + type: boolean + description: Whether the group is managed through SCIM. + required: + - object + - id + - name + - created_at + - scim_managed + x-oaiMeta: + name: The group object + example: | + { + "object": "group", + "id": "group_01J1F8ABCDXYZ", + "name": "Support Team", + "created_at": 1711471533, + "scim_managed": false + } + GroupDeletedResource: + type: object + description: Confirmation payload returned after deleting a group. + properties: + object: + type: string + enum: + - group.deleted + description: Always `group.deleted`. + x-stainless-const: true + id: + type: string + description: Identifier of the deleted group. + deleted: + type: boolean + description: Whether the group was deleted. + required: + - object + - id + - deleted + x-oaiMeta: + example: | + { + "object": "group.deleted", + "id": "group_01J1F8ABCDXYZ", + "deleted": true + } + GroupListResource: + type: object + description: Paginated list of organization groups. + properties: + object: + type: string + enum: + - list + description: Always `list`. + x-stainless-const: true + data: + type: array + description: Groups returned in the current page. + items: + $ref: '#/components/schemas/GroupResponse' + has_more: + type: boolean + description: Whether additional groups are available when paginating. + next: + description: >- + Cursor to fetch the next page of results, or `null` if there are no + more results. + anyOf: + - type: string + - type: 'null' + required: + - object + - data + - has_more + - next + x-oaiMeta: + name: Group list + example: | + { + "object": "list", + "data": [ + { + "id": "group_01J1F8ABCDXYZ", + "name": "Support Team", + "created_at": 1711471533, + "is_scim_managed": false + }, + { + "id": "group_01J1F8PQRMNO", + "name": "Sales", + "created_at": 1711472599, + "is_scim_managed": true + } + ], + "has_more": false, + "next": null + } + GroupResourceWithSuccess: + type: object + description: Response returned after updating a group. + properties: + id: + type: string + description: Identifier for the group. + name: + type: string + description: Updated display name for the group. + created_at: + type: integer + format: int64 + description: Unix timestamp (in seconds) when the group was created. + is_scim_managed: + type: boolean + description: >- + Whether the group is managed through SCIM and controlled by your + identity provider. + required: + - id + - name + - created_at + - is_scim_managed + x-oaiMeta: + example: | + { + "id": "group_01J1F8ABCDXYZ", + "name": "Escalations", + "created_at": 1711471533, + "is_scim_managed": false + } + GroupResponse: + type: object + description: Details about an organization group. + properties: + id: + type: string + description: Identifier for the group. + name: + type: string + description: Display name of the group. + created_at: + type: integer + format: int64 + description: Unix timestamp (in seconds) when the group was created. + is_scim_managed: + type: boolean + description: >- + Whether the group is managed through SCIM and controlled by your + identity provider. + required: + - id + - name + - created_at + - is_scim_managed + x-oaiMeta: + name: Group + example: | + { + "id": "group_01J1F8ABCDXYZ", + "name": "Support Team", + "created_at": 1711471533, + "is_scim_managed": false + } + GroupRoleAssignment: + type: object + description: Role assignment linking a group to a role. + properties: + object: + type: string + enum: + - group.role + description: Always `group.role`. + x-stainless-const: true + group: + $ref: '#/components/schemas/Group' + role: + $ref: '#/components/schemas/Role' + required: + - object + - group + - role + x-oaiMeta: + name: The group role object + example: | + { + "object": "group.role", + "group": { + "object": "group", + "id": "group_01J1F8ABCDXYZ", + "name": "Support Team", + "created_at": 1711471533, + "scim_managed": false + }, + "role": { + "object": "role", + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "description": "Allows managing organization groups", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false + } + } + GroupUserAssignment: + type: object + description: Confirmation payload returned after adding a user to a group. + properties: + object: + type: string + enum: + - group.user + description: Always `group.user`. + x-stainless-const: true + user_id: + type: string + description: Identifier of the user that was added. + group_id: + type: string + description: Identifier of the group the user was added to. + required: + - object + - user_id + - group_id + x-oaiMeta: + name: The group user object + example: | + { + "object": "group.user", + "user_id": "user_abc123", + "group_id": "group_01J1F8ABCDXYZ" + } + GroupUserDeletedResource: + type: object + description: Confirmation payload returned after removing a user from a group. + properties: + object: + type: string + enum: + - group.user.deleted + description: Always `group.user.deleted`. + x-stainless-const: true + deleted: + type: boolean + description: Whether the group membership was removed. + required: + - object + - deleted + x-oaiMeta: + name: Group user deletion confirmation + example: | + { + "object": "group.user.deleted", + "deleted": true + } + Image: + type: object + description: >- + Represents the content or the URL of an image generated by the OpenAI + API. + properties: + b64_json: + type: string + description: >- + The base64-encoded JSON of the generated image. Returned by default + for the GPT image models, and only present if `response_format` is + set to `b64_json` for `dall-e-2` and `dall-e-3`. + url: + type: string + description: >- + When using `dall-e-2` or `dall-e-3`, the URL of the generated image + if `response_format` is set to `url` (default value). Unsupported + for the GPT image models. + revised_prompt: + type: string + description: >- + For `dall-e-3` only, the revised prompt that was used to generate + the image. + ImageEditCompletedEvent: + type: object + description: > + Emitted when image editing has completed and the final image is + available. + properties: + type: + type: string + description: | + The type of the event. Always `image_edit.completed`. + enum: + - image_edit.completed + x-stainless-const: true + b64_json: + type: string + description: > + Base64-encoded final edited image data, suitable for rendering as an + image. + created_at: + type: integer + description: | + The Unix timestamp when the event was created. + size: + type: string + description: | + The size of the edited image. + enum: + - 1024x1024 + - 1024x1536 + - 1536x1024 + - auto + quality: + type: string + description: | + The quality setting for the edited image. + enum: + - low + - medium + - high + - auto + background: + type: string + description: | + The background setting for the edited image. + enum: + - transparent + - opaque + - auto + output_format: + type: string + description: | + The output format for the edited image. + enum: + - png + - webp + - jpeg + usage: + $ref: '#/components/schemas/ImagesUsage' + required: + - type + - b64_json + - created_at + - size + - quality + - background + - output_format + - usage + x-oaiMeta: + name: image_edit.completed + group: images + example: | + { + "type": "image_edit.completed", + "b64_json": "...", + "created_at": 1620000000, + "size": "1024x1024", + "quality": "high", + "background": "transparent", + "output_format": "png", + "usage": { + "total_tokens": 100, + "input_tokens": 50, + "output_tokens": 50, + "input_tokens_details": { + "text_tokens": 10, + "image_tokens": 40 + } + } + } + ImageEditPartialImageEvent: + type: object + description: > + Emitted when a partial image is available during image editing + streaming. + properties: + type: + type: string + description: | + The type of the event. Always `image_edit.partial_image`. + enum: + - image_edit.partial_image + x-stainless-const: true + b64_json: + type: string + description: > + Base64-encoded partial image data, suitable for rendering as an + image. + created_at: + type: integer + description: | + The Unix timestamp when the event was created. + size: + type: string + description: | + The size of the requested edited image. + enum: + - 1024x1024 + - 1024x1536 + - 1536x1024 + - auto + quality: + type: string + description: | + The quality setting for the requested edited image. + enum: + - low + - medium + - high + - auto + background: + type: string + description: | + The background setting for the requested edited image. + enum: + - transparent + - opaque + - auto + output_format: + type: string + description: | + The output format for the requested edited image. + enum: + - png + - webp + - jpeg + partial_image_index: + type: integer + description: | + 0-based index for the partial image (streaming). + required: + - type + - b64_json + - created_at + - size + - quality + - background + - output_format + - partial_image_index + x-oaiMeta: + name: image_edit.partial_image + group: images + example: | + { + "type": "image_edit.partial_image", + "b64_json": "...", + "created_at": 1620000000, + "size": "1024x1024", + "quality": "high", + "background": "transparent", + "output_format": "png", + "partial_image_index": 0 + } + ImageEditStreamEvent: + anyOf: + - $ref: '#/components/schemas/ImageEditPartialImageEvent' + - $ref: '#/components/schemas/ImageEditCompletedEvent' + discriminator: + propertyName: type + ImageGenCompletedEvent: + type: object + description: > + Emitted when image generation has completed and the final image is + available. + properties: + type: + type: string + description: | + The type of the event. Always `image_generation.completed`. + enum: + - image_generation.completed + x-stainless-const: true + b64_json: + type: string + description: | + Base64-encoded image data, suitable for rendering as an image. + created_at: + type: integer + description: | + The Unix timestamp when the event was created. + size: + type: string + description: | + The size of the generated image. + enum: + - 1024x1024 + - 1024x1536 + - 1536x1024 + - auto + quality: + type: string + description: | + The quality setting for the generated image. + enum: + - low + - medium + - high + - auto + background: + type: string + description: | + The background setting for the generated image. + enum: + - transparent + - opaque + - auto + output_format: + type: string + description: | + The output format for the generated image. + enum: + - png + - webp + - jpeg + usage: + $ref: '#/components/schemas/ImagesUsage' + required: + - type + - b64_json + - created_at + - size + - quality + - background + - output_format + - usage + x-oaiMeta: + name: image_generation.completed + group: images + example: | + { + "type": "image_generation.completed", + "b64_json": "...", + "created_at": 1620000000, + "size": "1024x1024", + "quality": "high", + "background": "transparent", + "output_format": "png", + "usage": { + "total_tokens": 100, + "input_tokens": 50, + "output_tokens": 50, + "input_tokens_details": { + "text_tokens": 10, + "image_tokens": 40 + } + } + } + ImageGenPartialImageEvent: + type: object + description: > + Emitted when a partial image is available during image generation + streaming. + properties: + type: + type: string + description: | + The type of the event. Always `image_generation.partial_image`. + enum: + - image_generation.partial_image + x-stainless-const: true + b64_json: + type: string + description: > + Base64-encoded partial image data, suitable for rendering as an + image. + created_at: + type: integer + description: | + The Unix timestamp when the event was created. + size: + type: string + description: | + The size of the requested image. + enum: + - 1024x1024 + - 1024x1536 + - 1536x1024 + - auto + quality: + type: string + description: | + The quality setting for the requested image. + enum: + - low + - medium + - high + - auto + background: + type: string + description: | + The background setting for the requested image. + enum: + - transparent + - opaque + - auto + output_format: + type: string + description: | + The output format for the requested image. + enum: + - png + - webp + - jpeg + partial_image_index: + type: integer + description: | + 0-based index for the partial image (streaming). + required: + - type + - b64_json + - created_at + - size + - quality + - background + - output_format + - partial_image_index + x-oaiMeta: + name: image_generation.partial_image + group: images + example: | + { + "type": "image_generation.partial_image", + "b64_json": "...", + "created_at": 1620000000, + "size": "1024x1024", + "quality": "high", + "background": "transparent", + "output_format": "png", + "partial_image_index": 0 + } + ImageGenStreamEvent: + anyOf: + - $ref: '#/components/schemas/ImageGenPartialImageEvent' + - $ref: '#/components/schemas/ImageGenCompletedEvent' + discriminator: + propertyName: type + ImageGenTool: + type: object + title: Image generation tool + description: | + A tool that generates images using the GPT image models. + properties: + type: + type: string + enum: + - image_generation + description: | + The type of the image generation tool. Always `image_generation`. + x-stainless-const: true + model: + anyOf: + - type: string + - type: string + enum: + - gpt-image-1 + - gpt-image-1-mini + - gpt-image-1.5 + description: | + The image generation model to use. Default: `gpt-image-1`. + default: gpt-image-1 + quality: + type: string + enum: + - low + - medium + - high + - auto + description: | + The quality of the generated image. One of `low`, `medium`, `high`, + or `auto`. Default: `auto`. + default: auto + size: + type: string + enum: + - 1024x1024 + - 1024x1536 + - 1536x1024 + - auto + description: | + The size of the generated image. One of `1024x1024`, `1024x1536`, + `1536x1024`, or `auto`. Default: `auto`. + default: auto + output_format: + type: string + enum: + - png + - webp + - jpeg + description: | + The output format of the generated image. One of `png`, `webp`, or + `jpeg`. Default: `png`. + default: png + output_compression: + type: integer + minimum: 0 + maximum: 100 + description: | + Compression level for the output image. Default: 100. + default: 100 + moderation: + type: string + enum: + - auto + - low + description: | + Moderation level for the generated image. Default: `auto`. + default: auto + background: + type: string + enum: + - transparent + - opaque + - auto + description: | + Background type for the generated image. One of `transparent`, + `opaque`, or `auto`. Default: `auto`. + default: auto + input_fidelity: + anyOf: + - $ref: '#/components/schemas/InputFidelity' + - type: 'null' + input_image_mask: + type: object + description: | + Optional mask for inpainting. Contains `image_url` + (string, optional) and `file_id` (string, optional). + properties: + image_url: + type: string + description: | + Base64-encoded mask image. + file_id: + type: string + description: | + File ID for the mask image. + required: [] + additionalProperties: false + partial_images: + type: integer + minimum: 0 + maximum: 3 + description: > + Number of partial images to generate in streaming mode, from 0 + (default value) to 3. + default: 0 + action: + description: > + Whether to generate a new image or edit an existing image. Default: + `auto`. + $ref: '#/components/schemas/ImageGenActionEnum' + required: + - type + ImageGenToolCall: + type: object + title: Image generation call + description: | + An image generation request made by the model. + properties: + type: + type: string + enum: + - image_generation_call + description: > + The type of the image generation call. Always + `image_generation_call`. + x-stainless-const: true + id: + type: string + description: | + The unique ID of the image generation call. + status: + type: string + enum: + - in_progress + - completed + - generating + - failed + description: | + The status of the image generation call. + result: + anyOf: + - type: string + description: | + The generated image encoded in base64. + - type: 'null' + required: + - type + - id + - status + - result + ImageRefParam: + type: object + description: | + Reference an input image by either URL or uploaded file ID. + Provide exactly one of `image_url` or `file_id`. + properties: + image_url: + type: string + maxLength: 20971520 + description: A fully qualified URL or base64-encoded data URL. + example: https://example.com/source-image.png + file_id: + type: string + description: The File API ID of an uploaded image to use as input. + example: file-abc123 + anyOf: + - required: + - image_url + - required: + - file_id + not: + required: + - image_url + - file_id + additionalProperties: false + ImagesResponse: + type: object + title: Image generation response + description: The response from the image generation endpoint. + properties: + created: + type: integer + description: The Unix timestamp (in seconds) of when the image was created. + data: + type: array + description: The list of generated images. + items: + $ref: '#/components/schemas/Image' + background: + type: string + description: >- + The background parameter used for the image generation. Either + `transparent` or `opaque`. + enum: + - transparent + - opaque + output_format: + type: string + description: >- + The output format of the image generation. Either `png`, `webp`, or + `jpeg`. + enum: + - png + - webp + - jpeg + size: + type: string + description: >- + The size of the image generated. Either `1024x1024`, `1024x1536`, or + `1536x1024`. + enum: + - 1024x1024 + - 1024x1536 + - 1536x1024 + quality: + type: string + description: >- + The quality of the image generated. Either `low`, `medium`, or + `high`. + enum: + - low + - medium + - high + usage: + $ref: '#/components/schemas/ImageGenUsage' + required: + - created + x-oaiMeta: + name: The image generation response + group: images + example: | + { + "created": 1713833628, + "data": [ + { + "b64_json": "..." + } + ], + "background": "transparent", + "output_format": "png", + "size": "1024x1024", + "quality": "high", + "usage": { + "total_tokens": 100, + "input_tokens": 50, + "output_tokens": 50, + "input_tokens_details": { + "text_tokens": 10, + "image_tokens": 40 + } + } + } + ImagesUsage: + type: object + description: > + For the GPT image models only, the token usage information for the image + generation. + required: + - total_tokens + - input_tokens + - output_tokens + - input_tokens_details + properties: + total_tokens: + type: integer + description: > + The total number of tokens (images and text) used for the image + generation. + input_tokens: + type: integer + description: The number of tokens (images and text) in the input prompt. + output_tokens: + type: integer + description: The number of image tokens in the output image. + input_tokens_details: + type: object + description: The input tokens detailed information for the image generation. + required: + - text_tokens + - image_tokens + properties: + text_tokens: + type: integer + description: The number of text tokens in the input prompt. + image_tokens: + type: integer + description: The number of image tokens in the input prompt. + InputAudio: + type: object + title: Input audio + description: | + An audio input to the model. + properties: + type: + type: string + description: | + The type of the input item. Always `input_audio`. + enum: + - input_audio + x-stainless-const: true + input_audio: + type: object + properties: + data: + type: string + description: | + Base64-encoded audio data. + format: + type: string + description: > + The format of the audio data. Currently supported formats are + `mp3` and + + `wav`. + enum: + - mp3 + - wav + required: + - data + - format + required: + - type + - input_audio + InputContent: + oneOf: + - $ref: '#/components/schemas/InputTextContent' + - $ref: '#/components/schemas/InputImageContent' + - $ref: '#/components/schemas/InputFileContent' + discriminator: + propertyName: type + InputItem: + oneOf: + - $ref: '#/components/schemas/EasyInputMessage' + - type: object + title: Item + description: | + An item representing part of the context for the response to be + generated by the model. Can contain text, images, and audio inputs, + as well as previous assistant responses and tool call outputs. + $ref: '#/components/schemas/Item' + - $ref: '#/components/schemas/ItemReferenceParam' + discriminator: + propertyName: type + InputMessage: + type: object + title: Input message + description: > + A message input to the model with a role indicating instruction + following + + hierarchy. Instructions given with the `developer` or `system` role take + + precedence over instructions given with the `user` role. + properties: + type: + type: string + description: | + The type of the message input. Always set to `message`. + enum: + - message + x-stainless-const: true + role: + type: string + description: > + The role of the message input. One of `user`, `system`, or + `developer`. + enum: + - user + - system + - developer + status: + type: string + description: | + The status of item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + enum: + - in_progress + - completed + - incomplete + content: + $ref: '#/components/schemas/InputMessageContentList' + required: + - role + - content + InputMessageContentList: + type: array + title: Input item content list + description: > + A list of one or many input items to the model, containing different + content + + types. + items: + $ref: '#/components/schemas/InputContent' + InputMessageResource: + allOf: + - $ref: '#/components/schemas/InputMessage' + - type: object + properties: + id: + type: string + description: | + The unique ID of the message input. + required: + - id + - type + InputParam: + description: | + Text, image, or file inputs to the model, used to generate a response. + + Learn more: + - [Text inputs and outputs](/docs/guides/text) + - [Image inputs](/docs/guides/images) + - [File inputs](/docs/guides/pdf-files) + - [Conversation state](/docs/guides/conversation-state) + - [Function calling](/docs/guides/function-calling) + oneOf: + - type: string + title: Text input + description: | + A text input to the model, equivalent to a text input with the + `user` role. + - type: array + title: Input item list + description: | + A list of one or many input items to the model, containing + different content types. + items: + $ref: '#/components/schemas/InputItem' + Invite: + type: object + description: Represents an individual `invite` to the organization. + properties: + object: + type: string + enum: + - organization.invite + description: The object type, which is always `organization.invite` + x-stainless-const: true + id: + type: string + description: The identifier, which can be referenced in API endpoints + email: + type: string + description: The email address of the individual to whom the invite was sent + role: + type: string + enum: + - owner + - reader + description: '`owner` or `reader`' + status: + type: string + enum: + - accepted + - expired + - pending + description: '`accepted`,`expired`, or `pending`' + invited_at: + type: integer + description: The Unix timestamp (in seconds) of when the invite was sent. + expires_at: + type: integer + description: The Unix timestamp (in seconds) of when the invite expires. + accepted_at: + type: integer + description: The Unix timestamp (in seconds) of when the invite was accepted. + projects: + type: array + description: >- + The projects that were granted membership upon acceptance of the + invite. + items: + type: object + properties: + id: + type: string + description: Project's public ID + role: + type: string + enum: + - member + - owner + description: Project membership role + required: + - object + - id + - email + - role + - status + - invited_at + - expires_at + x-oaiMeta: + name: The invite object + example: | + { + "object": "organization.invite", + "id": "invite-abc", + "email": "user@example.com", + "role": "owner", + "status": "accepted", + "invited_at": 1711471533, + "expires_at": 1711471533, + "accepted_at": 1711471533, + "projects": [ + { + "id": "project-xyz", + "role": "member" + } + ] + } + InviteDeleteResponse: + type: object + properties: + object: + type: string + enum: + - organization.invite.deleted + description: The object type, which is always `organization.invite.deleted` + x-stainless-const: true + id: + type: string + deleted: + type: boolean + required: + - object + - id + - deleted + InviteListResponse: + type: object + properties: + object: + type: string + enum: + - list + description: The object type, which is always `list` + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/Invite' + first_id: + type: string + description: The first `invite_id` in the retrieved `list` + last_id: + type: string + description: The last `invite_id` in the retrieved `list` + has_more: + type: boolean + description: >- + The `has_more` property is used for pagination to indicate there are + additional results. + required: + - object + - data + InviteProjectGroupBody: + type: object + description: Request payload for granting a group access to a project. + properties: + group_id: + type: string + description: Identifier of the group to add to the project. + role: + type: string + description: Identifier of the project role to grant to the group. + required: + - group_id + - role + x-oaiMeta: + example: | + { + "group_id": "group_01J1F8ABCDXYZ", + "role": "role_01J1F8PROJ" + } + InviteRequest: + type: object + properties: + email: + type: string + description: Send an email to this address + role: + type: string + enum: + - reader + - owner + description: '`owner` or `reader`' + projects: + type: array + description: >- + An array of projects to which membership is granted at the same time + the org invite is accepted. If omitted, the user will be invited to + the default project for compatibility with legacy behavior. + items: + type: object + properties: + id: + type: string + description: Project's public ID + role: + type: string + enum: + - member + - owner + description: Project membership role + required: + - id + - role + required: + - email + - role + Item: + type: object + description: | + Content item used to generate a response. + oneOf: + - $ref: '#/components/schemas/InputMessage' + - $ref: '#/components/schemas/OutputMessage' + - $ref: '#/components/schemas/FileSearchToolCall' + - $ref: '#/components/schemas/ComputerToolCall' + - $ref: '#/components/schemas/ComputerCallOutputItemParam' + - $ref: '#/components/schemas/WebSearchToolCall' + - $ref: '#/components/schemas/FunctionToolCall' + - $ref: '#/components/schemas/FunctionCallOutputItemParam' + - $ref: '#/components/schemas/ToolSearchCallItemParam' + - $ref: '#/components/schemas/ToolSearchOutputItemParam' + - $ref: '#/components/schemas/ReasoningItem' + - $ref: '#/components/schemas/CompactionSummaryItemParam' + - $ref: '#/components/schemas/ImageGenToolCall' + - $ref: '#/components/schemas/CodeInterpreterToolCall' + - $ref: '#/components/schemas/LocalShellToolCall' + - $ref: '#/components/schemas/LocalShellToolCallOutput' + - $ref: '#/components/schemas/FunctionShellCallItemParam' + - $ref: '#/components/schemas/FunctionShellCallOutputItemParam' + - $ref: '#/components/schemas/ApplyPatchToolCallItemParam' + - $ref: '#/components/schemas/ApplyPatchToolCallOutputItemParam' + - $ref: '#/components/schemas/MCPListTools' + - $ref: '#/components/schemas/MCPApprovalRequest' + - $ref: '#/components/schemas/MCPApprovalResponse' + - $ref: '#/components/schemas/MCPToolCall' + - $ref: '#/components/schemas/CustomToolCallOutput' + - $ref: '#/components/schemas/CustomToolCall' + discriminator: + propertyName: type + ItemResource: + description: | + Content item used to generate a response. + oneOf: + - $ref: '#/components/schemas/InputMessageResource' + - $ref: '#/components/schemas/OutputMessage' + - $ref: '#/components/schemas/FileSearchToolCall' + - $ref: '#/components/schemas/ComputerToolCall' + - $ref: '#/components/schemas/ComputerToolCallOutputResource' + - $ref: '#/components/schemas/WebSearchToolCall' + - $ref: '#/components/schemas/FunctionToolCallResource' + - $ref: '#/components/schemas/FunctionToolCallOutputResource' + - $ref: '#/components/schemas/ToolSearchCall' + - $ref: '#/components/schemas/ToolSearchOutput' + - $ref: '#/components/schemas/ReasoningItem' + - $ref: '#/components/schemas/CompactionBody' + - $ref: '#/components/schemas/ImageGenToolCall' + - $ref: '#/components/schemas/CodeInterpreterToolCall' + - $ref: '#/components/schemas/LocalShellToolCall' + - $ref: '#/components/schemas/LocalShellToolCallOutput' + - $ref: '#/components/schemas/FunctionShellCall' + - $ref: '#/components/schemas/FunctionShellCallOutput' + - $ref: '#/components/schemas/ApplyPatchToolCall' + - $ref: '#/components/schemas/ApplyPatchToolCallOutput' + - $ref: '#/components/schemas/MCPListTools' + - $ref: '#/components/schemas/MCPApprovalRequest' + - $ref: '#/components/schemas/MCPApprovalResponseResource' + - $ref: '#/components/schemas/MCPToolCall' + - $ref: '#/components/schemas/CustomToolCallResource' + - $ref: '#/components/schemas/CustomToolCallOutputResource' + discriminator: + propertyName: type + ListAssistantsResponse: + type: object + properties: + object: + type: string + example: list + data: + type: array + items: + $ref: '#/components/schemas/AssistantObject' + first_id: + type: string + example: asst_abc123 + last_id: + type: string + example: asst_abc456 + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + x-oaiMeta: + name: List assistants response object + group: chat + example: | + { + "object": "list", + "data": [ + { + "id": "asst_abc123", + "object": "assistant", + "created_at": 1698982736, + "name": "Coding Tutor", + "description": null, + "model": "gpt-4o", + "instructions": "You are a helpful assistant designed to make me better at coding!", + "tools": [], + "tool_resources": {}, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + }, + { + "id": "asst_abc456", + "object": "assistant", + "created_at": 1698982718, + "name": "My Assistant", + "description": null, + "model": "gpt-4o", + "instructions": "You are a helpful assistant designed to make me better at coding!", + "tools": [], + "tool_resources": {}, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + }, + { + "id": "asst_abc789", + "object": "assistant", + "created_at": 1698982643, + "name": null, + "description": null, + "model": "gpt-4o", + "instructions": null, + "tools": [], + "tool_resources": {}, + "metadata": {}, + "top_p": 1.0, + "temperature": 1.0, + "response_format": "auto" + } + ], + "first_id": "asst_abc123", + "last_id": "asst_abc789", + "has_more": false + } + ListAuditLogsResponse: + type: object + properties: + object: + type: string + enum: + - list + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/AuditLog' + first_id: + type: string + example: audit_log-defb456h8dks + last_id: + type: string + example: audit_log-hnbkd8s93s + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + ListBatchesResponse: + type: object + properties: + data: + type: array + items: + $ref: '#/components/schemas/Batch' + first_id: + type: string + example: batch_abc123 + last_id: + type: string + example: batch_abc456 + has_more: + type: boolean + object: + type: string + enum: + - list + x-stainless-const: true + required: + - object + - data + - has_more + ListCertificatesResponse: + type: object + properties: + data: + type: array + items: + $ref: '#/components/schemas/Certificate' + first_id: + type: string + example: cert_abc + last_id: + type: string + example: cert_abc + has_more: + type: boolean + object: + type: string + enum: + - list + x-stainless-const: true + required: + - object + - data + - has_more + ListFilesResponse: + type: object + properties: + object: + type: string + example: list + data: + type: array + items: + $ref: '#/components/schemas/OpenAIFile' + first_id: + type: string + example: file-abc123 + last_id: + type: string + example: file-abc456 + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + ListFineTuningCheckpointPermissionResponse: + type: object + properties: + data: + type: array + items: + $ref: '#/components/schemas/FineTuningCheckpointPermission' + object: + type: string + enum: + - list + x-stainless-const: true + first_id: + anyOf: + - type: string + - type: 'null' + last_id: + anyOf: + - type: string + - type: 'null' + has_more: + type: boolean + required: + - object + - data + - has_more + ListFineTuningJobCheckpointsResponse: + type: object + properties: + data: + type: array + items: + $ref: '#/components/schemas/FineTuningJobCheckpoint' + object: + type: string + enum: + - list + x-stainless-const: true + first_id: + anyOf: + - type: string + - type: 'null' + last_id: + anyOf: + - type: string + - type: 'null' + has_more: + type: boolean + required: + - object + - data + - has_more + ListFineTuningJobEventsResponse: + type: object + properties: + data: + type: array + items: + $ref: '#/components/schemas/FineTuningJobEvent' + object: + type: string + enum: + - list + x-stainless-const: true + has_more: + type: boolean + required: + - object + - data + - has_more + ListMessagesResponse: + properties: + object: + type: string + example: list + data: + type: array + items: + $ref: '#/components/schemas/MessageObject' + first_id: + type: string + example: msg_abc123 + last_id: + type: string + example: msg_abc123 + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + ListModelsResponse: + type: object + properties: + object: + type: string + enum: + - list + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/Model' + required: + - object + - data + ListPaginatedFineTuningJobsResponse: + type: object + properties: + data: + type: array + items: + $ref: '#/components/schemas/FineTuningJob' + has_more: + type: boolean + object: + type: string + enum: + - list + x-stainless-const: true + required: + - object + - data + - has_more + ListRunStepsResponse: + properties: + object: + type: string + example: list + data: + type: array + items: + $ref: '#/components/schemas/RunStepObject' + first_id: + type: string + example: step_abc123 + last_id: + type: string + example: step_abc456 + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + ListRunsResponse: + type: object + properties: + object: + type: string + example: list + data: + type: array + items: + $ref: '#/components/schemas/RunObject' + first_id: + type: string + example: run_abc123 + last_id: + type: string + example: run_abc456 + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + ListVectorStoreFilesResponse: + properties: + object: + type: string + example: list + data: + type: array + items: + $ref: '#/components/schemas/VectorStoreFileObject' + first_id: + type: string + example: file-abc123 + last_id: + type: string + example: file-abc456 + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + ListVectorStoresResponse: + properties: + object: + type: string + example: list + data: + type: array + items: + $ref: '#/components/schemas/VectorStoreObject' + first_id: + type: string + example: vs_abc123 + last_id: + type: string + example: vs_abc456 + has_more: + type: boolean + example: false + required: + - object + - data + - first_id + - last_id + - has_more + LocalShellToolCall: + type: object + title: Local shell call + description: | + A tool call to run a command on the local shell. + properties: + type: + type: string + enum: + - local_shell_call + description: | + The type of the local shell call. Always `local_shell_call`. + x-stainless-const: true + id: + type: string + description: | + The unique ID of the local shell call. + call_id: + type: string + description: | + The unique ID of the local shell tool call generated by the model. + action: + $ref: '#/components/schemas/LocalShellExecAction' + status: + type: string + enum: + - in_progress + - completed + - incomplete + description: | + The status of the local shell call. + required: + - type + - id + - call_id + - action + - status + LocalShellToolCallOutput: + type: object + title: Local shell call output + description: | + The output of a local shell tool call. + properties: + type: + type: string + enum: + - local_shell_call_output + description: > + The type of the local shell tool call output. Always + `local_shell_call_output`. + x-stainless-const: true + id: + type: string + description: | + The unique ID of the local shell tool call generated by the model. + output: + type: string + description: | + A JSON string of the output of the local shell tool call. + status: + anyOf: + - type: string + enum: + - in_progress + - completed + - incomplete + description: > + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. + - type: 'null' + required: + - id + - type + - output + LogProbProperties: + type: object + description: | + A log probability object. + properties: + token: + type: string + description: | + The token that was used to generate the log probability. + logprob: + type: number + description: | + The log probability of the token. + bytes: + type: array + items: + type: integer + description: | + The bytes that were used to generate the log probability. + required: + - token + - logprob + - bytes + MCPApprovalRequest: + type: object + title: MCP approval request + description: | + A request for human approval of a tool invocation. + properties: + type: + type: string + enum: + - mcp_approval_request + description: | + The type of the item. Always `mcp_approval_request`. + x-stainless-const: true + id: + type: string + description: | + The unique ID of the approval request. + server_label: + type: string + description: | + The label of the MCP server making the request. + name: + type: string + description: | + The name of the tool to run. + arguments: + type: string + description: | + A JSON string of arguments for the tool. + required: + - type + - id + - server_label + - name + - arguments + MCPApprovalResponse: + type: object + title: MCP approval response + description: | + A response to an MCP approval request. + properties: + type: + type: string + enum: + - mcp_approval_response + description: | + The type of the item. Always `mcp_approval_response`. + x-stainless-const: true + id: + anyOf: + - type: string + description: | + The unique ID of the approval response + - type: 'null' + approval_request_id: + type: string + description: | + The ID of the approval request being answered. + approve: + type: boolean + description: | + Whether the request was approved. + reason: + anyOf: + - type: string + description: | + Optional reason for the decision. + - type: 'null' + required: + - type + - approve + - approval_request_id + MCPApprovalResponseResource: + type: object + title: MCP approval response + description: | + A response to an MCP approval request. + properties: + type: + type: string + enum: + - mcp_approval_response + description: | + The type of the item. Always `mcp_approval_response`. + x-stainless-const: true + id: + type: string + description: | + The unique ID of the approval response + approval_request_id: + type: string + description: | + The ID of the approval request being answered. + approve: + type: boolean + description: | + Whether the request was approved. + reason: + anyOf: + - type: string + description: | + Optional reason for the decision. + - type: 'null' + required: + - type + - id + - approve + - approval_request_id + MCPListTools: + type: object + title: MCP list tools + description: | + A list of tools available on an MCP server. + properties: + type: + type: string + enum: + - mcp_list_tools + description: | + The type of the item. Always `mcp_list_tools`. + x-stainless-const: true + id: + type: string + description: | + The unique ID of the list. + server_label: + type: string + description: | + The label of the MCP server. + tools: + type: array + items: + $ref: '#/components/schemas/MCPListToolsTool' + description: | + The tools available on the server. + error: + anyOf: + - type: string + description: | + Error message if the server could not list tools. + - type: 'null' + required: + - type + - id + - server_label + - tools + MCPListToolsTool: + type: object + title: MCP list tools tool + description: | + A tool available on an MCP server. + properties: + name: + type: string + description: | + The name of the tool. + description: + anyOf: + - type: string + description: | + The description of the tool. + - type: 'null' + input_schema: + type: object + description: | + The JSON schema describing the tool's input. + annotations: + anyOf: + - type: object + description: | + Additional annotations about the tool. + - type: 'null' + required: + - name + - input_schema + MCPTool: + type: object + title: MCP tool + description: > + Give the model access to additional tools via remote Model Context + Protocol + + (MCP) servers. [Learn more about MCP](/docs/guides/tools-remote-mcp). + properties: + type: + type: string + enum: + - mcp + description: The type of the MCP tool. Always `mcp`. + x-stainless-const: true + server_label: + type: string + description: | + A label for this MCP server, used to identify it in tool calls. + server_url: + type: string + description: > + The URL for the MCP server. One of `server_url` or `connector_id` + must be + + provided. + connector_id: + type: string + enum: + - connector_dropbox + - connector_gmail + - connector_googlecalendar + - connector_googledrive + - connector_microsoftteams + - connector_outlookcalendar + - connector_outlookemail + - connector_sharepoint + description: > + Identifier for service connectors, like those available in ChatGPT. + One of + + `server_url` or `connector_id` must be provided. Learn more about + service + + connectors [here](/docs/guides/tools-remote-mcp#connectors). + + + Currently supported `connector_id` values are: + + + - Dropbox: `connector_dropbox` + + - Gmail: `connector_gmail` + + - Google Calendar: `connector_googlecalendar` + + - Google Drive: `connector_googledrive` + + - Microsoft Teams: `connector_microsoftteams` + + - Outlook Calendar: `connector_outlookcalendar` + + - Outlook Email: `connector_outlookemail` + + - SharePoint: `connector_sharepoint` + authorization: + type: string + description: > + An OAuth access token that can be used with a remote MCP server, + either + + with a custom MCP server URL or a service connector. Your + application + + must handle the OAuth authorization flow and provide the token here. + server_description: + type: string + description: > + Optional description of the MCP server, used to provide more + context. + headers: + anyOf: + - type: object + additionalProperties: + type: string + description: > + Optional HTTP headers to send to the MCP server. Use for + authentication + + or other purposes. + - type: 'null' + allowed_tools: + anyOf: + - description: | + List of allowed tool names or a filter object. + oneOf: + - type: array + title: MCP allowed tools + description: A string array of allowed tool names + items: + type: string + - $ref: '#/components/schemas/MCPToolFilter' + - type: 'null' + require_approval: + anyOf: + - description: Specify which of the MCP server's tools require approval. + oneOf: + - type: object + title: MCP tool approval filter + description: > + Specify which of the MCP server's tools require approval. + Can be + + `always`, `never`, or a filter object associated with tools + + that require approval. + properties: + always: + $ref: '#/components/schemas/MCPToolFilter' + never: + $ref: '#/components/schemas/MCPToolFilter' + additionalProperties: false + - type: string + title: MCP tool approval setting + description: > + Specify a single approval policy for all tools. One of + `always` or + + `never`. When set to `always`, all tools will require + approval. When + + set to `never`, all tools will not require approval. + enum: + - always + - never + default: always + - type: 'null' + defer_loading: + type: boolean + description: | + Whether this MCP tool is deferred and discovered via tool search. + required: + - type + - server_label + MCPToolCall: + type: object + title: MCP tool call + description: | + An invocation of a tool on an MCP server. + properties: + type: + type: string + enum: + - mcp_call + description: | + The type of the item. Always `mcp_call`. + x-stainless-const: true + id: + type: string + description: | + The unique ID of the tool call. + server_label: + type: string + description: | + The label of the MCP server running the tool. + name: + type: string + description: | + The name of the tool that was run. + arguments: + type: string + description: | + A JSON string of the arguments passed to the tool. + output: + anyOf: + - type: string + description: | + The output from the tool call. + - type: 'null' + error: + anyOf: + - type: string + description: | + The error from the tool call, if any. + - type: 'null' + status: + $ref: '#/components/schemas/MCPToolCallStatus' + description: > + The status of the tool call. One of `in_progress`, `completed`, + `incomplete`, `calling`, or `failed`. + approval_request_id: + anyOf: + - type: string + description: > + 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. + - type: 'null' + required: + - type + - id + - server_label + - name + - arguments + MCPToolFilter: + type: object + title: MCP tool filter + description: | + A filter object to specify which tools are allowed. + properties: + tool_names: + type: array + title: MCP allowed tools + items: + type: string + description: List of allowed tool names. + read_only: + type: boolean + description: > + Indicates whether or not a tool modifies data or is read-only. If an + + MCP server is [annotated with + `readOnlyHint`](https://modelcontextprotocol.io/specification/2025-06-18/schema#toolannotations-readonlyhint), + + it will match this filter. + required: [] + additionalProperties: false + MessageContentImageFileObject: + title: Image file + type: object + description: >- + References an image [File](/docs/api-reference/files) in the content of + a message. + properties: + type: + description: Always `image_file`. + type: string + enum: + - image_file + x-stainless-const: true + image_file: + type: object + properties: + file_id: + description: >- + The [File](/docs/api-reference/files) ID of the image in the + message content. Set `purpose="vision"` when uploading the File + if you need to later display the file content. + type: string + detail: + type: string + description: >- + Specifies the detail level of the image if specified by the + user. `low` uses fewer tokens, you can opt in to high resolution + using `high`. + enum: + - auto + - low + - high + default: auto + required: + - file_id + required: + - type + - image_file + MessageContentImageUrlObject: + title: Image URL + type: object + description: References an image URL in the content of a message. + properties: + type: + type: string + enum: + - image_url + description: The type of the content part. + x-stainless-const: true + image_url: + type: object + properties: + url: + type: string + description: >- + The external URL of the image, must be a supported image types: + jpeg, jpg, png, gif, webp. + format: uri + detail: + type: string + description: >- + Specifies the detail level of the image. `low` uses fewer + tokens, you can opt in to high resolution using `high`. Default + value is `auto` + enum: + - auto + - low + - high + default: auto + required: + - url + required: + - type + - image_url + MessageContentRefusalObject: + title: Refusal + type: object + description: The refusal content generated by the assistant. + properties: + type: + description: Always `refusal`. + type: string + enum: + - refusal + x-stainless-const: true + refusal: + type: string + required: + - type + - refusal + MessageContentTextAnnotationsFileCitationObject: + title: File citation + type: object + description: >- + A citation within the message that points to a specific quote from a + specific File associated with the assistant or the message. Generated + when the assistant uses the "file_search" tool to search files. + properties: + type: + description: Always `file_citation`. + type: string + enum: + - file_citation + x-stainless-const: true + text: + description: The text in the message content that needs to be replaced. + type: string + file_citation: + type: object + properties: + file_id: + description: The ID of the specific File the citation is from. + type: string + required: + - file_id + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - type + - text + - file_citation + - start_index + - end_index + MessageContentTextAnnotationsFilePathObject: + title: File path + type: object + description: >- + A URL for the file that's generated when the assistant used the + `code_interpreter` tool to generate a file. + properties: + type: + description: Always `file_path`. + type: string + enum: + - file_path + x-stainless-const: true + text: + description: The text in the message content that needs to be replaced. + type: string + file_path: + type: object + properties: + file_id: + description: The ID of the file that was generated. + type: string + required: + - file_id + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - type + - text + - file_path + - start_index + - end_index + MessageContentTextObject: + title: Text + type: object + description: The text content that is part of a message. + properties: + type: + description: Always `text`. + type: string + enum: + - text + x-stainless-const: true + text: + type: object + properties: + value: + description: The data that makes up the text. + type: string + annotations: + type: array + items: + oneOf: + - $ref: >- + #/components/schemas/MessageContentTextAnnotationsFileCitationObject + - $ref: >- + #/components/schemas/MessageContentTextAnnotationsFilePathObject + required: + - value + - annotations + required: + - type + - text + MessageDeltaContentImageFileObject: + title: Image file + type: object + description: >- + References an image [File](/docs/api-reference/files) in the content of + a message. + properties: + index: + type: integer + description: The index of the content part in the message. + type: + description: Always `image_file`. + type: string + enum: + - image_file + x-stainless-const: true + image_file: + type: object + properties: + file_id: + description: >- + The [File](/docs/api-reference/files) ID of the image in the + message content. Set `purpose="vision"` when uploading the File + if you need to later display the file content. + type: string + detail: + type: string + description: >- + Specifies the detail level of the image if specified by the + user. `low` uses fewer tokens, you can opt in to high resolution + using `high`. + enum: + - auto + - low + - high + default: auto + required: + - index + - type + MessageDeltaContentImageUrlObject: + title: Image URL + type: object + description: References an image URL in the content of a message. + properties: + index: + type: integer + description: The index of the content part in the message. + type: + description: Always `image_url`. + type: string + enum: + - image_url + x-stainless-const: true + image_url: + type: object + properties: + url: + description: >- + The URL of the image, must be a supported image types: jpeg, + jpg, png, gif, webp. + type: string + detail: + type: string + description: >- + Specifies the detail level of the image. `low` uses fewer + tokens, you can opt in to high resolution using `high`. + enum: + - auto + - low + - high + default: auto + required: + - index + - type + MessageDeltaContentRefusalObject: + title: Refusal + type: object + description: The refusal content that is part of a message. + properties: + index: + type: integer + description: The index of the refusal part in the message. + type: + description: Always `refusal`. + type: string + enum: + - refusal + x-stainless-const: true + refusal: + type: string + required: + - index + - type + MessageDeltaContentTextAnnotationsFileCitationObject: + title: File citation + type: object + description: >- + A citation within the message that points to a specific quote from a + specific File associated with the assistant or the message. Generated + when the assistant uses the "file_search" tool to search files. + properties: + index: + type: integer + description: The index of the annotation in the text content part. + type: + description: Always `file_citation`. + type: string + enum: + - file_citation + x-stainless-const: true + text: + description: The text in the message content that needs to be replaced. + type: string + file_citation: + type: object + properties: + file_id: + description: The ID of the specific File the citation is from. + type: string + quote: + description: The specific quote in the file. + type: string + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - index + - type + MessageDeltaContentTextAnnotationsFilePathObject: + title: File path + type: object + description: >- + A URL for the file that's generated when the assistant used the + `code_interpreter` tool to generate a file. + properties: + index: + type: integer + description: The index of the annotation in the text content part. + type: + description: Always `file_path`. + type: string + enum: + - file_path + x-stainless-const: true + text: + description: The text in the message content that needs to be replaced. + type: string + file_path: + type: object + properties: + file_id: + description: The ID of the file that was generated. + type: string + start_index: + type: integer + minimum: 0 + end_index: + type: integer + minimum: 0 + required: + - index + - type + MessageDeltaContentTextObject: + title: Text + type: object + description: The text content that is part of a message. + properties: + index: + type: integer + description: The index of the content part in the message. + type: + description: Always `text`. + type: string + enum: + - text + x-stainless-const: true + text: + type: object + properties: + value: + description: The data that makes up the text. + type: string + annotations: + type: array + items: + oneOf: + - $ref: >- + #/components/schemas/MessageDeltaContentTextAnnotationsFileCitationObject + - $ref: >- + #/components/schemas/MessageDeltaContentTextAnnotationsFilePathObject + required: + - index + - type + MessageDeltaObject: + type: object + title: Message delta object + description: > + Represents a message delta i.e. any changed fields on a message during + streaming. + properties: + id: + description: >- + The identifier of the message, which can be referenced in API + endpoints. + type: string + object: + description: The object type, which is always `thread.message.delta`. + type: string + enum: + - thread.message.delta + x-stainless-const: true + delta: + description: The delta containing the fields that have changed on the Message. + type: object + properties: + role: + description: >- + The entity that produced the message. One of `user` or + `assistant`. + type: string + enum: + - user + - assistant + content: + description: The content of the message in array of text and/or images. + type: array + items: + oneOf: + - $ref: '#/components/schemas/MessageDeltaContentImageFileObject' + - $ref: '#/components/schemas/MessageDeltaContentTextObject' + - $ref: '#/components/schemas/MessageDeltaContentRefusalObject' + - $ref: '#/components/schemas/MessageDeltaContentImageUrlObject' + required: + - id + - object + - delta + x-oaiMeta: + name: The message delta object + beta: true + example: | + { + "id": "msg_123", + "object": "thread.message.delta", + "delta": { + "content": [ + { + "index": 0, + "type": "text", + "text": { "value": "Hello", "annotations": [] } + } + ] + } + } + MessageObject: + type: object + title: The message object + description: Represents a message within a [thread](/docs/api-reference/threads). + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.message`. + type: string + enum: + - thread.message + x-stainless-const: true + created_at: + description: The Unix timestamp (in seconds) for when the message was created. + type: integer + thread_id: + description: >- + The [thread](/docs/api-reference/threads) ID that this message + belongs to. + type: string + status: + description: >- + The status of the message, which can be either `in_progress`, + `incomplete`, or `completed`. + type: string + enum: + - in_progress + - incomplete + - completed + incomplete_details: + anyOf: + - description: >- + On an incomplete message, details about why the message is + incomplete. + type: object + properties: + reason: + type: string + description: The reason the message is incomplete. + enum: + - content_filter + - max_tokens + - run_cancelled + - run_expired + - run_failed + required: + - reason + - type: 'null' + completed_at: + anyOf: + - description: >- + The Unix timestamp (in seconds) for when the message was + completed. + type: integer + - type: 'null' + incomplete_at: + anyOf: + - description: >- + The Unix timestamp (in seconds) for when the message was marked + as incomplete. + type: integer + - type: 'null' + role: + description: The entity that produced the message. One of `user` or `assistant`. + type: string + enum: + - user + - assistant + content: + description: The content of the message in array of text and/or images. + type: array + items: + oneOf: + - $ref: '#/components/schemas/MessageContentImageFileObject' + - $ref: '#/components/schemas/MessageContentImageUrlObject' + - $ref: '#/components/schemas/MessageContentTextObject' + - $ref: '#/components/schemas/MessageContentRefusalObject' + assistant_id: + anyOf: + - description: >- + If applicable, the ID of the + [assistant](/docs/api-reference/assistants) that authored this + message. + type: string + - type: 'null' + run_id: + anyOf: + - description: >- + The ID of the [run](/docs/api-reference/runs) associated with + the creation of this message. Value is `null` when messages are + created manually using the create message or create thread + endpoints. + type: string + - type: 'null' + attachments: + anyOf: + - type: array + items: + type: object + properties: + file_id: + type: string + description: The ID of the file to attach to the message. + tools: + description: The tools to add this file to. + type: array + items: + oneOf: + - $ref: '#/components/schemas/AssistantToolsCode' + - $ref: >- + #/components/schemas/AssistantToolsFileSearchTypeOnly + description: >- + A list of files attached to the message, and the tools they were + added to. + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + required: + - id + - object + - created_at + - thread_id + - status + - incomplete_details + - completed_at + - incomplete_at + - role + - content + - assistant_id + - run_id + - attachments + - metadata + x-oaiMeta: + name: The message object + beta: true + example: | + { + "id": "msg_abc123", + "object": "thread.message", + "created_at": 1698983503, + "thread_id": "thread_abc123", + "role": "assistant", + "content": [ + { + "type": "text", + "text": { + "value": "Hi! How can I help you today?", + "annotations": [] + } + } + ], + "assistant_id": "asst_abc123", + "run_id": "run_abc123", + "attachments": [], + "metadata": {} + } + MessagePhase: + type: string + description: > + Labels an `assistant` message as intermediate commentary (`commentary`) + or the final answer (`final_answer`). + + For models like `gpt-5.3-codex` and beyond, when sending follow-up + requests, preserve and resend + + phase on all assistant messages — dropping it can degrade performance. + Not used for user messages. + enum: + - commentary + - final_answer + MessageRequestContentTextObject: + title: Text + type: object + description: The text content that is part of a message. + properties: + type: + description: Always `text`. + type: string + enum: + - text + x-stainless-const: true + text: + type: string + description: Text content to be sent to the model + required: + - type + - text + MessageStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: + - thread.message.created + x-stainless-const: true + data: + $ref: '#/components/schemas/MessageObject' + required: + - event + - data + description: >- + Occurs when a [message](/docs/api-reference/messages/object) is + created. + x-oaiMeta: + dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' + - type: object + properties: + event: + type: string + enum: + - thread.message.in_progress + x-stainless-const: true + data: + $ref: '#/components/schemas/MessageObject' + required: + - event + - data + description: >- + Occurs when a [message](/docs/api-reference/messages/object) moves + to an `in_progress` state. + x-oaiMeta: + dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' + - type: object + properties: + event: + type: string + enum: + - thread.message.delta + x-stainless-const: true + data: + $ref: '#/components/schemas/MessageDeltaObject' + required: + - event + - data + description: >- + Occurs when parts of a + [Message](/docs/api-reference/messages/object) are being streamed. + x-oaiMeta: + dataDescription: >- + `data` is a [message + delta](/docs/api-reference/assistants-streaming/message-delta-object) + - type: object + properties: + event: + type: string + enum: + - thread.message.completed + x-stainless-const: true + data: + $ref: '#/components/schemas/MessageObject' + required: + - event + - data + description: >- + Occurs when a [message](/docs/api-reference/messages/object) is + completed. + x-oaiMeta: + dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' + - type: object + properties: + event: + type: string + enum: + - thread.message.incomplete + x-stainless-const: true + data: + $ref: '#/components/schemas/MessageObject' + required: + - event + - data + description: >- + Occurs when a [message](/docs/api-reference/messages/object) ends + before it is completed. + x-oaiMeta: + dataDescription: '`data` is a [message](/docs/api-reference/messages/object)' + Metadata: + anyOf: + - type: object + description: > + Set of 16 key-value pairs that can be attached to an object. This + can be + + useful for storing additional information about the object in a + structured + + format, and querying for objects via API or the dashboard. + + + Keys are strings with a maximum length of 64 characters. Values are + strings + + with a maximum length of 512 characters. + additionalProperties: + type: string + x-oaiTypeLabel: map + - type: 'null' + Model: + title: Model + description: Describes an OpenAI model offering that can be used with the API. + properties: + id: + type: string + description: The model identifier, which can be referenced in the API endpoints. + created: + type: integer + description: The Unix timestamp (in seconds) when the model was created. + object: + type: string + description: The object type, which is always "model". + enum: + - model + x-stainless-const: true + owned_by: + type: string + description: The organization that owns the model. + required: + - id + - object + - created + - owned_by + x-oaiMeta: + name: The model object + example: | + { + "id": "VAR_chat_model_id", + "object": "model", + "created": 1686935002, + "owned_by": "openai" + } + ModelIds: + anyOf: + - $ref: '#/components/schemas/ModelIdsShared' + - $ref: '#/components/schemas/ModelIdsResponses' + ModelIdsCompaction: + anyOf: + - $ref: '#/components/schemas/ModelIdsResponses' + - type: string + - type: 'null' + description: >- + Model ID used to generate the response, like `gpt-5` or `o3`. OpenAI + offers a wide range of models with different capabilities, performance + characteristics, and price points. Refer to the [model + guide](/docs/models) to browse and compare available models. + ModelIdsResponses: + example: gpt-5.1 + anyOf: + - $ref: '#/components/schemas/ModelIdsShared' + - type: string + title: ResponsesOnlyModel + enum: + - o1-pro + - o1-pro-2025-03-19 + - o3-pro + - o3-pro-2025-06-10 + - o3-deep-research + - o3-deep-research-2025-06-26 + - o4-mini-deep-research + - o4-mini-deep-research-2025-06-26 + - computer-use-preview + - computer-use-preview-2025-03-11 + - gpt-5-codex + - gpt-5-pro + - gpt-5-pro-2025-10-06 + - gpt-5.1-codex-max + ModelIdsShared: + example: gpt-5.4 + anyOf: + - type: string + - type: string + enum: + - gpt-5.4 + - gpt-5.4-mini + - gpt-5.4-nano + - gpt-5.4-mini-2026-03-17 + - gpt-5.4-nano-2026-03-17 + - gpt-5.3-chat-latest + - gpt-5.2 + - gpt-5.2-2025-12-11 + - gpt-5.2-chat-latest + - gpt-5.2-pro + - gpt-5.2-pro-2025-12-11 + - gpt-5.1 + - gpt-5.1-2025-11-13 + - gpt-5.1-codex + - gpt-5.1-mini + - gpt-5.1-chat-latest + - gpt-5 + - gpt-5-mini + - gpt-5-nano + - gpt-5-2025-08-07 + - gpt-5-mini-2025-08-07 + - gpt-5-nano-2025-08-07 + - gpt-5-chat-latest + - gpt-4.1 + - gpt-4.1-mini + - gpt-4.1-nano + - gpt-4.1-2025-04-14 + - gpt-4.1-mini-2025-04-14 + - gpt-4.1-nano-2025-04-14 + - o4-mini + - o4-mini-2025-04-16 + - o3 + - o3-2025-04-16 + - o3-mini + - o3-mini-2025-01-31 + - o1 + - o1-2024-12-17 + - o1-preview + - o1-preview-2024-09-12 + - o1-mini + - o1-mini-2024-09-12 + - gpt-4o + - gpt-4o-2024-11-20 + - gpt-4o-2024-08-06 + - gpt-4o-2024-05-13 + - gpt-4o-audio-preview + - gpt-4o-audio-preview-2024-10-01 + - gpt-4o-audio-preview-2024-12-17 + - gpt-4o-audio-preview-2025-06-03 + - gpt-4o-mini-audio-preview + - gpt-4o-mini-audio-preview-2024-12-17 + - gpt-4o-search-preview + - gpt-4o-mini-search-preview + - gpt-4o-search-preview-2025-03-11 + - gpt-4o-mini-search-preview-2025-03-11 + - chatgpt-4o-latest + - codex-mini-latest + - gpt-4o-mini + - gpt-4o-mini-2024-07-18 + - gpt-4-turbo + - gpt-4-turbo-2024-04-09 + - gpt-4-0125-preview + - gpt-4-turbo-preview + - gpt-4-1106-preview + - gpt-4-vision-preview + - gpt-4 + - gpt-4-0314 + - gpt-4-0613 + - gpt-4-32k + - gpt-4-32k-0314 + - gpt-4-32k-0613 + - gpt-3.5-turbo + - gpt-3.5-turbo-16k + - gpt-3.5-turbo-0301 + - gpt-3.5-turbo-0613 + - gpt-3.5-turbo-1106 + - gpt-3.5-turbo-0125 + - gpt-3.5-turbo-16k-0613 + ModelResponseProperties: + type: object + properties: + metadata: + $ref: '#/components/schemas/Metadata' + top_logprobs: + anyOf: + - description: > + An integer between 0 and 20 specifying the number of most likely + tokens to + + return at each token position, each with an associated log + probability. + type: integer + minimum: 0 + maximum: 20 + - type: 'null' + temperature: + anyOf: + - type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + description: > + What sampling temperature to use, between 0 and 2. Higher values + like 0.8 will make the output more random, while lower values + like 0.2 will make it more focused and deterministic. + + We generally recommend altering this or `top_p` but not both. + - type: 'null' + top_p: + anyOf: + - type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + description: > + An alternative to sampling with temperature, called nucleus + sampling, + + where the model considers the results of the tokens with top_p + probability + + mass. So 0.1 means only the tokens comprising the top 10% + probability mass + + are considered. + + + We generally recommend altering this or `temperature` but not + both. + - type: 'null' + user: + type: string + example: user-1234 + deprecated: true + description: > + This field is being replaced by `safety_identifier` and + `prompt_cache_key`. Use `prompt_cache_key` instead to maintain + caching optimizations. + + A stable identifier for your end-users. + + Used to boost cache hit rates by better bucketing similar requests + and to help OpenAI detect and prevent abuse. [Learn + more](/docs/guides/safety-best-practices#safety-identifiers). + safety_identifier: + type: string + maxLength: 64 + example: safety-identifier-1234 + description: > + A stable identifier used to help detect users of your application + that may be violating OpenAI's usage policies. + + The IDs should be a string that uniquely identifies each user, with + a maximum length of 64 characters. We recommend hashing their + username or email address, in order to avoid sending us any + identifying information. [Learn + more](/docs/guides/safety-best-practices#safety-identifiers). + prompt_cache_key: + type: string + example: prompt-cache-key-1234 + description: > + Used by OpenAI to cache responses for similar requests to optimize + your cache hit rates. Replaces the `user` field. [Learn + more](/docs/guides/prompt-caching). + service_tier: + $ref: '#/components/schemas/ServiceTier' + prompt_cache_retention: + anyOf: + - type: string + enum: + - in-memory + - 24h + description: > + The retention policy for the prompt cache. Set to `24h` to + enable extended prompt caching, which keeps cached prefixes + active for longer, up to a maximum of 24 hours. [Learn + more](/docs/guides/prompt-caching#prompt-cache-retention). + - type: 'null' + ModifyAssistantRequest: + type: object + additionalProperties: false + properties: + model: + description: > + ID of the model to use. You can use the [List + models](/docs/api-reference/models/list) API to see all of your + available models, or see our [Model overview](/docs/models) for + descriptions of them. + anyOf: + - type: string + - $ref: '#/components/schemas/AssistantSupportedModels' + reasoning_effort: + $ref: '#/components/schemas/ReasoningEffort' + name: + anyOf: + - description: | + The name of the assistant. The maximum length is 256 characters. + type: string + maxLength: 256 + - type: 'null' + description: + anyOf: + - description: > + The description of the assistant. The maximum length is 512 + characters. + type: string + maxLength: 512 + - type: 'null' + instructions: + anyOf: + - description: > + The system instructions that the assistant uses. The maximum + length is 256,000 characters. + type: string + maxLength: 256000 + - type: 'null' + tools: + description: > + A list of tool enabled on the assistant. There can be a maximum of + 128 tools per assistant. Tools can be of types `code_interpreter`, + `file_search`, or `function`. + default: [] + type: array + maxItems: 128 + items: + oneOf: + - $ref: '#/components/schemas/AssistantToolsCode' + - $ref: '#/components/schemas/AssistantToolsFileSearch' + - $ref: '#/components/schemas/AssistantToolsFunction' + tool_resources: + anyOf: + - type: object + description: > + A set of resources that are used by the assistant's tools. The + resources are specific to the type of tool. For example, the + `code_interpreter` tool requires a list of file IDs, while the + `file_search` tool requires a list of vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: > + Overrides the list of [file](/docs/api-reference/files) + IDs made available to the `code_interpreter` tool. There + can be a maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: > + Overrides the [vector + store](/docs/api-reference/vector-stores/object) + attached to this assistant. There can be a maximum of 1 + vector store attached to the assistant. + maxItems: 1 + items: + type: string + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + temperature: + anyOf: + - description: > + What sampling temperature to use, between 0 and 2. Higher values + like 0.8 will make the output more random, while lower values + like 0.2 will make it more focused and deterministic. + type: number + minimum: 0 + maximum: 2 + default: 1 + example: 1 + - type: 'null' + top_p: + anyOf: + - type: number + minimum: 0 + maximum: 1 + default: 1 + example: 1 + description: > + An alternative to sampling with temperature, called nucleus + sampling, where the model considers the results of the tokens + with top_p probability mass. So 0.1 means only the tokens + comprising the top 10% probability mass are considered. + + + We generally recommend altering this or temperature but not + both. + - type: 'null' + response_format: + anyOf: + - $ref: '#/components/schemas/AssistantsApiResponseFormatOption' + - type: 'null' + ModifyCertificateRequest: + type: object + properties: + name: + type: string + description: The updated name for the certificate + required: + - name + ModifyMessageRequest: + type: object + additionalProperties: false + properties: + metadata: + $ref: '#/components/schemas/Metadata' + ModifyRunRequest: + type: object + additionalProperties: false + properties: + metadata: + $ref: '#/components/schemas/Metadata' + ModifyThreadRequest: + type: object + additionalProperties: false + properties: + tool_resources: + anyOf: + - type: object + description: > + A set of resources that are made available to the assistant's + tools in this thread. The resources are specific to the type of + tool. For example, the `code_interpreter` tool requires a list + of file IDs, while the `file_search` tool requires a list of + vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: > + A list of [file](/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a + maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: > + The [vector + store](/docs/api-reference/vector-stores/object) + attached to this thread. There can be a maximum of 1 + vector store attached to the thread. + maxItems: 1 + items: + type: string + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + NoiseReductionType: + type: string + enum: + - near_field + - far_field + description: > + Type of noise reduction. `near_field` is for close-talking microphones + such as headphones, `far_field` is for far-field microphones such as + laptop or conference room microphones. + OpenAIFile: + title: OpenAIFile + description: >- + The `File` object represents a document that has been uploaded to + OpenAI. + properties: + id: + type: string + description: The file identifier, which can be referenced in the API endpoints. + bytes: + type: integer + description: The size of the file, in bytes. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the file was created. + expires_at: + type: integer + description: The Unix timestamp (in seconds) for when the file will expire. + filename: + type: string + description: The name of the file. + object: + type: string + description: The object type, which is always `file`. + enum: + - file + x-stainless-const: true + purpose: + type: string + description: >- + The intended purpose of the file. Supported values are `assistants`, + `assistants_output`, `batch`, `batch_output`, `fine-tune`, + `fine-tune-results`, `vision`, and `user_data`. + enum: + - assistants + - assistants_output + - batch + - batch_output + - fine-tune + - fine-tune-results + - vision + - user_data + status: + type: string + deprecated: true + description: >- + Deprecated. The current status of the file, which can be either + `uploaded`, `processed`, or `error`. + enum: + - uploaded + - processed + - error + status_details: + type: string + deprecated: true + description: >- + Deprecated. For details on why a fine-tuning training file failed + validation, see the `error` field on `fine_tuning.job`. + required: + - id + - object + - bytes + - created_at + - filename + - purpose + - status + x-oaiMeta: + name: The file object + example: | + { + "id": "file-abc123", + "object": "file", + "bytes": 120000, + "created_at": 1677610602, + "expires_at": 1680202602, + "filename": "salesOverview.pdf", + "purpose": "assistants", + } + OtherChunkingStrategyResponseParam: + type: object + title: Other Chunking Strategy + description: >- + This is returned when the chunking strategy is unknown. Typically, this + is because the file was indexed before the `chunking_strategy` concept + was introduced in the API. + additionalProperties: false + properties: + type: + type: string + description: Always `other`. + enum: + - other + x-stainless-const: true + required: + - type + OutputAudio: + type: object + title: Output audio + description: | + An audio output from the model. + properties: + type: + type: string + description: | + The type of the output audio. Always `output_audio`. + enum: + - output_audio + x-stainless-const: true + data: + type: string + description: | + Base64-encoded audio data from the model. + transcript: + type: string + description: | + The transcript of the audio data from the model. + required: + - type + - data + - transcript + OutputContent: + oneOf: + - $ref: '#/components/schemas/OutputTextContent' + - $ref: '#/components/schemas/RefusalContent' + - $ref: '#/components/schemas/ReasoningTextContent' + discriminator: + propertyName: type + OutputItem: + oneOf: + - $ref: '#/components/schemas/OutputMessage' + - $ref: '#/components/schemas/FileSearchToolCall' + - $ref: '#/components/schemas/FunctionToolCall' + - $ref: '#/components/schemas/FunctionToolCallOutputResource' + - $ref: '#/components/schemas/WebSearchToolCall' + - $ref: '#/components/schemas/ComputerToolCall' + - $ref: '#/components/schemas/ComputerToolCallOutputResource' + - $ref: '#/components/schemas/ReasoningItem' + - $ref: '#/components/schemas/ToolSearchCall' + - $ref: '#/components/schemas/ToolSearchOutput' + - $ref: '#/components/schemas/CompactionBody' + - $ref: '#/components/schemas/ImageGenToolCall' + - $ref: '#/components/schemas/CodeInterpreterToolCall' + - $ref: '#/components/schemas/LocalShellToolCall' + - $ref: '#/components/schemas/LocalShellToolCallOutput' + - $ref: '#/components/schemas/FunctionShellCall' + - $ref: '#/components/schemas/FunctionShellCallOutput' + - $ref: '#/components/schemas/ApplyPatchToolCall' + - $ref: '#/components/schemas/ApplyPatchToolCallOutput' + - $ref: '#/components/schemas/MCPToolCall' + - $ref: '#/components/schemas/MCPListTools' + - $ref: '#/components/schemas/MCPApprovalRequest' + - $ref: '#/components/schemas/MCPApprovalResponseResource' + - $ref: '#/components/schemas/CustomToolCall' + - $ref: '#/components/schemas/CustomToolCallOutputResource' + discriminator: + propertyName: type + OutputMessage: + type: object + title: Output message + description: | + An output message from the model. + properties: + id: + type: string + description: | + The unique ID of the output message. + type: + type: string + description: | + The type of the output message. Always `message`. + enum: + - message + x-stainless-const: true + role: + type: string + description: | + The role of the output message. Always `assistant`. + enum: + - assistant + x-stainless-const: true + content: + type: array + description: | + The content of the output message. + items: + $ref: '#/components/schemas/OutputMessageContent' + phase: + anyOf: + - $ref: '#/components/schemas/MessagePhase' + - type: 'null' + status: + type: string + description: > + The status of the message input. One of `in_progress`, `completed`, + or + + `incomplete`. Populated when input items are returned via API. + enum: + - in_progress + - completed + - incomplete + required: + - id + - type + - role + - content + - status + OutputMessageContent: + oneOf: + - $ref: '#/components/schemas/OutputTextContent' + - $ref: '#/components/schemas/RefusalContent' + discriminator: + propertyName: type + ParallelToolCalls: + description: >- + Whether to enable [parallel function + calling](/docs/guides/function-calling#configuring-parallel-function-calling) + during tool use. + type: boolean + default: true + PartialImages: + anyOf: + - type: integer + maximum: 3 + minimum: 0 + default: 0 + example: 1 + description: > + The number of partial images to generate. This parameter is used for + + streaming responses that return partial images. Value must be + between 0 and 3. + + When set to 0, the response will be a single image sent in one + streaming event. + + + Note that the final image may be sent before the full number of + partial images + + are generated if the full image is generated more quickly. + - type: 'null' + PredictionContent: + type: object + title: Static Content + description: > + Static predicted output content, such as the content of a text file that + is + + being regenerated. + required: + - type + - content + properties: + type: + type: string + enum: + - content + description: | + The type of the predicted content you want to provide. This type is + currently always `content`. + x-stainless-const: true + content: + description: > + The content that should be matched when generating a model response. + + If generated tokens would match this content, the entire model + response + + can be returned much more quickly. + oneOf: + - type: string + title: Text content + description: | + The content used for a Predicted Output. This is often the + text of a file you are regenerating with minor changes. + - type: array + description: >- + An array of content parts with a defined type. Supported options + differ based on the [model](/docs/models) being used to generate + the response. Can contain text inputs. + title: Array of content parts + items: + $ref: >- + #/components/schemas/ChatCompletionRequestMessageContentPartText + minItems: 1 + Project: + type: object + description: Represents an individual project. + properties: + id: + type: string + description: The identifier, which can be referenced in API endpoints + object: + type: string + enum: + - organization.project + description: The object type, which is always `organization.project` + x-stainless-const: true + name: + type: string + description: The name of the project. This appears in reporting. + created_at: + type: integer + description: The Unix timestamp (in seconds) of when the project was created. + archived_at: + anyOf: + - type: integer + description: >- + The Unix timestamp (in seconds) of when the project was archived + or `null`. + - type: 'null' + status: + type: string + enum: + - active + - archived + description: '`active` or `archived`' + required: + - id + - object + - name + - created_at + - status + x-oaiMeta: + name: The project object + example: | + { + "id": "proj_abc", + "object": "organization.project", + "name": "Project example", + "created_at": 1711471533, + "archived_at": null, + "status": "active" + } + ProjectApiKey: + type: object + description: Represents an individual API key in a project. + properties: + object: + type: string + enum: + - organization.project.api_key + description: The object type, which is always `organization.project.api_key` + x-stainless-const: true + redacted_value: + type: string + description: The redacted value of the API key + name: + type: string + description: The name of the API key + created_at: + type: integer + description: The Unix timestamp (in seconds) of when the API key was created + last_used_at: + type: integer + description: The Unix timestamp (in seconds) of when the API key was last used. + id: + type: string + description: The identifier, which can be referenced in API endpoints + owner: + type: object + properties: + type: + type: string + enum: + - user + - service_account + description: '`user` or `service_account`' + user: + $ref: '#/components/schemas/ProjectUser' + service_account: + $ref: '#/components/schemas/ProjectServiceAccount' + required: + - object + - redacted_value + - name + - created_at + - last_used_at + - id + - owner + x-oaiMeta: + name: The project API key object + example: | + { + "object": "organization.project.api_key", + "redacted_value": "sk-abc...def", + "name": "My API Key", + "created_at": 1711471533, + "last_used_at": 1711471534, + "id": "key_abc", + "owner": { + "type": "user", + "user": { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "created_at": 1711471533 + } + } + } + ProjectApiKeyDeleteResponse: + type: object + properties: + object: + type: string + enum: + - organization.project.api_key.deleted + x-stainless-const: true + id: + type: string + deleted: + type: boolean + required: + - object + - id + - deleted + ProjectApiKeyListResponse: + type: object + properties: + object: + type: string + enum: + - list + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/ProjectApiKey' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + ProjectCreateRequest: + type: object + properties: + name: + type: string + description: The friendly name of the project, this name appears in reports. + geography: + type: string + enum: + - US + - EU + - JP + - IN + - KR + - CA + - AU + - SG + description: >- + Create the project with the specified data residency region. Your + organization must have access to Data residency functionality in + order to use. See [data residency + controls](/docs/guides/your-data#data-residency-controls) to review + the functionality and limitations of setting this field. + required: + - name + ProjectGroup: + type: object + description: Details about a group's membership in a project. + properties: + object: + type: string + enum: + - project.group + description: Always `project.group`. + x-stainless-const: true + project_id: + type: string + description: Identifier of the project. + group_id: + type: string + description: Identifier of the group that has access to the project. + group_name: + type: string + description: Display name of the group. + created_at: + type: integer + format: int64 + description: >- + Unix timestamp (in seconds) when the group was granted project + access. + required: + - object + - project_id + - group_id + - group_name + - created_at + x-oaiMeta: + name: The project group object + example: | + { + "object": "project.group", + "project_id": "proj_abc123", + "group_id": "group_01J1F8ABCDXYZ", + "group_name": "Support Team", + "created_at": 1711471533 + } + ProjectGroupDeletedResource: + type: object + description: Confirmation payload returned after removing a group from a project. + properties: + object: + type: string + enum: + - project.group.deleted + description: Always `project.group.deleted`. + x-stainless-const: true + deleted: + type: boolean + description: Whether the group membership in the project was removed. + required: + - object + - deleted + x-oaiMeta: + name: Project group deletion confirmation + example: | + { + "object": "project.group.deleted", + "deleted": true + } + ProjectGroupListResource: + type: object + description: Paginated list of groups that have access to a project. + properties: + object: + type: string + enum: + - list + description: Always `list`. + x-stainless-const: true + data: + type: array + description: Project group memberships returned in the current page. + items: + $ref: '#/components/schemas/ProjectGroup' + has_more: + type: boolean + description: Whether additional project group memberships are available. + next: + description: >- + Cursor to fetch the next page of results, or `null` when there are + no more results. + anyOf: + - type: string + - type: 'null' + required: + - object + - data + - has_more + - next + x-oaiMeta: + name: Project group list + example: | + { + "object": "list", + "data": [ + { + "object": "project.group", + "project_id": "proj_abc123", + "group_id": "group_01J1F8ABCDXYZ", + "group_name": "Support Team", + "created_at": 1711471533 + } + ], + "has_more": false, + "next": null + } + ProjectListResponse: + type: object + properties: + object: + type: string + enum: + - list + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/Project' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + ProjectRateLimit: + type: object + description: Represents a project rate limit config. + properties: + object: + type: string + enum: + - project.rate_limit + description: The object type, which is always `project.rate_limit` + x-stainless-const: true + id: + type: string + description: The identifier, which can be referenced in API endpoints. + model: + type: string + description: The model this rate limit applies to. + max_requests_per_1_minute: + type: integer + description: The maximum requests per minute. + max_tokens_per_1_minute: + type: integer + description: The maximum tokens per minute. + max_images_per_1_minute: + type: integer + description: The maximum images per minute. Only present for relevant models. + max_audio_megabytes_per_1_minute: + type: integer + description: >- + The maximum audio megabytes per minute. Only present for relevant + models. + max_requests_per_1_day: + type: integer + description: The maximum requests per day. Only present for relevant models. + batch_1_day_max_input_tokens: + type: integer + description: >- + The maximum batch input tokens per day. Only present for relevant + models. + required: + - object + - id + - model + - max_requests_per_1_minute + - max_tokens_per_1_minute + x-oaiMeta: + name: The project rate limit object + example: | + { + "object": "project.rate_limit", + "id": "rl_ada", + "model": "ada", + "max_requests_per_1_minute": 600, + "max_tokens_per_1_minute": 150000, + "max_images_per_1_minute": 10 + } + ProjectRateLimitListResponse: + type: object + properties: + object: + type: string + enum: + - list + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/ProjectRateLimit' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + ProjectRateLimitUpdateRequest: + type: object + properties: + max_requests_per_1_minute: + type: integer + description: The maximum requests per minute. + max_tokens_per_1_minute: + type: integer + description: The maximum tokens per minute. + max_images_per_1_minute: + type: integer + description: The maximum images per minute. Only relevant for certain models. + max_audio_megabytes_per_1_minute: + type: integer + description: >- + The maximum audio megabytes per minute. Only relevant for certain + models. + max_requests_per_1_day: + type: integer + description: The maximum requests per day. Only relevant for certain models. + batch_1_day_max_input_tokens: + type: integer + description: >- + The maximum batch input tokens per day. Only relevant for certain + models. + ProjectServiceAccount: + type: object + description: Represents an individual service account in a project. + properties: + object: + type: string + enum: + - organization.project.service_account + description: >- + The object type, which is always + `organization.project.service_account` + x-stainless-const: true + id: + type: string + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the service account + role: + type: string + enum: + - owner + - member + description: '`owner` or `member`' + created_at: + type: integer + description: >- + The Unix timestamp (in seconds) of when the service account was + created + required: + - object + - id + - name + - role + - created_at + x-oaiMeta: + name: The project service account object + example: | + { + "object": "organization.project.service_account", + "id": "svc_acct_abc", + "name": "Service Account", + "role": "owner", + "created_at": 1711471533 + } + ProjectServiceAccountApiKey: + type: object + properties: + object: + type: string + enum: + - organization.project.service_account.api_key + description: >- + The object type, which is always + `organization.project.service_account.api_key` + x-stainless-const: true + value: + type: string + name: + type: string + created_at: + type: integer + id: + type: string + required: + - object + - value + - name + - created_at + - id + ProjectServiceAccountCreateRequest: + type: object + properties: + name: + type: string + description: The name of the service account being created. + required: + - name + ProjectServiceAccountCreateResponse: + type: object + properties: + object: + type: string + enum: + - organization.project.service_account + x-stainless-const: true + id: + type: string + name: + type: string + role: + type: string + enum: + - member + description: Service accounts can only have one role of type `member` + x-stainless-const: true + created_at: + type: integer + api_key: + $ref: '#/components/schemas/ProjectServiceAccountApiKey' + required: + - object + - id + - name + - role + - created_at + - api_key + ProjectServiceAccountDeleteResponse: + type: object + properties: + object: + type: string + enum: + - organization.project.service_account.deleted + x-stainless-const: true + id: + type: string + deleted: + type: boolean + required: + - object + - id + - deleted + ProjectServiceAccountListResponse: + type: object + properties: + object: + type: string + enum: + - list + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/ProjectServiceAccount' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + ProjectUpdateRequest: + type: object + properties: + name: + type: string + description: The updated name of the project, this name appears in reports. + required: + - name + ProjectUser: + type: object + description: Represents an individual user in a project. + properties: + object: + type: string + enum: + - organization.project.user + description: The object type, which is always `organization.project.user` + x-stainless-const: true + id: + type: string + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the user + email: + type: string + description: The email address of the user + role: + type: string + enum: + - owner + - member + description: '`owner` or `member`' + added_at: + type: integer + description: The Unix timestamp (in seconds) of when the project was added. + required: + - object + - id + - name + - email + - role + - added_at + x-oaiMeta: + name: The project user object + example: | + { + "object": "organization.project.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + ProjectUserCreateRequest: + type: object + properties: + user_id: + type: string + description: The ID of the user. + role: + type: string + enum: + - owner + - member + description: '`owner` or `member`' + required: + - user_id + - role + ProjectUserDeleteResponse: + type: object + properties: + object: + type: string + enum: + - organization.project.user.deleted + x-stainless-const: true + id: + type: string + deleted: + type: boolean + required: + - object + - id + - deleted + ProjectUserListResponse: + type: object + properties: + object: + type: string + data: + type: array + items: + $ref: '#/components/schemas/ProjectUser' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + ProjectUserUpdateRequest: + type: object + properties: + role: + type: string + enum: + - owner + - member + description: '`owner` or `member`' + required: + - role + Prompt: + anyOf: + - type: object + description: | + Reference to a prompt template and its variables. + [Learn more](/docs/guides/text?api-mode=responses#reusable-prompts). + required: + - id + properties: + id: + type: string + description: The unique identifier of the prompt template to use. + version: + anyOf: + - type: string + description: Optional version of the prompt template. + - type: 'null' + variables: + $ref: '#/components/schemas/ResponsePromptVariables' + - type: 'null' + PublicAssignOrganizationGroupRoleBody: + type: object + description: Request payload for assigning a role to a group or user. + properties: + role_id: + type: string + description: Identifier of the role to assign. + required: + - role_id + x-oaiMeta: + example: | + { + "role_id": "role_01J1F8ROLE01" + } + PublicCreateOrganizationRoleBody: + type: object + description: Request payload for creating a custom role. + properties: + role_name: + type: string + description: Unique name for the role. + permissions: + type: array + description: Permissions to grant to the role. + items: + type: string + description: + description: Optional description of the role. + anyOf: + - type: string + - type: 'null' + required: + - role_name + - permissions + x-oaiMeta: + example: | + { + "role_name": "API Group Manager", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "description": "Allows managing organization groups" + } + PublicRoleListResource: + type: object + description: Paginated list of roles available on an organization or project. + properties: + object: + type: string + enum: + - list + description: Always `list`. + x-stainless-const: true + data: + type: array + description: Roles returned in the current page. + items: + $ref: '#/components/schemas/Role' + has_more: + type: boolean + description: Whether more roles are available when paginating. + next: + description: >- + Cursor to fetch the next page of results, or `null` when there are + no additional roles. + anyOf: + - type: string + - type: 'null' + required: + - object + - data + - has_more + - next + x-oaiMeta: + name: Role list + example: | + { + "object": "list", + "data": [ + { + "object": "role", + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "description": "Allows managing organization groups", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false + } + ], + "has_more": false, + "next": null + } + PublicUpdateOrganizationRoleBody: + type: object + description: Request payload for updating an existing role. + properties: + permissions: + description: Updated set of permissions for the role. + anyOf: + - type: array + items: + type: string + - type: 'null' + description: + description: New description for the role. + anyOf: + - type: string + - type: 'null' + role_name: + description: New name for the role. + anyOf: + - type: string + - type: 'null' + x-oaiMeta: + example: | + { + "role_name": "API Group Manager", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "description": "Allows managing organization groups" + } + RealtimeAudioFormats: + anyOf: + - type: object + title: PCM audio format + description: The PCM audio format. Only a 24kHz sample rate is supported. + properties: + type: + type: string + description: The audio format. Always `audio/pcm`. + enum: + - audio/pcm + rate: + type: integer + description: The sample rate of the audio. Always `24000`. + enum: + - 24000 + - type: object + title: PCMU audio format + description: The G.711 μ-law format. + properties: + type: + type: string + description: The audio format. Always `audio/pcmu`. + enum: + - audio/pcmu + - type: object + title: PCMA audio format + description: The G.711 A-law format. + properties: + type: + type: string + description: The audio format. Always `audio/pcma`. + enum: + - audio/pcma + RealtimeBetaClientEventConversationItemCreate: + type: object + description: > + Add a new Item to the Conversation's context, including messages, + function + + calls, and function call responses. This event can be used both to + populate a + + "history" of the conversation and to add new items mid-stream, but has + the + + current limitation that it cannot populate assistant audio messages. + + + If successful, the server will respond with a + `conversation.item.created` + + event, otherwise an `error` event will be sent. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - conversation.item.create + description: The event type, must be `conversation.item.create`. + x-stainless-const: true + previous_item_id: + type: string + description: > + The ID of the preceding item after which the new item will be + inserted. + + If not set, the new item will be appended to the end of the + conversation. + + If set to `root`, the new item will be added to the beginning of the + conversation. + + If set to an existing ID, it allows an item to be inserted + mid-conversation. If the + + ID cannot be found, an error will be returned and the item will not + be added. + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - type + - item + x-oaiMeta: + name: conversation.item.create + group: realtime + example: | + { + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "hi" + } + ] + }, + "event_id": "b904fba0-0ec4-40af-8bbb-f908a9b26793", + } + RealtimeBetaClientEventConversationItemDelete: + type: object + description: > + Send this event when you want to remove any item from the conversation + + history. The server will respond with a `conversation.item.deleted` + event, + + unless the item does not exist in the conversation history, in which + case the + + server will respond with an error. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - conversation.item.delete + description: The event type, must be `conversation.item.delete`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item to delete. + required: + - type + - item_id + x-oaiMeta: + name: conversation.item.delete + group: realtime + example: | + { + "event_id": "event_901", + "type": "conversation.item.delete", + "item_id": "msg_003" + } + RealtimeBetaClientEventConversationItemRetrieve: + type: object + description: > + Send this event when you want to retrieve the server's representation of + a specific item in the conversation history. This is useful, for + example, to inspect user audio after noise cancellation and VAD. + + The server will respond with a `conversation.item.retrieved` event, + + unless the item does not exist in the conversation history, in which + case the + + server will respond with an error. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - conversation.item.retrieve + description: The event type, must be `conversation.item.retrieve`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item to retrieve. + required: + - type + - item_id + x-oaiMeta: + name: conversation.item.retrieve + group: realtime + example: | + { + "event_id": "event_901", + "type": "conversation.item.retrieve", + "item_id": "msg_003" + } + RealtimeBetaClientEventConversationItemTruncate: + type: object + description: > + Send this event to truncate a previous assistant message’s audio. The + server + + will produce audio faster than realtime, so this event is useful when + the user + + interrupts to truncate audio that has already been sent to the client + but not + + yet played. This will synchronize the server's understanding of the + audio with + + the client's playback. + + + Truncating audio will delete the server-side text transcript to ensure + there + + is not text in the context that hasn't been heard by the user. + + + If successful, the server will respond with a + `conversation.item.truncated` + + event. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - conversation.item.truncate + description: The event type, must be `conversation.item.truncate`. + x-stainless-const: true + item_id: + type: string + description: > + The ID of the assistant message item to truncate. Only assistant + message + + items can be truncated. + content_index: + type: integer + description: The index of the content part to truncate. Set this to 0. + audio_end_ms: + type: integer + description: > + Inclusive duration up to which audio is truncated, in milliseconds. + If + + the audio_end_ms is greater than the actual audio duration, the + server + + will respond with an error. + required: + - type + - item_id + - content_index + - audio_end_ms + x-oaiMeta: + name: conversation.item.truncate + group: realtime + example: | + { + "event_id": "event_678", + "type": "conversation.item.truncate", + "item_id": "msg_002", + "content_index": 0, + "audio_end_ms": 1500 + } + RealtimeBetaClientEventInputAudioBufferAppend: + type: object + description: > + Send this event to append audio bytes to the input audio buffer. The + audio + + buffer is temporary storage you can write to and later commit. In Server + VAD + + mode, the audio buffer is used to detect speech and the server will + decide + + when to commit. When Server VAD is disabled, you must commit the audio + buffer + + manually. + + + The client may choose how much audio to place in each event up to a + maximum + + of 15 MiB, for example streaming smaller chunks from the client may + allow the + + VAD to be more responsive. Unlike made other client events, the server + will + + not send a confirmation response to this event. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - input_audio_buffer.append + description: The event type, must be `input_audio_buffer.append`. + x-stainless-const: true + audio: + type: string + description: > + Base64-encoded audio bytes. This must be in the format specified by + the + + `input_audio_format` field in the session configuration. + required: + - type + - audio + x-oaiMeta: + name: input_audio_buffer.append + group: realtime + example: | + { + "event_id": "event_456", + "type": "input_audio_buffer.append", + "audio": "Base64EncodedAudioData" + } + RealtimeBetaClientEventInputAudioBufferClear: + type: object + description: | + Send this event to clear the audio bytes in the buffer. The server will + respond with an `input_audio_buffer.cleared` event. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - input_audio_buffer.clear + description: The event type, must be `input_audio_buffer.clear`. + x-stainless-const: true + required: + - type + x-oaiMeta: + name: input_audio_buffer.clear + group: realtime + example: | + { + "event_id": "event_012", + "type": "input_audio_buffer.clear" + } + RealtimeBetaClientEventInputAudioBufferCommit: + type: object + description: > + Send this event to commit the user input audio buffer, which will create + a + + new user message item in the conversation. This event will produce an + error + + if the input audio buffer is empty. When in Server VAD mode, the client + does + + not need to send this event, the server will commit the audio buffer + + automatically. + + + Committing the input audio buffer will trigger input audio + transcription + + (if enabled in session configuration), but it will not create a + response + + from the model. The server will respond with an + `input_audio_buffer.committed` + + event. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - input_audio_buffer.commit + description: The event type, must be `input_audio_buffer.commit`. + x-stainless-const: true + required: + - type + x-oaiMeta: + name: input_audio_buffer.commit + group: realtime + example: | + { + "event_id": "event_789", + "type": "input_audio_buffer.commit" + } + RealtimeBetaClientEventOutputAudioBufferClear: + type: object + description: > + **WebRTC/SIP Only:** Emit to cut off the current audio response. This + will trigger the server to + + stop generating audio and emit a `output_audio_buffer.cleared` event. + This + + event should be preceded by a `response.cancel` client event to stop the + + generation of the current response. + + [Learn + more](/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). + properties: + event_id: + type: string + description: The unique ID of the client event used for error handling. + type: + type: string + enum: + - output_audio_buffer.clear + description: The event type, must be `output_audio_buffer.clear`. + x-stainless-const: true + required: + - type + x-oaiMeta: + name: output_audio_buffer.clear + group: realtime + example: | + { + "event_id": "optional_client_event_id", + "type": "output_audio_buffer.clear" + } + RealtimeBetaClientEventResponseCancel: + type: object + description: > + Send this event to cancel an in-progress response. The server will + respond + + with a `response.done` event with a status of + `response.status=cancelled`. If + + there is no response to cancel, the server will respond with an error. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - response.cancel + description: The event type, must be `response.cancel`. + x-stainless-const: true + response_id: + type: string + description: | + A specific response ID to cancel - if not provided, will cancel an + in-progress response in the default conversation. + required: + - type + x-oaiMeta: + name: response.cancel + group: realtime + example: | + { + "event_id": "event_567", + "type": "response.cancel" + } + RealtimeBetaClientEventResponseCreate: + type: object + description: > + This event instructs the server to create a Response, which means + triggering + + model inference. When in Server VAD mode, the server will create + Responses + + automatically. + + + A Response will include at least one Item, and may have two, in which + case + + the second will be a function call. These Items will be appended to the + + conversation history. + + + The server will respond with a `response.created` event, events for + Items + + and content created, and finally a `response.done` event to indicate + the + + Response is complete. + + + The `response.create` event can optionally include inference + configuration like + + `instructions`, and `temperature`. These fields will override the + Session's + + configuration for this Response only. + + + Responses can be created out-of-band of the default Conversation, + meaning that they can + + have arbitrary input, and it's possible to disable writing the output to + the Conversation. + + Only one Response can write to the default Conversation at a time, but + otherwise multiple + + Responses can be created in parallel. + + + Clients can set `conversation` to `none` to create a Response that does + not write to the default + + Conversation. Arbitrary input can be provided with the `input` field, + which is an array accepting + + raw Items and references to existing Items. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - response.create + description: The event type, must be `response.create`. + x-stainless-const: true + response: + $ref: '#/components/schemas/RealtimeBetaResponseCreateParams' + required: + - type + x-oaiMeta: + name: response.create + group: realtime + example: > + // Trigger a response with the default Conversation and no special + parameters + + { + "type": "response.create", + } + + + // Trigger an out-of-band response that does not write to the default + Conversation + + { + "type": "response.create", + "response": { + "instructions": "Provide a concise answer.", + "tools": [], // clear any session tools + "conversation": "none", + "output_modalities": ["text"], + "input": [ + { + "type": "item_reference", + "id": "item_12345", + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "Summarize the above message in one sentence." + } + ] + } + ], + } + } + RealtimeBetaClientEventSessionUpdate: + type: object + description: > + Send this event to update the session’s default configuration. + + The client may send this event at any time to update any field, + + except for `voice`. However, note that once a session has been + + initialized with a particular `model`, it can’t be changed to + + another model using `session.update`. + + + When the server receives a `session.update`, it will respond + + with a `session.updated` event showing the full, effective + configuration. + + Only the fields that are present are updated. To clear a field like + + `instructions`, pass an empty string. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - session.update + description: The event type, must be `session.update`. + x-stainless-const: true + session: + $ref: '#/components/schemas/RealtimeSessionCreateRequest' + required: + - type + - session + x-oaiMeta: + name: session.update + group: realtime + example: | + { + "type": "session.update", + "session": { + "tools": [ + { + "type": "function", + "name": "display_color_palette", + "description": "Call this function when a user asks for a color palette.", + "parameters": { + "type": "object", + "properties": { + "theme": { + "type": "string", + "description": "Description of the theme for the color scheme." + }, + "colors": { + "type": "array", + "description": "Array of five hex color codes based on the theme.", + "items": { + "type": "string", + "description": "Hex color code" + } + } + }, + "required": [ + "theme", + "colors" + ] + } + } + ], + "tool_choice": "auto" + } + } + RealtimeBetaClientEventTranscriptionSessionUpdate: + type: object + description: | + Send this event to update a transcription session. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - transcription_session.update + description: The event type, must be `transcription_session.update`. + x-stainless-const: true + session: + $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequest' + required: + - type + - session + x-oaiMeta: + name: transcription_session.update + group: realtime + example: | + { + "type": "transcription_session.update", + "session": { + "input_audio_format": "pcm16", + "input_audio_transcription": { + "model": "gpt-4o-transcribe", + "prompt": "", + "language": "" + }, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 500, + "create_response": true, + }, + "input_audio_noise_reduction": { + "type": "near_field" + }, + "include": [ + "item.input_audio_transcription.logprobs", + ] + } + } + RealtimeBetaResponse: + type: object + description: The response resource. + properties: + id: + type: string + description: The unique ID of the response. + object: + type: string + enum: + - realtime.response + description: The object type, must be `realtime.response`. + x-stainless-const: true + status: + type: string + enum: + - completed + - cancelled + - failed + - incomplete + - in_progress + description: > + The final status of the response (`completed`, `cancelled`, + `failed`, or + + `incomplete`, `in_progress`). + status_details: + type: object + description: Additional details about the status. + properties: + type: + type: string + enum: + - completed + - cancelled + - failed + - incomplete + description: > + The type of error that caused the response to fail, + corresponding + + with the `status` field (`completed`, `cancelled`, + `incomplete`, + + `failed`). + reason: + type: string + enum: + - turn_detected + - client_cancelled + - max_output_tokens + - content_filter + description: > + The reason the Response did not complete. For a `cancelled` + Response, + + one of `turn_detected` (the server VAD detected a new start of + speech) + + or `client_cancelled` (the client sent a cancel event). For an + + `incomplete` Response, one of `max_output_tokens` or + `content_filter` + + (the server-side safety filter activated and cut off the + response). + error: + type: object + description: | + A description of the error that caused the response to fail, + populated when the `status` is `failed`. + properties: + type: + type: string + description: The type of error. + code: + type: string + description: Error code, if any. + output: + type: array + description: The list of output items generated by the response. + items: + $ref: '#/components/schemas/RealtimeConversationItem' + metadata: + $ref: '#/components/schemas/Metadata' + usage: + type: object + description: > + Usage statistics for the Response, this will correspond to billing. + A + + Realtime API session will maintain a conversation context and append + new + + Items to the Conversation, thus output from previous turns (text + and + + audio tokens) will become the input for later turns. + properties: + total_tokens: + type: integer + description: > + The total number of tokens in the Response including input and + output + + text and audio tokens. + input_tokens: + type: integer + description: > + The number of input tokens used in the Response, including text + and + + audio tokens. + output_tokens: + type: integer + description: > + The number of output tokens sent in the Response, including text + and + + audio tokens. + input_token_details: + type: object + description: Details about the input tokens used in the Response. + properties: + cached_tokens: + type: integer + description: The number of cached tokens used as input for the Response. + text_tokens: + type: integer + description: The number of text tokens used as input for the Response. + image_tokens: + type: integer + description: The number of image tokens used as input for the Response. + audio_tokens: + type: integer + description: The number of audio tokens used as input for the Response. + cached_tokens_details: + type: object + description: >- + Details about the cached tokens used as input for the + Response. + properties: + text_tokens: + type: integer + description: >- + The number of cached text tokens used as input for the + Response. + image_tokens: + type: integer + description: >- + The number of cached image tokens used as input for the + Response. + audio_tokens: + type: integer + description: >- + The number of cached audio tokens used as input for the + Response. + output_token_details: + type: object + description: Details about the output tokens used in the Response. + properties: + text_tokens: + type: integer + description: The number of text tokens used in the Response. + audio_tokens: + type: integer + description: The number of audio tokens used in the Response. + conversation_id: + description: > + Which conversation the response is added to, determined by the + `conversation` + + field in the `response.create` event. If `auto`, the response will + be added to + + the default conversation and the value of `conversation_id` will be + an id like + + `conv_1234`. If `none`, the response will not be added to any + conversation and + + the value of `conversation_id` will be `null`. If responses are + being triggered + + by server VAD, the response will be added to the default + conversation, thus + + the `conversation_id` will be an id like `conv_1234`. + type: string + voice: + $ref: '#/components/schemas/VoiceIdsShared' + description: > + The voice the model used to respond. + + Current voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, + `sage`, + + `shimmer`, and `verse`. + modalities: + type: array + description: > + The set of modalities the model used to respond. If there are + multiple modalities, + + the model will pick one, for example if `modalities` is `["text", + "audio"]`, the model + + could be responding in either text or audio. + items: + type: string + enum: + - text + - audio + output_audio_format: + type: string + enum: + - pcm16 + - g711_ulaw + - g711_alaw + description: > + The format of output audio. Options are `pcm16`, `g711_ulaw`, or + `g711_alaw`. + temperature: + type: number + description: > + Sampling temperature for the model, limited to [0.6, 1.2]. Defaults + to 0.8. + max_output_tokens: + oneOf: + - type: integer + - type: string + enum: + - inf + x-stainless-const: true + description: | + Maximum number of output tokens for a single assistant response, + inclusive of tool calls, that was used in this response. + RealtimeBetaResponseCreateParams: + type: object + description: Create a new Realtime response with these parameters + properties: + modalities: + type: array + description: | + The set of modalities the model can respond with. To disable audio, + set this to ["text"]. + items: + type: string + enum: + - text + - audio + instructions: + type: string + description: > + The default system instructions (i.e. system message) prepended to + model + + calls. This field allows the client to guide the model on desired + + responses. The model can be instructed on response content and + format, + + (e.g. "be extremely succinct", "act friendly", "here are examples of + good + + responses") and on audio behavior (e.g. "talk quickly", "inject + emotion + + into your voice", "laugh frequently"). The instructions are not + guaranteed + + to be followed by the model, but they provide guidance to the model + on the + + desired behavior. + + + Note that the server sets default instructions which will be used if + this + + field is not set and are visible in the `session.created` event at + the + + start of the session. + voice: + $ref: '#/components/schemas/VoiceIdsOrCustomVoice' + description: > + The voice the model uses to respond. Supported built-in voices are + + `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, + `verse`, + + `marin`, and `cedar`. You may also provide a custom voice object + with an + + `id`, for example `{ "id": "voice_1234" }`. Voice cannot be changed + during + + the session once the model has responded with audio at least once. + output_audio_format: + type: string + enum: + - pcm16 + - g711_ulaw + - g711_alaw + description: > + The format of output audio. Options are `pcm16`, `g711_ulaw`, or + `g711_alaw`. + tools: + type: array + description: Tools (functions) available to the model. + items: + type: object + properties: + type: + type: string + enum: + - function + description: The type of the tool, i.e. `function`. + x-stainless-const: true + name: + type: string + description: The name of the function. + description: + type: string + description: > + The description of the function, including guidance on when + and how + + to call it, and guidance about what to tell the user when + calling + + (if anything). + parameters: + type: object + description: Parameters of the function in JSON Schema. + tool_choice: + description: > + How the model chooses tools. Provide one of the string modes or + force a specific + + function/MCP tool. + oneOf: + - $ref: '#/components/schemas/ToolChoiceOptions' + - $ref: '#/components/schemas/ToolChoiceFunction' + - $ref: '#/components/schemas/ToolChoiceMCP' + default: auto + temperature: + type: number + description: > + Sampling temperature for the model, limited to [0.6, 1.2]. Defaults + to 0.8. + max_output_tokens: + oneOf: + - type: integer + - type: string + enum: + - inf + x-stainless-const: true + description: | + Maximum number of output tokens for a single assistant response, + inclusive of tool calls. Provide an integer between 1 and 4096 to + limit output tokens, or `inf` for the maximum available tokens for a + given model. Defaults to `inf`. + conversation: + description: > + Controls which conversation the response is added to. Currently + supports + + `auto` and `none`, with `auto` as the default value. The `auto` + value + + means that the contents of the response will be added to the default + + conversation. Set this to `none` to create an out-of-band response + which + + will not add items to default conversation. + oneOf: + - type: string + - type: string + default: auto + enum: + - auto + - none + metadata: + $ref: '#/components/schemas/Metadata' + prompt: + $ref: '#/components/schemas/Prompt' + input: + type: array + description: > + Input items to include in the prompt for the model. Using this field + + creates a new context for this Response instead of using the default + + conversation. An empty array `[]` will clear the context for this + Response. + + Note that this can include references to items from the default + conversation. + items: + $ref: '#/components/schemas/RealtimeConversationItem' + RealtimeBetaServerEventConversationItemCreated: + type: object + description: > + Returned when a conversation item is created. There are several + scenarios that produce this event: + - The server is generating a Response, which if successful will produce + either one or two Items, which will be of type `message` + (role `assistant`) or type `function_call`. + - The input audio buffer has been committed, either by the client or the + server (in `server_vad` mode). The server will take the content of the + input audio buffer and add it to a new user message Item. + - The client has sent a `conversation.item.create` event to add a new Item + to the Conversation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.created + description: The event type, must be `conversation.item.created`. + x-stainless-const: true + previous_item_id: + anyOf: + - type: string + description: > + The ID of the preceding item in the Conversation context, allows + the + + client to understand the order of the conversation. Can be + `null` if the + + item has no predecessor. + - type: 'null' + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - item + x-oaiMeta: + name: conversation.item.created + group: realtime + example: | + { + "event_id": "event_1920", + "type": "conversation.item.created", + "previous_item_id": "msg_002", + "item": { + "id": "msg_003", + "object": "realtime.item", + "type": "message", + "status": "completed", + "role": "user", + "content": [] + } + } + RealtimeBetaServerEventConversationItemDeleted: + type: object + description: > + Returned when an item in the conversation is deleted by the client with + a + + `conversation.item.delete` event. This event is used to synchronize the + + server's understanding of the conversation history with the client's + view. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.deleted + description: The event type, must be `conversation.item.deleted`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item that was deleted. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: conversation.item.deleted + group: realtime + example: | + { + "event_id": "event_2728", + "type": "conversation.item.deleted", + "item_id": "msg_005" + } + RealtimeBetaServerEventConversationItemInputAudioTranscriptionCompleted: + type: object + description: > + This event is the output of audio transcription for user audio written + to the + + user audio buffer. Transcription begins when the input audio buffer is + + committed by the client or server (in `server_vad` mode). Transcription + runs + + asynchronously with Response creation, so this event may come before or + after + + the Response events. + + + Realtime API models accept audio natively, and thus input transcription + is a + + separate process run on a separate ASR (Automatic Speech Recognition) + model. + + The transcript may diverge somewhat from the model's interpretation, and + + should be treated as a rough guide. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.input_audio_transcription.completed + description: | + The event type, must be + `conversation.item.input_audio_transcription.completed`. + x-stainless-const: true + item_id: + type: string + description: The ID of the user message item containing the audio. + content_index: + type: integer + description: The index of the content part containing the audio. + transcript: + type: string + description: The transcribed text. + logprobs: + anyOf: + - type: array + description: The log probabilities of the transcription. + items: + $ref: '#/components/schemas/LogProbProperties' + - type: 'null' + usage: + type: object + description: Usage statistics for the transcription. + oneOf: + - $ref: '#/components/schemas/TranscriptTextUsageTokens' + title: Token Usage + - $ref: '#/components/schemas/TranscriptTextUsageDuration' + title: Duration Usage + required: + - event_id + - type + - item_id + - content_index + - transcript + - usage + x-oaiMeta: + name: conversation.item.input_audio_transcription.completed + group: realtime + example: | + { + "event_id": "event_2122", + "type": "conversation.item.input_audio_transcription.completed", + "item_id": "msg_003", + "content_index": 0, + "transcript": "Hello, how are you?", + "usage": { + "type": "tokens", + "total_tokens": 48, + "input_tokens": 38, + "input_token_details": { + "text_tokens": 10, + "audio_tokens": 28, + }, + "output_tokens": 10, + } + } + RealtimeBetaServerEventConversationItemInputAudioTranscriptionDelta: + type: object + description: > + Returned when the text value of an input audio transcription content + part is updated. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.input_audio_transcription.delta + description: >- + The event type, must be + `conversation.item.input_audio_transcription.delta`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item. + content_index: + type: integer + description: The index of the content part in the item's content array. + delta: + type: string + description: The text delta. + logprobs: + anyOf: + - type: array + description: The log probabilities of the transcription. + items: + $ref: '#/components/schemas/LogProbProperties' + - type: 'null' + required: + - event_id + - type + - item_id + x-oaiMeta: + name: conversation.item.input_audio_transcription.delta + group: realtime + example: | + { + "type": "conversation.item.input_audio_transcription.delta", + "event_id": "event_001", + "item_id": "item_001", + "content_index": 0, + "delta": "Hello" + } + RealtimeBetaServerEventConversationItemInputAudioTranscriptionFailed: + type: object + description: > + Returned when input audio transcription is configured, and a + transcription + + request for a user message failed. These events are separate from other + + `error` events so that the client can identify the related Item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.input_audio_transcription.failed + description: | + The event type, must be + `conversation.item.input_audio_transcription.failed`. + x-stainless-const: true + item_id: + type: string + description: The ID of the user message item. + content_index: + type: integer + description: The index of the content part containing the audio. + error: + type: object + description: Details of the transcription error. + properties: + type: + type: string + description: The type of error. + code: + type: string + description: Error code, if any. + message: + type: string + description: A human-readable error message. + param: + type: string + description: Parameter related to the error, if any. + required: + - event_id + - type + - item_id + - content_index + - error + x-oaiMeta: + name: conversation.item.input_audio_transcription.failed + group: realtime + example: | + { + "event_id": "event_2324", + "type": "conversation.item.input_audio_transcription.failed", + "item_id": "msg_003", + "content_index": 0, + "error": { + "type": "transcription_error", + "code": "audio_unintelligible", + "message": "The audio could not be transcribed.", + "param": null + } + } + RealtimeBetaServerEventConversationItemInputAudioTranscriptionSegment: + type: object + description: >- + Returned when an input audio transcription segment is identified for an + item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.input_audio_transcription.segment + description: >- + The event type, must be + `conversation.item.input_audio_transcription.segment`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item containing the input audio content. + content_index: + type: integer + description: The index of the input audio content part within the item. + text: + type: string + description: The text for this segment. + id: + type: string + description: The segment identifier. + speaker: + type: string + description: The detected speaker label for this segment. + start: + type: number + format: float + description: Start time of the segment in seconds. + end: + type: number + format: float + description: End time of the segment in seconds. + required: + - event_id + - type + - item_id + - content_index + - text + - id + - speaker + - start + - end + x-oaiMeta: + name: conversation.item.input_audio_transcription.segment + group: realtime + example: | + { + "event_id": "event_6501", + "type": "conversation.item.input_audio_transcription.segment", + "item_id": "msg_011", + "content_index": 0, + "text": "hello", + "id": "seg_0001", + "speaker": "spk_1", + "start": 0.0, + "end": 0.4 + } + RealtimeBetaServerEventConversationItemRetrieved: + type: object + description: > + Returned when a conversation item is retrieved with + `conversation.item.retrieve`. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.retrieved + description: The event type, must be `conversation.item.retrieved`. + x-stainless-const: true + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - item + x-oaiMeta: + name: conversation.item.retrieved + group: realtime + example: | + { + "event_id": "event_1920", + "type": "conversation.item.created", + "previous_item_id": "msg_002", + "item": { + "id": "msg_003", + "object": "realtime.item", + "type": "message", + "status": "completed", + "role": "user", + "content": [ + { + "type": "input_audio", + "transcript": "hello how are you", + "audio": "base64encodedaudio==" + } + ] + } + } + RealtimeBetaServerEventConversationItemTruncated: + type: object + description: > + Returned when an earlier assistant audio message item is truncated by + the + + client with a `conversation.item.truncate` event. This event is used to + + synchronize the server's understanding of the audio with the client's + playback. + + + This action will truncate the audio and remove the server-side text + transcript + + to ensure there is no text in the context that hasn't been heard by the + user. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.truncated + description: The event type, must be `conversation.item.truncated`. + x-stainless-const: true + item_id: + type: string + description: The ID of the assistant message item that was truncated. + content_index: + type: integer + description: The index of the content part that was truncated. + audio_end_ms: + type: integer + description: | + The duration up to which the audio was truncated, in milliseconds. + required: + - event_id + - type + - item_id + - content_index + - audio_end_ms + x-oaiMeta: + name: conversation.item.truncated + group: realtime + example: | + { + "event_id": "event_2526", + "type": "conversation.item.truncated", + "item_id": "msg_004", + "content_index": 0, + "audio_end_ms": 1500 + } + RealtimeBetaServerEventError: + type: object + description: > + Returned when an error occurs, which could be a client problem or a + server + + problem. Most errors are recoverable and the session will stay open, we + + recommend to implementors to monitor and log error messages by default. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - error + description: The event type, must be `error`. + x-stainless-const: true + error: + type: object + description: Details of the error. + required: + - type + - message + properties: + type: + type: string + description: > + The type of error (e.g., "invalid_request_error", + "server_error"). + code: + anyOf: + - type: string + description: Error code, if any. + - type: 'null' + message: + type: string + description: A human-readable error message. + param: + anyOf: + - type: string + description: Parameter related to the error, if any. + - type: 'null' + event_id: + anyOf: + - type: string + description: > + The event_id of the client event that caused the error, if + applicable. + - type: 'null' + required: + - event_id + - type + - error + x-oaiMeta: + name: error + group: realtime + example: | + { + "event_id": "event_890", + "type": "error", + "error": { + "type": "invalid_request_error", + "code": "invalid_event", + "message": "The 'type' field is missing.", + "param": null, + "event_id": "event_567" + } + } + RealtimeBetaServerEventInputAudioBufferCleared: + type: object + description: | + Returned when the input audio buffer is cleared by the client with a + `input_audio_buffer.clear` event. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - input_audio_buffer.cleared + description: The event type, must be `input_audio_buffer.cleared`. + x-stainless-const: true + required: + - event_id + - type + x-oaiMeta: + name: input_audio_buffer.cleared + group: realtime + example: | + { + "event_id": "event_1314", + "type": "input_audio_buffer.cleared" + } + RealtimeBetaServerEventInputAudioBufferCommitted: + type: object + description: > + Returned when an input audio buffer is committed, either by the client + or + + automatically in server VAD mode. The `item_id` property is the ID of + the user + + message item that will be created, thus a `conversation.item.created` + event + + will also be sent to the client. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - input_audio_buffer.committed + description: The event type, must be `input_audio_buffer.committed`. + x-stainless-const: true + previous_item_id: + anyOf: + - type: string + description: > + The ID of the preceding item after which the new item will be + inserted. + + Can be `null` if the item has no predecessor. + - type: 'null' + item_id: + type: string + description: The ID of the user message item that will be created. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: input_audio_buffer.committed + group: realtime + example: | + { + "event_id": "event_1121", + "type": "input_audio_buffer.committed", + "previous_item_id": "msg_001", + "item_id": "msg_002" + } + RealtimeBetaServerEventInputAudioBufferSpeechStarted: + type: object + description: > + Sent by the server when in `server_vad` mode to indicate that speech has + been + + detected in the audio buffer. This can happen any time audio is added to + the + + buffer (unless speech is already detected). The client may want to use + this + + event to interrupt audio playback or provide visual feedback to the + user. + + + The client should expect to receive a + `input_audio_buffer.speech_stopped` event + + when speech stops. The `item_id` property is the ID of the user message + item + + that will be created when speech stops and will also be included in the + + `input_audio_buffer.speech_stopped` event (unless the client manually + commits + + the audio buffer during VAD activation). + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - input_audio_buffer.speech_started + description: The event type, must be `input_audio_buffer.speech_started`. + x-stainless-const: true + audio_start_ms: + type: integer + description: > + Milliseconds from the start of all audio written to the buffer + during the + + session when speech was first detected. This will correspond to the + + beginning of audio sent to the model, and thus includes the + + `prefix_padding_ms` configured in the Session. + item_id: + type: string + description: > + The ID of the user message item that will be created when speech + stops. + required: + - event_id + - type + - audio_start_ms + - item_id + x-oaiMeta: + name: input_audio_buffer.speech_started + group: realtime + example: | + { + "event_id": "event_1516", + "type": "input_audio_buffer.speech_started", + "audio_start_ms": 1000, + "item_id": "msg_003" + } + RealtimeBetaServerEventInputAudioBufferSpeechStopped: + type: object + description: > + Returned in `server_vad` mode when the server detects the end of speech + in + + the audio buffer. The server will also send an + `conversation.item.created` + + event with the user message item that is created from the audio buffer. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - input_audio_buffer.speech_stopped + description: The event type, must be `input_audio_buffer.speech_stopped`. + x-stainless-const: true + audio_end_ms: + type: integer + description: > + Milliseconds since the session started when speech stopped. This + will + + correspond to the end of audio sent to the model, and thus includes + the + + `min_silence_duration_ms` configured in the Session. + item_id: + type: string + description: The ID of the user message item that will be created. + required: + - event_id + - type + - audio_end_ms + - item_id + x-oaiMeta: + name: input_audio_buffer.speech_stopped + group: realtime + example: | + { + "event_id": "event_1718", + "type": "input_audio_buffer.speech_stopped", + "audio_end_ms": 2000, + "item_id": "msg_003" + } + RealtimeBetaServerEventMCPListToolsCompleted: + type: object + description: Returned when listing MCP tools has completed for an item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - mcp_list_tools.completed + description: The event type, must be `mcp_list_tools.completed`. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP list tools item. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: mcp_list_tools.completed + group: realtime + example: | + { + "event_id": "event_6102", + "type": "mcp_list_tools.completed", + "item_id": "mcp_list_tools_001" + } + RealtimeBetaServerEventMCPListToolsFailed: + type: object + description: Returned when listing MCP tools has failed for an item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - mcp_list_tools.failed + description: The event type, must be `mcp_list_tools.failed`. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP list tools item. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: mcp_list_tools.failed + group: realtime + example: | + { + "event_id": "event_6103", + "type": "mcp_list_tools.failed", + "item_id": "mcp_list_tools_001" + } + RealtimeBetaServerEventMCPListToolsInProgress: + type: object + description: Returned when listing MCP tools is in progress for an item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - mcp_list_tools.in_progress + description: The event type, must be `mcp_list_tools.in_progress`. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP list tools item. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: mcp_list_tools.in_progress + group: realtime + example: | + { + "event_id": "event_6101", + "type": "mcp_list_tools.in_progress", + "item_id": "mcp_list_tools_001" + } + RealtimeBetaServerEventRateLimitsUpdated: + type: object + description: > + Emitted at the beginning of a Response to indicate the updated rate + limits. + + When a Response is created some tokens will be "reserved" for the + output + + tokens, the rate limits shown here reflect that reservation, which is + then + + adjusted accordingly once the Response is completed. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - rate_limits.updated + description: The event type, must be `rate_limits.updated`. + x-stainless-const: true + rate_limits: + type: array + description: List of rate limit information. + items: + type: object + properties: + name: + type: string + enum: + - requests + - tokens + description: | + The name of the rate limit (`requests`, `tokens`). + limit: + type: integer + description: The maximum allowed value for the rate limit. + remaining: + type: integer + description: The remaining value before the limit is reached. + reset_seconds: + type: number + description: Seconds until the rate limit resets. + required: + - event_id + - type + - rate_limits + x-oaiMeta: + name: rate_limits.updated + group: realtime + example: | + { + "event_id": "event_5758", + "type": "rate_limits.updated", + "rate_limits": [ + { + "name": "requests", + "limit": 1000, + "remaining": 999, + "reset_seconds": 60 + }, + { + "name": "tokens", + "limit": 50000, + "remaining": 49950, + "reset_seconds": 60 + } + ] + } + RealtimeBetaServerEventResponseAudioDelta: + type: object + description: Returned when the model-generated audio is updated. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_audio.delta + description: The event type, must be `response.output_audio.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + delta: + type: string + description: Base64-encoded audio data delta. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - delta + x-oaiMeta: + name: response.output_audio.delta + group: realtime + example: | + { + "event_id": "event_4950", + "type": "response.output_audio.delta", + "response_id": "resp_001", + "item_id": "msg_008", + "output_index": 0, + "content_index": 0, + "delta": "Base64EncodedAudioDelta" + } + RealtimeBetaServerEventResponseAudioDone: + type: object + description: > + Returned when the model-generated audio is done. Also emitted when a + Response + + is interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_audio.done + description: The event type, must be `response.output_audio.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + x-oaiMeta: + name: response.output_audio.done + group: realtime + example: | + { + "event_id": "event_5152", + "type": "response.output_audio.done", + "response_id": "resp_001", + "item_id": "msg_008", + "output_index": 0, + "content_index": 0 + } + RealtimeBetaServerEventResponseAudioTranscriptDelta: + type: object + description: > + Returned when the model-generated transcription of audio output is + updated. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_audio_transcript.delta + description: The event type, must be `response.output_audio_transcript.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + delta: + type: string + description: The transcript delta. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - delta + x-oaiMeta: + name: response.output_audio_transcript.delta + group: realtime + example: | + { + "event_id": "event_4546", + "type": "response.output_audio_transcript.delta", + "response_id": "resp_001", + "item_id": "msg_008", + "output_index": 0, + "content_index": 0, + "delta": "Hello, how can I a" + } + RealtimeBetaServerEventResponseAudioTranscriptDone: + type: object + description: | + Returned when the model-generated transcription of audio output is done + streaming. Also emitted when a Response is interrupted, incomplete, or + cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_audio_transcript.done + description: The event type, must be `response.output_audio_transcript.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + transcript: + type: string + description: The final transcript of the audio. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - transcript + x-oaiMeta: + name: response.output_audio_transcript.done + group: realtime + example: | + { + "event_id": "event_4748", + "type": "response.output_audio_transcript.done", + "response_id": "resp_001", + "item_id": "msg_008", + "output_index": 0, + "content_index": 0, + "transcript": "Hello, how can I assist you today?" + } + RealtimeBetaServerEventResponseContentPartAdded: + type: object + description: > + Returned when a new content part is added to an assistant message item + during + + response generation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.content_part.added + description: The event type, must be `response.content_part.added`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item to which the content part was added. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + part: + type: object + description: The content part that was added. + properties: + type: + type: string + enum: + - audio + - text + description: The content type ("text", "audio"). + text: + type: string + description: The text content (if type is "text"). + audio: + type: string + description: Base64-encoded audio data (if type is "audio"). + transcript: + type: string + description: The transcript of the audio (if type is "audio"). + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - part + x-oaiMeta: + name: response.content_part.added + group: realtime + example: | + { + "event_id": "event_3738", + "type": "response.content_part.added", + "response_id": "resp_001", + "item_id": "msg_007", + "output_index": 0, + "content_index": 0, + "part": { + "type": "text", + "text": "" + } + } + RealtimeBetaServerEventResponseContentPartDone: + type: object + description: > + Returned when a content part is done streaming in an assistant message + item. + + Also emitted when a Response is interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.content_part.done + description: The event type, must be `response.content_part.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + part: + type: object + description: The content part that is done. + properties: + type: + type: string + enum: + - audio + - text + description: The content type ("text", "audio"). + text: + type: string + description: The text content (if type is "text"). + audio: + type: string + description: Base64-encoded audio data (if type is "audio"). + transcript: + type: string + description: The transcript of the audio (if type is "audio"). + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - part + x-oaiMeta: + name: response.content_part.done + group: realtime + example: | + { + "event_id": "event_3940", + "type": "response.content_part.done", + "response_id": "resp_001", + "item_id": "msg_007", + "output_index": 0, + "content_index": 0, + "part": { + "type": "text", + "text": "Sure, I can help with that." + } + } + RealtimeBetaServerEventResponseCreated: + type: object + description: > + Returned when a new Response is created. The first event of response + creation, + + where the response is in an initial state of `in_progress`. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.created + description: The event type, must be `response.created`. + x-stainless-const: true + response: + $ref: '#/components/schemas/RealtimeBetaResponse' + required: + - event_id + - type + - response + x-oaiMeta: + name: response.created + group: realtime + example: | + { + "type": "response.created", + "event_id": "event_C9G8pqbTEddBSIxbBN6Os", + "response": { + "object": "realtime.response", + "id": "resp_C9G8p7IH2WxLbkgPNouYL", + "status": "in_progress", + "status_details": null, + "output": [], + "conversation_id": "conv_C9G8mmBkLhQJwCon3hoJN", + "output_modalities": [ + "audio" + ], + "max_output_tokens": "inf", + "audio": { + "output": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "voice": "marin" + } + }, + "usage": null, + "metadata": null + }, + "timestamp": "2:30:35 PM" + } + RealtimeBetaServerEventResponseDone: + type: object + description: > + Returned when a Response is done streaming. Always emitted, no matter + the + + final state. The Response object included in the `response.done` event + will + + include all output Items in the Response but will omit the raw audio + data. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.done + description: The event type, must be `response.done`. + x-stainless-const: true + response: + $ref: '#/components/schemas/RealtimeBetaResponse' + required: + - event_id + - type + - response + x-oaiMeta: + name: response.done + group: realtime + example: | + { + "event_id": "event_3132", + "type": "response.done", + "response": { + "id": "resp_001", + "object": "realtime.response", + "status": "completed", + "status_details": null, + "output": [ + { + "id": "msg_006", + "object": "realtime.item", + "type": "message", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "text", + "text": "Sure, how can I assist you today?" + } + ] + } + ], + "usage": { + "total_tokens":275, + "input_tokens":127, + "output_tokens":148, + "input_token_details": { + "cached_tokens":384, + "text_tokens":119, + "audio_tokens":8, + "cached_tokens_details": { + "text_tokens": 128, + "audio_tokens": 256 + } + }, + "output_token_details": { + "text_tokens":36, + "audio_tokens":112 + } + } + } + } + RealtimeBetaServerEventResponseFunctionCallArgumentsDelta: + type: object + description: | + Returned when the model-generated function call arguments are updated. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.function_call_arguments.delta + description: | + The event type, must be `response.function_call_arguments.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the function call item. + output_index: + type: integer + description: The index of the output item in the response. + call_id: + type: string + description: The ID of the function call. + delta: + type: string + description: The arguments delta as a JSON string. + required: + - event_id + - type + - response_id + - item_id + - output_index + - call_id + - delta + x-oaiMeta: + name: response.function_call_arguments.delta + group: realtime + example: | + { + "event_id": "event_5354", + "type": "response.function_call_arguments.delta", + "response_id": "resp_002", + "item_id": "fc_001", + "output_index": 0, + "call_id": "call_001", + "delta": "{\"location\": \"San\"" + } + RealtimeBetaServerEventResponseFunctionCallArgumentsDone: + type: object + description: > + Returned when the model-generated function call arguments are done + streaming. + + Also emitted when a Response is interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.function_call_arguments.done + description: | + The event type, must be `response.function_call_arguments.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the function call item. + output_index: + type: integer + description: The index of the output item in the response. + call_id: + type: string + description: The ID of the function call. + name: + type: string + description: The name of the function that was called. + arguments: + type: string + description: The final arguments as a JSON string. + required: + - event_id + - type + - response_id + - item_id + - output_index + - call_id + - name + - arguments + x-oaiMeta: + name: response.function_call_arguments.done + group: realtime + example: | + { + "event_id": "event_5556", + "type": "response.function_call_arguments.done", + "response_id": "resp_002", + "item_id": "fc_001", + "output_index": 0, + "call_id": "call_001", + "name": "get_weather", + "arguments": "{\"location\": \"San Francisco\"}" + } + RealtimeBetaServerEventResponseMCPCallArgumentsDelta: + type: object + description: >- + Returned when MCP tool call arguments are updated during response + generation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call_arguments.delta + description: The event type, must be `response.mcp_call_arguments.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the MCP tool call item. + output_index: + type: integer + description: The index of the output item in the response. + delta: + type: string + description: The JSON-encoded arguments delta. + obfuscation: + anyOf: + - type: string + description: If present, indicates the delta text was obfuscated. + - type: 'null' + required: + - event_id + - type + - response_id + - item_id + - output_index + - delta + x-oaiMeta: + name: response.mcp_call_arguments.delta + group: realtime + example: | + { + "event_id": "event_6201", + "type": "response.mcp_call_arguments.delta", + "response_id": "resp_001", + "item_id": "mcp_call_001", + "output_index": 0, + "delta": "{\"partial\":true}" + } + RealtimeBetaServerEventResponseMCPCallArgumentsDone: + type: object + description: >- + Returned when MCP tool call arguments are finalized during response + generation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call_arguments.done + description: The event type, must be `response.mcp_call_arguments.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the MCP tool call item. + output_index: + type: integer + description: The index of the output item in the response. + arguments: + type: string + description: The final JSON-encoded arguments string. + required: + - event_id + - type + - response_id + - item_id + - output_index + - arguments + x-oaiMeta: + name: response.mcp_call_arguments.done + group: realtime + example: | + { + "event_id": "event_6202", + "type": "response.mcp_call_arguments.done", + "response_id": "resp_001", + "item_id": "mcp_call_001", + "output_index": 0, + "arguments": "{\"q\":\"docs\"}" + } + RealtimeBetaServerEventResponseMCPCallCompleted: + type: object + description: Returned when an MCP tool call has completed successfully. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call.completed + description: The event type, must be `response.mcp_call.completed`. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response. + item_id: + type: string + description: The ID of the MCP tool call item. + required: + - event_id + - type + - output_index + - item_id + x-oaiMeta: + name: response.mcp_call.completed + group: realtime + example: | + { + "event_id": "event_6302", + "type": "response.mcp_call.completed", + "output_index": 0, + "item_id": "mcp_call_001" + } + RealtimeBetaServerEventResponseMCPCallFailed: + type: object + description: Returned when an MCP tool call has failed. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call.failed + description: The event type, must be `response.mcp_call.failed`. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response. + item_id: + type: string + description: The ID of the MCP tool call item. + required: + - event_id + - type + - output_index + - item_id + x-oaiMeta: + name: response.mcp_call.failed + group: realtime + example: | + { + "event_id": "event_6303", + "type": "response.mcp_call.failed", + "output_index": 0, + "item_id": "mcp_call_001" + } + RealtimeBetaServerEventResponseMCPCallInProgress: + type: object + description: Returned when an MCP tool call has started and is in progress. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call.in_progress + description: The event type, must be `response.mcp_call.in_progress`. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response. + item_id: + type: string + description: The ID of the MCP tool call item. + required: + - event_id + - type + - output_index + - item_id + x-oaiMeta: + name: response.mcp_call.in_progress + group: realtime + example: | + { + "event_id": "event_6301", + "type": "response.mcp_call.in_progress", + "output_index": 0, + "item_id": "mcp_call_001" + } + RealtimeBetaServerEventResponseOutputItemAdded: + type: object + description: Returned when a new Item is created during Response generation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_item.added + description: The event type, must be `response.output_item.added`. + x-stainless-const: true + response_id: + type: string + description: The ID of the Response to which the item belongs. + output_index: + type: integer + description: The index of the output item in the Response. + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - response_id + - output_index + - item + x-oaiMeta: + name: response.output_item.added + group: realtime + example: | + { + "event_id": "event_3334", + "type": "response.output_item.added", + "response_id": "resp_001", + "output_index": 0, + "item": { + "id": "msg_007", + "object": "realtime.item", + "type": "message", + "status": "in_progress", + "role": "assistant", + "content": [] + } + } + RealtimeBetaServerEventResponseOutputItemDone: + type: object + description: > + Returned when an Item is done streaming. Also emitted when a Response + is + + interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_item.done + description: The event type, must be `response.output_item.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the Response to which the item belongs. + output_index: + type: integer + description: The index of the output item in the Response. + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - response_id + - output_index + - item + x-oaiMeta: + name: response.output_item.done + group: realtime + example: | + { + "event_id": "event_3536", + "type": "response.output_item.done", + "response_id": "resp_001", + "output_index": 0, + "item": { + "id": "msg_007", + "object": "realtime.item", + "type": "message", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "text", + "text": "Sure, I can help with that." + } + ] + } + } + RealtimeBetaServerEventResponseTextDelta: + type: object + description: >- + Returned when the text value of an "output_text" content part is + updated. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_text.delta + description: The event type, must be `response.output_text.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + delta: + type: string + description: The text delta. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - delta + x-oaiMeta: + name: response.output_text.delta + group: realtime + example: | + { + "event_id": "event_4142", + "type": "response.output_text.delta", + "response_id": "resp_001", + "item_id": "msg_007", + "output_index": 0, + "content_index": 0, + "delta": "Sure, I can h" + } + RealtimeBetaServerEventResponseTextDone: + type: object + description: > + Returned when the text value of an "output_text" content part is done + streaming. Also + + emitted when a Response is interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_text.done + description: The event type, must be `response.output_text.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + text: + type: string + description: The final text content. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - text + x-oaiMeta: + name: response.output_text.done + group: realtime + example: | + { + "event_id": "event_4344", + "type": "response.output_text.done", + "response_id": "resp_001", + "item_id": "msg_007", + "output_index": 0, + "content_index": 0, + "text": "Sure, I can help with that." + } + RealtimeBetaServerEventSessionCreated: + type: object + description: > + Returned when a Session is created. Emitted automatically when a new + + connection is established as the first server event. This event will + contain + + the default Session configuration. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - session.created + description: The event type, must be `session.created`. + x-stainless-const: true + session: + $ref: '#/components/schemas/RealtimeSession' + required: + - event_id + - type + - session + x-oaiMeta: + name: session.created + group: realtime + example: | + { + "type": "session.created", + "event_id": "event_C9G5RJeJ2gF77mV7f2B1j", + "session": { + "object": "realtime.session", + "id": "sess_C9G5QPteg4UIbotdKLoYQ", + "model": "gpt-realtime-2025-08-28", + "modalities": [ + "audio" + ], + "instructions": "Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you’re asked about them.", + "tools": [], + "tool_choice": "auto", + "max_response_output_tokens": "inf", + "tracing": null, + "prompt": null, + "expires_at": 1756324625, + "input_audio_format": "pcm16", + "input_audio_transcription": null, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 200, + "idle_timeout_ms": null, + "create_response": true, + "interrupt_response": true + }, + "output_audio_format": "pcm16", + "voice": "marin", + "include": null + } + } + RealtimeBetaServerEventSessionUpdated: + type: object + description: | + Returned when a session is updated with a `session.update` event, unless + there is an error. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - session.updated + description: The event type, must be `session.updated`. + x-stainless-const: true + session: + $ref: '#/components/schemas/RealtimeSession' + required: + - event_id + - type + - session + x-oaiMeta: + name: session.updated + group: realtime + example: | + { + "event_id": "event_5678", + "type": "session.updated", + "session": { + "id": "sess_001", + "object": "realtime.session", + "model": "gpt-realtime", + "modalities": ["text"], + "instructions": "New instructions", + "voice": "sage", + "input_audio_format": "pcm16", + "output_audio_format": "pcm16", + "input_audio_transcription": { + "model": "whisper-1" + }, + "turn_detection": null, + "tools": [], + "tool_choice": "none", + "temperature": 0.7, + "max_response_output_tokens": 200, + "speed": 1.1, + "tracing": "auto" + } + } + RealtimeBetaServerEventTranscriptionSessionCreated: + type: object + description: | + Returned when a transcription session is created. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - transcription_session.created + description: The event type, must be `transcription_session.created`. + x-stainless-const: true + session: + $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponse' + required: + - event_id + - type + - session + x-oaiMeta: + name: transcription_session.created + group: realtime + example: | + { + "event_id": "event_5566", + "type": "transcription_session.created", + "session": { + "id": "sess_001", + "object": "realtime.transcription_session", + "input_audio_format": "pcm16", + "input_audio_transcription": { + "model": "gpt-4o-transcribe", + "prompt": "", + "language": "" + }, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 500 + }, + "input_audio_noise_reduction": { + "type": "near_field" + }, + "include": [] + } + } + RealtimeBetaServerEventTranscriptionSessionUpdated: + type: object + description: > + Returned when a transcription session is updated with a + `transcription_session.update` event, unless + + there is an error. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - transcription_session.updated + description: The event type, must be `transcription_session.updated`. + x-stainless-const: true + session: + $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponse' + required: + - event_id + - type + - session + x-oaiMeta: + name: transcription_session.updated + group: realtime + example: | + { + "event_id": "event_5678", + "type": "transcription_session.updated", + "session": { + "id": "sess_001", + "object": "realtime.transcription_session", + "input_audio_format": "pcm16", + "input_audio_transcription": { + "model": "gpt-4o-transcribe", + "prompt": "", + "language": "" + }, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 500, + "create_response": true, + // "interrupt_response": false -- this will NOT be returned + }, + "input_audio_noise_reduction": { + "type": "near_field" + }, + "include": [ + "item.input_audio_transcription.avg_logprob", + ], + } + } + RealtimeCallCreateRequest: + title: Realtime call creation request + type: object + description: >- + Parameters required to initiate a realtime call and receive the SDP + answer + + needed to complete a WebRTC peer connection. Provide an SDP offer + generated + + by your client and optionally configure the session that will answer the + call. + required: + - sdp + properties: + sdp: + type: string + description: >- + WebRTC Session Description Protocol (SDP) offer generated by the + caller. + session: + title: Session configuration + allOf: + - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' + description: >- + Optional session configuration to apply before the realtime session + is + + created. Use the same parameters you would send in a [`create client + secret`](/docs/api-reference/realtime-sessions/create-realtime-client-secret) + + request. + additionalProperties: false + RealtimeCallReferRequest: + title: Realtime call refer request + type: object + description: >- + Parameters required to transfer a SIP call to a new destination using + the + + Realtime API. + required: + - target_uri + properties: + target_uri: + type: string + description: >- + URI that should appear in the SIP Refer-To header. Supports values + like + + `tel:+14155550123` or `sip:agent@example.com`. + example: tel:+14155550123 + additionalProperties: false + RealtimeCallRejectRequest: + title: Realtime call reject request + type: object + description: >- + Parameters used to decline an incoming SIP call handled by the Realtime + API. + properties: + status_code: + type: integer + description: >- + SIP response code to send back to the caller. Defaults to `603` + (Decline) + + when omitted. + example: 486 + additionalProperties: false + RealtimeClientEvent: + discriminator: + propertyName: type + description: | + A realtime client event. + anyOf: + - $ref: '#/components/schemas/RealtimeClientEventConversationItemCreate' + - $ref: '#/components/schemas/RealtimeClientEventConversationItemDelete' + - $ref: '#/components/schemas/RealtimeClientEventConversationItemRetrieve' + - $ref: '#/components/schemas/RealtimeClientEventConversationItemTruncate' + - $ref: '#/components/schemas/RealtimeClientEventInputAudioBufferAppend' + - $ref: '#/components/schemas/RealtimeClientEventInputAudioBufferClear' + - $ref: '#/components/schemas/RealtimeClientEventOutputAudioBufferClear' + - $ref: '#/components/schemas/RealtimeClientEventInputAudioBufferCommit' + - $ref: '#/components/schemas/RealtimeClientEventResponseCancel' + - $ref: '#/components/schemas/RealtimeClientEventResponseCreate' + - $ref: '#/components/schemas/RealtimeClientEventSessionUpdate' + RealtimeClientEventConversationItemCreate: + type: object + description: > + Add a new Item to the Conversation's context, including messages, + function + + calls, and function call responses. This event can be used both to + populate a + + "history" of the conversation and to add new items mid-stream, but has + the + + current limitation that it cannot populate assistant audio messages. + + + If successful, the server will respond with a + `conversation.item.created` + + event, otherwise an `error` event will be sent. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - conversation.item.create + description: The event type, must be `conversation.item.create`. + x-stainless-const: true + previous_item_id: + type: string + description: > + The ID of the preceding item after which the new item will be + inserted. If not set, the new item will be appended to the end of + the conversation. + + + If set to `root`, the new item will be added to the beginning of the + conversation. + + + If set to an existing ID, it allows an item to be inserted + mid-conversation. If the ID cannot be found, an error will be + returned and the item will not be added. + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - type + - item + x-oaiMeta: + name: conversation.item.create + group: realtime + example: | + { + "type": "conversation.item.create", + "item": { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "hi" + } + ] + } + } + RealtimeClientEventConversationItemDelete: + type: object + description: > + Send this event when you want to remove any item from the conversation + + history. The server will respond with a `conversation.item.deleted` + event, + + unless the item does not exist in the conversation history, in which + case the + + server will respond with an error. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - conversation.item.delete + description: The event type, must be `conversation.item.delete`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item to delete. + required: + - type + - item_id + x-oaiMeta: + name: conversation.item.delete + group: realtime + example: | + { + "event_id": "event_901", + "type": "conversation.item.delete", + "item_id": "item_003" + } + RealtimeClientEventConversationItemRetrieve: + type: object + description: > + Send this event when you want to retrieve the server's representation of + a specific item in the conversation history. This is useful, for + example, to inspect user audio after noise cancellation and VAD. + + The server will respond with a `conversation.item.retrieved` event, + + unless the item does not exist in the conversation history, in which + case the + + server will respond with an error. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - conversation.item.retrieve + description: The event type, must be `conversation.item.retrieve`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item to retrieve. + required: + - type + - item_id + x-oaiMeta: + name: conversation.item.retrieve + group: realtime + example: | + { + "event_id": "event_901", + "type": "conversation.item.retrieve", + "item_id": "item_003" + } + RealtimeClientEventConversationItemTruncate: + type: object + description: > + Send this event to truncate a previous assistant message’s audio. The + server + + will produce audio faster than realtime, so this event is useful when + the user + + interrupts to truncate audio that has already been sent to the client + but not + + yet played. This will synchronize the server's understanding of the + audio with + + the client's playback. + + + Truncating audio will delete the server-side text transcript to ensure + there + + is not text in the context that hasn't been heard by the user. + + + If successful, the server will respond with a + `conversation.item.truncated` + + event. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - conversation.item.truncate + description: The event type, must be `conversation.item.truncate`. + x-stainless-const: true + item_id: + type: string + description: > + The ID of the assistant message item to truncate. Only assistant + message + + items can be truncated. + content_index: + type: integer + description: The index of the content part to truncate. Set this to `0`. + audio_end_ms: + type: integer + description: > + Inclusive duration up to which audio is truncated, in milliseconds. + If + + the audio_end_ms is greater than the actual audio duration, the + server + + will respond with an error. + required: + - type + - item_id + - content_index + - audio_end_ms + x-oaiMeta: + name: conversation.item.truncate + group: realtime + example: | + { + "event_id": "event_678", + "type": "conversation.item.truncate", + "item_id": "item_002", + "content_index": 0, + "audio_end_ms": 1500 + } + RealtimeClientEventInputAudioBufferAppend: + type: object + description: > + Send this event to append audio bytes to the input audio buffer. The + audio + + buffer is temporary storage you can write to and later commit. A + "commit" will create a new + + user message item in the conversation history from the buffer content + and clear the buffer. + + Input audio transcription (if enabled) will be generated when the buffer + is committed. + + + If VAD is enabled the audio buffer is used to detect speech and the + server will decide + + when to commit. When Server VAD is disabled, you must commit the audio + buffer + + manually. Input audio noise reduction operates on writes to the audio + buffer. + + + The client may choose how much audio to place in each event up to a + maximum + + of 15 MiB, for example streaming smaller chunks from the client may + allow the + + VAD to be more responsive. Unlike most other client events, the server + will + + not send a confirmation response to this event. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - input_audio_buffer.append + description: The event type, must be `input_audio_buffer.append`. + x-stainless-const: true + audio: + type: string + description: > + Base64-encoded audio bytes. This must be in the format specified by + the + + `input_audio_format` field in the session configuration. + required: + - type + - audio + x-oaiMeta: + name: input_audio_buffer.append + group: realtime + example: | + { + "event_id": "event_456", + "type": "input_audio_buffer.append", + "audio": "Base64EncodedAudioData" + } + RealtimeClientEventInputAudioBufferClear: + type: object + description: | + Send this event to clear the audio bytes in the buffer. The server will + respond with an `input_audio_buffer.cleared` event. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - input_audio_buffer.clear + description: The event type, must be `input_audio_buffer.clear`. + x-stainless-const: true + required: + - type + x-oaiMeta: + name: input_audio_buffer.clear + group: realtime + example: | + { + "event_id": "event_012", + "type": "input_audio_buffer.clear" + } + RealtimeClientEventInputAudioBufferCommit: + type: object + description: > + Send this event to commit the user input audio buffer, which will create + a new user message item in the conversation. This event will produce an + error if the input audio buffer is empty. When in Server VAD mode, the + client does not need to send this event, the server will commit the + audio buffer automatically. + + + Committing the input audio buffer will trigger input audio + transcription (if enabled in session configuration), but it will not + create a response from the model. The server will respond with an + `input_audio_buffer.committed` event. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - input_audio_buffer.commit + description: The event type, must be `input_audio_buffer.commit`. + x-stainless-const: true + required: + - type + x-oaiMeta: + name: input_audio_buffer.commit + group: realtime + example: | + { + "event_id": "event_789", + "type": "input_audio_buffer.commit" + } + RealtimeClientEventOutputAudioBufferClear: + type: object + description: > + **WebRTC/SIP Only:** Emit to cut off the current audio response. This + will trigger the server to + + stop generating audio and emit a `output_audio_buffer.cleared` event. + This + + event should be preceded by a `response.cancel` client event to stop the + + generation of the current response. + + [Learn + more](/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). + properties: + event_id: + type: string + description: The unique ID of the client event used for error handling. + type: + type: string + enum: + - output_audio_buffer.clear + description: The event type, must be `output_audio_buffer.clear`. + x-stainless-const: true + required: + - type + x-oaiMeta: + name: output_audio_buffer.clear + group: realtime + example: | + { + "event_id": "optional_client_event_id", + "type": "output_audio_buffer.clear" + } + RealtimeClientEventResponseCancel: + type: object + description: > + Send this event to cancel an in-progress response. The server will + respond + + with a `response.done` event with a status of + `response.status=cancelled`. If + + there is no response to cancel, the server will respond with an error. + It's safe + + to call `response.cancel` even if no response is in progress, an error + will be + + returned the session will remain unaffected. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - response.cancel + description: The event type, must be `response.cancel`. + x-stainless-const: true + response_id: + type: string + description: | + A specific response ID to cancel - if not provided, will cancel an + in-progress response in the default conversation. + required: + - type + x-oaiMeta: + name: response.cancel + group: realtime + example: | + { + "type": "response.cancel", + "response_id": "resp_12345" + } + RealtimeClientEventResponseCreate: + type: object + description: > + This event instructs the server to create a Response, which means + triggering + + model inference. When in Server VAD mode, the server will create + Responses + + automatically. + + + A Response will include at least one Item, and may have two, in which + case + + the second will be a function call. These Items will be appended to the + + conversation history by default. + + + The server will respond with a `response.created` event, events for + Items + + and content created, and finally a `response.done` event to indicate + the + + Response is complete. + + + The `response.create` event includes inference configuration like + + `instructions` and `tools`. If these are set, they will override the + Session's + + configuration for this Response only. + + + Responses can be created out-of-band of the default Conversation, + meaning that they can + + have arbitrary input, and it's possible to disable writing the output to + the Conversation. + + Only one Response can write to the default Conversation at a time, but + otherwise multiple + + Responses can be created in parallel. The `metadata` field is a good way + to disambiguate + + multiple simultaneous Responses. + + + Clients can set `conversation` to `none` to create a Response that does + not write to the default + + Conversation. Arbitrary input can be provided with the `input` field, + which is an array accepting + + raw Items and references to existing Items. + properties: + event_id: + type: string + maxLength: 512 + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - response.create + description: The event type, must be `response.create`. + x-stainless-const: true + response: + $ref: '#/components/schemas/RealtimeResponseCreateParams' + required: + - type + x-oaiMeta: + name: response.create + group: realtime + example: > + // Trigger a response with the default Conversation and no special + parameters + + { + "type": "response.create", + } + + + // Trigger an out-of-band response that does not write to the default + Conversation + + { + "type": "response.create", + "response": { + "instructions": "Provide a concise answer.", + "tools": [], // clear any session tools + "conversation": "none", + "output_modalities": ["text"], + "metadata": { + "response_purpose": "summarization" + }, + "input": [ + { + "type": "item_reference", + "id": "item_12345" + }, + { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "Summarize the above message in one sentence." + } + ] + } + ] + } + } + RealtimeClientEventSessionUpdate: + type: object + description: > + Send this event to update the session’s configuration. + + The client may send this event at any time to update any field + + except for `voice` and `model`. `voice` can be updated only if there + have been no other audio outputs yet. + + + When the server receives a `session.update`, it will respond + + with a `session.updated` event showing the full, effective + configuration. + + Only the fields that are present in the `session.update` are updated. To + clear a field like + + `instructions`, pass an empty string. To clear a field like `tools`, + pass an empty array. + + To clear a field like `turn_detection`, pass `null`. + properties: + event_id: + type: string + maxLength: 512 + description: >- + Optional client-generated ID used to identify this event. This is an + arbitrary string that a client may assign. It will be passed back if + there is an error with the event, but the corresponding + `session.updated` event will not include it. + type: + type: string + enum: + - session.update + description: The event type, must be `session.update`. + x-stainless-const: true + session: + type: object + description: | + Update the Realtime session. Choose either a realtime + session or a transcription session. + oneOf: + - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' + - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequestGA' + required: + - type + - session + x-oaiMeta: + name: session.update + group: realtime + example: | + { + "type": "session.update", + "session": { + "type": "realtime", + "instructions": "You are a creative assistant that helps with design tasks.", + "tools": [ + { + "type": "function", + "name": "display_color_palette", + "description": "Call this function when a user asks for a color palette.", + "parameters": { + "type": "object", + "properties": { + "theme": { + "type": "string", + "description": "Description of the theme for the color scheme." + }, + "colors": { + "type": "array", + "description": "Array of five hex color codes based on the theme.", + "items": { + "type": "string", + "description": "Hex color code" + } + } + }, + "required": [ + "theme", + "colors" + ] + } + } + ], + "tool_choice": "auto" + } + } + RealtimeClientEventTranscriptionSessionUpdate: + type: object + description: | + Send this event to update a transcription session. + properties: + event_id: + type: string + description: Optional client-generated ID used to identify this event. + type: + type: string + enum: + - transcription_session.update + description: The event type, must be `transcription_session.update`. + x-stainless-const: true + session: + $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequest' + required: + - type + - session + x-oaiMeta: + name: transcription_session.update + group: realtime + example: | + { + "type": "transcription_session.update", + "session": { + "input_audio_format": "pcm16", + "input_audio_transcription": { + "model": "gpt-4o-transcribe", + "prompt": "", + "language": "" + }, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 500, + "create_response": true, + }, + "input_audio_noise_reduction": { + "type": "near_field" + }, + "include": [ + "item.input_audio_transcription.logprobs", + ] + } + } + RealtimeConversationItem: + description: A single item within a Realtime conversation. + anyOf: + - $ref: '#/components/schemas/RealtimeConversationItemMessageSystem' + - $ref: '#/components/schemas/RealtimeConversationItemMessageUser' + - $ref: '#/components/schemas/RealtimeConversationItemMessageAssistant' + - $ref: '#/components/schemas/RealtimeConversationItemFunctionCall' + - $ref: '#/components/schemas/RealtimeConversationItemFunctionCallOutput' + - $ref: '#/components/schemas/RealtimeMCPApprovalResponse' + - $ref: '#/components/schemas/RealtimeMCPListTools' + - $ref: '#/components/schemas/RealtimeMCPToolCall' + - $ref: '#/components/schemas/RealtimeMCPApprovalRequest' + discriminator: + propertyName: type + RealtimeConversationItemFunctionCall: + type: object + title: Realtime function call item + description: A function call item in a Realtime conversation. + properties: + id: + type: string + description: >- + The unique ID of the item. This may be provided by the client or + generated by the server. + object: + type: string + enum: + - realtime.item + description: >- + Identifier for the API object being returned - always + `realtime.item`. Optional when creating a new item. + x-stainless-const: true + type: + type: string + enum: + - function_call + description: The type of the item. Always `function_call`. + x-stainless-const: true + status: + type: string + enum: + - completed + - incomplete + - in_progress + description: The status of the item. Has no effect on the conversation. + call_id: + type: string + description: The ID of the function call. + name: + type: string + description: The name of the function being called. + arguments: + type: string + description: >- + The arguments of the function call. This is a JSON-encoded string + representing the arguments passed to the function, for example + `{"arg1": "value1", "arg2": 42}`. + required: + - type + - name + - arguments + RealtimeConversationItemFunctionCallOutput: + type: object + title: Realtime function call output item + description: A function call output item in a Realtime conversation. + properties: + id: + type: string + description: >- + The unique ID of the item. This may be provided by the client or + generated by the server. + object: + type: string + enum: + - realtime.item + description: >- + Identifier for the API object being returned - always + `realtime.item`. Optional when creating a new item. + x-stainless-const: true + type: + type: string + enum: + - function_call_output + description: The type of the item. Always `function_call_output`. + x-stainless-const: true + status: + type: string + enum: + - completed + - incomplete + - in_progress + description: The status of the item. Has no effect on the conversation. + call_id: + type: string + description: The ID of the function call this output is for. + output: + type: string + description: >- + The output of the function call, this is free text and can contain + any information or simply be empty. + required: + - type + - call_id + - output + RealtimeConversationItemMessageAssistant: + type: object + title: Realtime assistant message item + description: An assistant message item in a Realtime conversation. + properties: + id: + type: string + description: >- + The unique ID of the item. This may be provided by the client or + generated by the server. + object: + type: string + enum: + - realtime.item + description: >- + Identifier for the API object being returned - always + `realtime.item`. Optional when creating a new item. + x-stainless-const: true + type: + type: string + enum: + - message + description: The type of the item. Always `message`. + x-stainless-const: true + status: + type: string + enum: + - completed + - incomplete + - in_progress + description: The status of the item. Has no effect on the conversation. + role: + type: string + enum: + - assistant + description: The role of the message sender. Always `assistant`. + x-stainless-const: true + content: + type: array + description: The content of the message. + items: + type: object + properties: + type: + type: string + enum: + - output_text + - output_audio + description: >- + The content type, `output_text` or `output_audio` depending on + the session `output_modalities` configuration. + text: + type: string + description: The text content. + audio: + type: string + description: >- + Base64-encoded audio bytes, these will be parsed as the format + specified in the session output audio type configuration. This + defaults to PCM 16-bit 24kHz mono if not specified. + transcript: + type: string + description: >- + The transcript of the audio content, this will always be + present if the output type is `audio`. + required: + - type + - role + - content + RealtimeConversationItemMessageSystem: + type: object + title: Realtime system message item + description: >- + A system message in a Realtime conversation can be used to provide + additional context or instructions to the model. This is similar but + distinct from the instruction prompt provided at the start of a + conversation, as system messages can be added at any point in the + conversation. For major changes to the conversation's behavior, use + instructions, but for smaller updates (e.g. "the user is now asking + about a different topic"), use system messages. + properties: + id: + type: string + description: >- + The unique ID of the item. This may be provided by the client or + generated by the server. + object: + type: string + enum: + - realtime.item + description: >- + Identifier for the API object being returned - always + `realtime.item`. Optional when creating a new item. + x-stainless-const: true + type: + type: string + enum: + - message + description: The type of the item. Always `message`. + x-stainless-const: true + status: + type: string + enum: + - completed + - incomplete + - in_progress + description: The status of the item. Has no effect on the conversation. + role: + type: string + enum: + - system + description: The role of the message sender. Always `system`. + x-stainless-const: true + content: + type: array + description: The content of the message. + items: + type: object + properties: + type: + type: string + enum: + - input_text + description: The content type. Always `input_text` for system messages. + x-stainless-const: true + text: + type: string + description: The text content. + required: + - type + - role + - content + RealtimeConversationItemMessageUser: + type: object + title: Realtime user message item + description: A user message item in a Realtime conversation. + properties: + id: + type: string + description: >- + The unique ID of the item. This may be provided by the client or + generated by the server. + object: + type: string + enum: + - realtime.item + description: >- + Identifier for the API object being returned - always + `realtime.item`. Optional when creating a new item. + x-stainless-const: true + type: + type: string + enum: + - message + description: The type of the item. Always `message`. + x-stainless-const: true + status: + type: string + enum: + - completed + - incomplete + - in_progress + description: The status of the item. Has no effect on the conversation. + role: + type: string + enum: + - user + description: The role of the message sender. Always `user`. + x-stainless-const: true + content: + type: array + description: The content of the message. + items: + type: object + properties: + type: + type: string + enum: + - input_text + - input_audio + - input_image + description: >- + The content type (`input_text`, `input_audio`, or + `input_image`). + text: + type: string + description: The text content (for `input_text`). + audio: + type: string + description: >- + Base64-encoded audio bytes (for `input_audio`), these will be + parsed as the format specified in the session input audio type + configuration. This defaults to PCM 16-bit 24kHz mono if not + specified. + image_url: + type: string + description: >- + Base64-encoded image bytes (for `input_image`) as a data URI. + For example + `data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA...`. Supported + formats are PNG and JPEG. + detail: + type: string + description: >- + The detail level of the image (for `input_image`). `auto` will + default to `high`. + default: auto + enum: + - auto + - low + - high + transcript: + type: string + description: >- + Transcript of the audio (for `input_audio`). This is not sent + to the model, but will be attached to the message item for + reference. + required: + - type + - role + - content + RealtimeConversationItemWithReference: + type: object + description: The item to add to the conversation. + properties: + id: + type: string + description: > + For an item of type (`message` | `function_call` | + `function_call_output`) + + this field allows the client to assign the unique ID of the item. It + is + + not required because the server will generate one if not provided. + + + For an item of type `item_reference`, this field is required and is + a + + reference to any item that has previously existed in the + conversation. + type: + type: string + enum: + - message + - function_call + - function_call_output + description: > + The type of the item (`message`, `function_call`, + `function_call_output`, `item_reference`). + object: + type: string + enum: + - realtime.item + description: > + Identifier for the API object being returned - always + `realtime.item`. + x-stainless-const: true + status: + type: string + enum: + - completed + - incomplete + - in_progress + description: > + The status of the item (`completed`, `incomplete`, `in_progress`). + These have no effect + + on the conversation, but are accepted for consistency with the + + `conversation.item.created` event. + role: + type: string + enum: + - user + - assistant + - system + description: > + The role of the message sender (`user`, `assistant`, `system`), + only + + applicable for `message` items. + content: + type: array + description: > + The content of the message, applicable for `message` items. + + - Message items of role `system` support only `input_text` content + + - Message items of role `user` support `input_text` and + `input_audio` + content + - Message items of role `assistant` support `text` content. + items: + type: object + properties: + type: + type: string + enum: + - input_audio + - input_text + - item_reference + - text + description: > + The content type (`input_text`, `input_audio`, + `item_reference`, `text`). + text: + type: string + description: > + The text content, used for `input_text` and `text` content + types. + id: + type: string + description: > + ID of a previous conversation item to reference (for + `item_reference` + + content types in `response.create` events). These can + reference both + + client and server created items. + audio: + type: string + description: > + Base64-encoded audio bytes, used for `input_audio` content + type. + transcript: + type: string + description: > + The transcript of the audio, used for `input_audio` content + type. + call_id: + type: string + description: > + The ID of the function call (for `function_call` and + + `function_call_output` items). If passed on a + `function_call_output` + + item, the server will check that a `function_call` item with the + same + + ID exists in the conversation history. + name: + type: string + description: | + The name of the function being called (for `function_call` items). + arguments: + type: string + description: | + The arguments of the function call (for `function_call` items). + output: + type: string + description: | + The output of the function call (for `function_call_output` items). + RealtimeCreateClientSecretRequest: + type: object + title: Realtime client secret creation request + description: > + Create a session and client secret for the Realtime API. The request can + specify + + either a realtime or a transcription session configuration. + + [Learn more about the Realtime API](/docs/guides/realtime). + properties: + expires_after: + type: object + title: Client secret expiration + description: > + Configuration for the client secret expiration. Expiration refers to + the time after which + + a client secret will no longer be valid for creating sessions. The + session itself may + + continue after that time once started. A secret can be used to + create multiple sessions + + until it expires. + properties: + anchor: + type: string + enum: + - created_at + description: > + The anchor point for the client secret expiration, meaning that + `seconds` will be added to the `created_at` time of the client + secret to produce an expiration timestamp. Only `created_at` is + currently supported. + default: created_at + x-stainless-const: true + seconds: + type: integer + description: > + The number of seconds from the anchor point to the expiration. + Select a value between `10` and `7200` (2 hours). This default + to 600 seconds (10 minutes) if not specified. + minimum: 10 + maximum: 7200 + default: 600 + session: + title: Session configuration + description: > + Session configuration to use for the client secret. Choose either a + realtime + + session or a transcription session. + oneOf: + - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' + - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequestGA' + RealtimeCreateClientSecretResponse: + type: object + title: Realtime session and client secret + description: | + Response from creating a session and client secret for the Realtime API. + properties: + value: + type: string + description: The generated client secret value. + expires_at: + type: integer + description: Expiration timestamp for the client secret, in seconds since epoch. + session: + title: Session configuration + description: > + The session configuration for either a realtime or transcription + session. + oneOf: + - $ref: '#/components/schemas/RealtimeSessionCreateResponseGA' + - $ref: >- + #/components/schemas/RealtimeTranscriptionSessionCreateResponseGA + discriminator: + propertyName: type + required: + - value + - expires_at + - session + x-oaiMeta: + name: Session response object + group: realtime + example: | + { + "value": "ek_68af296e8e408191a1120ab6383263c2", + "expires_at": 1756310470, + "session": { + "type": "realtime", + "object": "realtime.session", + "id": "sess_C9CiUVUzUzYIssh3ELY1d", + "model": "gpt-realtime-2025-08-25", + "output_modalities": [ + "audio" + ], + "instructions": "You are a friendly assistant.", + "tools": [], + "tool_choice": "auto", + "max_output_tokens": "inf", + "tracing": null, + "truncation": "auto", + "prompt": null, + "expires_at": 0, + "audio": { + "input": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "transcription": null, + "noise_reduction": null, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 200, + "idle_timeout_ms": null, + "create_response": true, + "interrupt_response": true + } + }, + "output": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "voice": "alloy", + "speed": 1.0 + } + }, + "include": null + } + } + RealtimeFunctionTool: + type: object + title: Function tool + properties: + type: + type: string + enum: + - function + description: The type of the tool, i.e. `function`. + x-stainless-const: true + name: + type: string + description: The name of the function. + description: + type: string + description: | + The description of the function, including guidance on when and how + to call it, and guidance about what to tell the user when calling + (if anything). + parameters: + type: object + description: Parameters of the function in JSON Schema. + RealtimeMCPApprovalRequest: + type: object + title: Realtime MCP approval request + description: | + A Realtime item requesting human approval of a tool invocation. + properties: + type: + type: string + enum: + - mcp_approval_request + description: The type of the item. Always `mcp_approval_request`. + x-stainless-const: true + id: + type: string + description: The unique ID of the approval request. + server_label: + type: string + description: The label of the MCP server making the request. + name: + type: string + description: The name of the tool to run. + arguments: + type: string + description: A JSON string of arguments for the tool. + required: + - type + - id + - server_label + - name + - arguments + RealtimeMCPApprovalResponse: + type: object + title: Realtime MCP approval response + description: | + A Realtime item responding to an MCP approval request. + properties: + type: + type: string + enum: + - mcp_approval_response + description: The type of the item. Always `mcp_approval_response`. + x-stainless-const: true + id: + type: string + description: The unique ID of the approval response. + approval_request_id: + type: string + description: The ID of the approval request being answered. + approve: + type: boolean + description: Whether the request was approved. + reason: + anyOf: + - type: string + description: Optional reason for the decision. + - type: 'null' + required: + - type + - id + - approval_request_id + - approve + RealtimeMCPHTTPError: + type: object + title: Realtime MCP HTTP error + properties: + type: + type: string + enum: + - http_error + x-stainless-const: true + code: + type: integer + message: + type: string + required: + - type + - code + - message + RealtimeMCPListTools: + type: object + title: Realtime MCP list tools + description: | + A Realtime item listing tools available on an MCP server. + properties: + type: + type: string + enum: + - mcp_list_tools + description: The type of the item. Always `mcp_list_tools`. + x-stainless-const: true + id: + type: string + description: The unique ID of the list. + server_label: + type: string + description: The label of the MCP server. + tools: + type: array + items: + $ref: '#/components/schemas/MCPListToolsTool' + description: The tools available on the server. + required: + - type + - server_label + - tools + RealtimeMCPProtocolError: + type: object + title: Realtime MCP protocol error + properties: + type: + type: string + enum: + - protocol_error + x-stainless-const: true + code: + type: integer + message: + type: string + required: + - type + - code + - message + RealtimeMCPToolCall: + type: object + title: Realtime MCP tool call + description: | + A Realtime item representing an invocation of a tool on an MCP server. + properties: + type: + type: string + enum: + - mcp_call + description: The type of the item. Always `mcp_call`. + x-stainless-const: true + id: + type: string + description: The unique ID of the tool call. + server_label: + type: string + description: The label of the MCP server running the tool. + name: + type: string + description: The name of the tool that was run. + arguments: + type: string + description: A JSON string of the arguments passed to the tool. + approval_request_id: + anyOf: + - type: string + description: The ID of an associated approval request, if any. + - type: 'null' + output: + anyOf: + - type: string + description: The output from the tool call. + - type: 'null' + error: + anyOf: + - description: The error from the tool call, if any. + oneOf: + - $ref: '#/components/schemas/RealtimeMCPProtocolError' + - $ref: '#/components/schemas/RealtimeMCPToolExecutionError' + - $ref: '#/components/schemas/RealtimeMCPHTTPError' + - type: 'null' + required: + - type + - id + - server_label + - name + - arguments + RealtimeMCPToolExecutionError: + type: object + title: Realtime MCP tool execution error + properties: + type: + type: string + enum: + - tool_execution_error + x-stainless-const: true + message: + type: string + required: + - type + - message + RealtimeResponse: + type: object + description: The response resource. + properties: + id: + type: string + description: The unique ID of the response, will look like `resp_1234`. + object: + type: string + enum: + - realtime.response + description: The object type, must be `realtime.response`. + x-stainless-const: true + status: + type: string + enum: + - completed + - cancelled + - failed + - incomplete + - in_progress + description: > + The final status of the response (`completed`, `cancelled`, + `failed`, or + + `incomplete`, `in_progress`). + status_details: + type: object + description: Additional details about the status. + properties: + type: + type: string + enum: + - completed + - cancelled + - failed + - incomplete + description: > + The type of error that caused the response to fail, + corresponding + + with the `status` field (`completed`, `cancelled`, + `incomplete`, + + `failed`). + reason: + type: string + enum: + - turn_detected + - client_cancelled + - max_output_tokens + - content_filter + description: > + The reason the Response did not complete. For a `cancelled` + Response, one of `turn_detected` (the server VAD detected a new + start of speech) or `client_cancelled` (the client sent a + cancel event). For an `incomplete` Response, one of + `max_output_tokens` or `content_filter` (the server-side safety + filter activated and cut off the response). + error: + type: object + description: | + A description of the error that caused the response to fail, + populated when the `status` is `failed`. + properties: + type: + type: string + description: The type of error. + code: + type: string + description: Error code, if any. + output: + type: array + description: The list of output items generated by the response. + items: + $ref: '#/components/schemas/RealtimeConversationItem' + metadata: + $ref: '#/components/schemas/Metadata' + audio: + type: object + description: Configuration for audio output. + properties: + output: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + description: The format of the output audio. + voice: + $ref: '#/components/schemas/VoiceIdsShared' + default: alloy + description: > + The voice the model uses to respond. Voice cannot be changed + during the + + session once the model has responded with audio at least + once. Current + + voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, + `sage`, + + `shimmer`, `verse`, `marin`, and `cedar`. We recommend + `marin` and `cedar` for + + best quality. + usage: + type: object + description: > + Usage statistics for the Response, this will correspond to billing. + A + + Realtime API session will maintain a conversation context and append + new + + Items to the Conversation, thus output from previous turns (text + and + + audio tokens) will become the input for later turns. + properties: + total_tokens: + type: integer + description: > + The total number of tokens in the Response including input and + output + + text and audio tokens. + input_tokens: + type: integer + description: > + The number of input tokens used in the Response, including text + and + + audio tokens. + output_tokens: + type: integer + description: > + The number of output tokens sent in the Response, including text + and + + audio tokens. + input_token_details: + type: object + description: >- + Details about the input tokens used in the Response. Cached + tokens are tokens from previous turns in the conversation that + are included as context for the current response. Cached tokens + here are counted as a subset of input tokens, meaning input + tokens will include cached and uncached tokens. + properties: + cached_tokens: + type: integer + description: The number of cached tokens used as input for the Response. + text_tokens: + type: integer + description: The number of text tokens used as input for the Response. + image_tokens: + type: integer + description: The number of image tokens used as input for the Response. + audio_tokens: + type: integer + description: The number of audio tokens used as input for the Response. + cached_tokens_details: + type: object + description: >- + Details about the cached tokens used as input for the + Response. + properties: + text_tokens: + type: integer + description: >- + The number of cached text tokens used as input for the + Response. + image_tokens: + type: integer + description: >- + The number of cached image tokens used as input for the + Response. + audio_tokens: + type: integer + description: >- + The number of cached audio tokens used as input for the + Response. + output_token_details: + type: object + description: Details about the output tokens used in the Response. + properties: + text_tokens: + type: integer + description: The number of text tokens used in the Response. + audio_tokens: + type: integer + description: The number of audio tokens used in the Response. + conversation_id: + description: > + Which conversation the response is added to, determined by the + `conversation` + + field in the `response.create` event. If `auto`, the response will + be added to + + the default conversation and the value of `conversation_id` will be + an id like + + `conv_1234`. If `none`, the response will not be added to any + conversation and + + the value of `conversation_id` will be `null`. If responses are + being triggered + + automatically by VAD the response will be added to the default + conversation + type: string + output_modalities: + type: array + description: > + The set of modalities the model used to respond, currently the only + possible values are + + `[\"audio\"]`, `[\"text\"]`. Audio output always include a text + transcript. Setting the + + output to mode `text` will disable audio output from the model. + items: + type: string + enum: + - text + - audio + max_output_tokens: + oneOf: + - type: integer + - type: string + enum: + - inf + x-stainless-const: true + description: | + Maximum number of output tokens for a single assistant response, + inclusive of tool calls, that was used in this response. + RealtimeResponseCreateParams: + type: object + description: Create a new Realtime response with these parameters + properties: + output_modalities: + type: array + description: > + The set of modalities the model used to respond, currently the only + possible values are + + `[\"audio\"]`, `[\"text\"]`. Audio output always include a text + transcript. Setting the + + output to mode `text` will disable audio output from the model. + items: + type: string + enum: + - text + - audio + instructions: + type: string + description: > + The default system instructions (i.e. system message) prepended to + model calls. This field allows the client to guide the model on + desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are + examples of good responses") and on audio behavior (e.g. "talk + quickly", "inject emotion into your voice", "laugh frequently"). The + instructions are not guaranteed to be followed by the model, but + they provide guidance to the model on the desired behavior. + + Note that the server sets default instructions which will be used if + this field is not set and are visible in the `session.created` event + at the start of the session. + audio: + type: object + description: Configuration for audio input and output. + properties: + output: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + description: The format of the output audio. + voice: + $ref: '#/components/schemas/VoiceIdsOrCustomVoice' + default: alloy + description: > + The voice the model uses to respond. Supported built-in + voices are + + `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, + `shimmer`, `verse`, + + `marin`, and `cedar`. You may also provide a custom voice + object with + + an `id`, for example `{ "id": "voice_1234" }`. Voice cannot + be changed + + during the session once the model has responded with audio + at least once. + + We recommend `marin` and `cedar` for best quality. + tools: + type: array + description: Tools available to the model. + items: + oneOf: + - $ref: '#/components/schemas/RealtimeFunctionTool' + - $ref: '#/components/schemas/MCPTool' + tool_choice: + description: > + How the model chooses tools. Provide one of the string modes or + force a specific + + function/MCP tool. + oneOf: + - $ref: '#/components/schemas/ToolChoiceOptions' + - $ref: '#/components/schemas/ToolChoiceFunction' + - $ref: '#/components/schemas/ToolChoiceMCP' + default: auto + max_output_tokens: + oneOf: + - type: integer + - type: string + enum: + - inf + x-stainless-const: true + description: | + Maximum number of output tokens for a single assistant response, + inclusive of tool calls. Provide an integer between 1 and 4096 to + limit output tokens, or `inf` for the maximum available tokens for a + given model. Defaults to `inf`. + conversation: + description: > + Controls which conversation the response is added to. Currently + supports + + `auto` and `none`, with `auto` as the default value. The `auto` + value + + means that the contents of the response will be added to the default + + conversation. Set this to `none` to create an out-of-band response + which + + will not add items to default conversation. + oneOf: + - type: string + - type: string + default: auto + enum: + - auto + - none + metadata: + $ref: '#/components/schemas/Metadata' + prompt: + $ref: '#/components/schemas/Prompt' + input: + type: array + description: > + Input items to include in the prompt for the model. Using this field + + creates a new context for this Response instead of using the default + + conversation. An empty array `[]` will clear the context for this + Response. + + Note that this can include references to items that previously + appeared in the session + + using their id. + items: + $ref: '#/components/schemas/RealtimeConversationItem' + RealtimeServerEvent: + discriminator: + propertyName: type + description: | + A realtime server event. + anyOf: + - $ref: '#/components/schemas/RealtimeServerEventConversationCreated' + - $ref: '#/components/schemas/RealtimeServerEventConversationItemCreated' + - $ref: '#/components/schemas/RealtimeServerEventConversationItemDeleted' + - $ref: >- + #/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionCompleted + - $ref: >- + #/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionDelta + - $ref: >- + #/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionFailed + - $ref: '#/components/schemas/RealtimeServerEventConversationItemRetrieved' + - $ref: '#/components/schemas/RealtimeServerEventConversationItemTruncated' + - $ref: '#/components/schemas/RealtimeServerEventError' + - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferCleared' + - $ref: '#/components/schemas/RealtimeServerEventInputAudioBufferCommitted' + - $ref: >- + #/components/schemas/RealtimeServerEventInputAudioBufferDtmfEventReceived + - $ref: >- + #/components/schemas/RealtimeServerEventInputAudioBufferSpeechStarted + - $ref: >- + #/components/schemas/RealtimeServerEventInputAudioBufferSpeechStopped + - $ref: '#/components/schemas/RealtimeServerEventRateLimitsUpdated' + - $ref: '#/components/schemas/RealtimeServerEventResponseAudioDelta' + - $ref: '#/components/schemas/RealtimeServerEventResponseAudioDone' + - $ref: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDelta' + - $ref: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDone' + - $ref: '#/components/schemas/RealtimeServerEventResponseContentPartAdded' + - $ref: '#/components/schemas/RealtimeServerEventResponseContentPartDone' + - $ref: '#/components/schemas/RealtimeServerEventResponseCreated' + - $ref: '#/components/schemas/RealtimeServerEventResponseDone' + - $ref: >- + #/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDelta + - $ref: >- + #/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDone + - $ref: '#/components/schemas/RealtimeServerEventResponseOutputItemAdded' + - $ref: '#/components/schemas/RealtimeServerEventResponseOutputItemDone' + - $ref: '#/components/schemas/RealtimeServerEventResponseTextDelta' + - $ref: '#/components/schemas/RealtimeServerEventResponseTextDone' + - $ref: '#/components/schemas/RealtimeServerEventSessionCreated' + - $ref: '#/components/schemas/RealtimeServerEventSessionUpdated' + - $ref: '#/components/schemas/RealtimeServerEventOutputAudioBufferStarted' + - $ref: '#/components/schemas/RealtimeServerEventOutputAudioBufferStopped' + - $ref: '#/components/schemas/RealtimeServerEventOutputAudioBufferCleared' + - $ref: '#/components/schemas/RealtimeServerEventConversationItemAdded' + - $ref: '#/components/schemas/RealtimeServerEventConversationItemDone' + - $ref: >- + #/components/schemas/RealtimeServerEventInputAudioBufferTimeoutTriggered + - $ref: >- + #/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionSegment + - $ref: '#/components/schemas/RealtimeServerEventMCPListToolsInProgress' + - $ref: '#/components/schemas/RealtimeServerEventMCPListToolsCompleted' + - $ref: '#/components/schemas/RealtimeServerEventMCPListToolsFailed' + - $ref: >- + #/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDelta + - $ref: '#/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDone' + - $ref: '#/components/schemas/RealtimeServerEventResponseMCPCallInProgress' + - $ref: '#/components/schemas/RealtimeServerEventResponseMCPCallCompleted' + - $ref: '#/components/schemas/RealtimeServerEventResponseMCPCallFailed' + RealtimeServerEventConversationCreated: + type: object + description: > + Returned when a conversation is created. Emitted right after session + creation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.created + description: The event type, must be `conversation.created`. + x-stainless-const: true + conversation: + type: object + description: The conversation resource. + properties: + id: + type: string + description: The unique ID of the conversation. + object: + type: string + description: The object type, must be `realtime.conversation`. + required: + - event_id + - type + - conversation + x-oaiMeta: + name: conversation.created + group: realtime + example: | + { + "event_id": "event_9101", + "type": "conversation.created", + "conversation": { + "id": "conv_001", + "object": "realtime.conversation" + } + } + RealtimeServerEventConversationItemAdded: + type: object + description: > + Sent by the server when an Item is added to the default Conversation. + This can happen in several cases: + + - When the client sends a `conversation.item.create` event. + + - When the input audio buffer is committed. In this case the item will + be a user message containing the audio from the buffer. + + - When the model is generating a Response. In this case the + `conversation.item.added` event will be sent when the model starts + generating a specific Item, and thus it will not yet have any content + (and `status` will be `in_progress`). + + + The event will include the full content of the Item (except when model + is generating a Response) except for audio data, which can be retrieved + separately with a `conversation.item.retrieve` event if necessary. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.added + description: The event type, must be `conversation.item.added`. + x-stainless-const: true + previous_item_id: + anyOf: + - type: string + description: > + The ID of the item that precedes this one, if any. This is used + to + + maintain ordering when items are inserted. + - type: 'null' + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - item + x-oaiMeta: + name: conversation.item.added + group: realtime + example: | + { + "type": "conversation.item.added", + "event_id": "event_C9G8pjSJCfRNEhMEnYAVy", + "previous_item_id": null, + "item": { + "id": "item_C9G8pGVKYnaZu8PH5YQ9O", + "type": "message", + "status": "completed", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "hi" + } + ] + } + } + RealtimeServerEventConversationItemCreated: + type: object + description: > + Returned when a conversation item is created. There are several + scenarios that produce this event: + - The server is generating a Response, which if successful will produce + either one or two Items, which will be of type `message` + (role `assistant`) or type `function_call`. + - The input audio buffer has been committed, either by the client or the + server (in `server_vad` mode). The server will take the content of the + input audio buffer and add it to a new user message Item. + - The client has sent a `conversation.item.create` event to add a new Item + to the Conversation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.created + description: The event type, must be `conversation.item.created`. + x-stainless-const: true + previous_item_id: + anyOf: + - type: string + description: > + The ID of the preceding item in the Conversation context, allows + the + + client to understand the order of the conversation. Can be + `null` if the + + item has no predecessor. + - type: 'null' + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - item + x-oaiMeta: + name: conversation.item.created + group: realtime + example: | + { + "event_id": "event_1920", + "type": "conversation.item.created", + "previous_item_id": "msg_002", + "item": { + "id": "msg_003", + "object": "realtime.item", + "type": "message", + "status": "completed", + "role": "user", + "content": [] + } + } + RealtimeServerEventConversationItemDeleted: + type: object + description: > + Returned when an item in the conversation is deleted by the client with + a + + `conversation.item.delete` event. This event is used to synchronize the + + server's understanding of the conversation history with the client's + view. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.deleted + description: The event type, must be `conversation.item.deleted`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item that was deleted. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: conversation.item.deleted + group: realtime + example: | + { + "event_id": "event_2728", + "type": "conversation.item.deleted", + "item_id": "msg_005" + } + RealtimeServerEventConversationItemDone: + type: object + description: > + Returned when a conversation item is finalized. + + + The event will include the full content of the Item except for audio + data, which can be retrieved separately with a + `conversation.item.retrieve` event if needed. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.done + description: The event type, must be `conversation.item.done`. + x-stainless-const: true + previous_item_id: + anyOf: + - type: string + description: > + The ID of the item that precedes this one, if any. This is used + to + + maintain ordering when items are inserted. + - type: 'null' + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - item + x-oaiMeta: + name: conversation.item.done + group: realtime + example: | + { + "type": "conversation.item.done", + "event_id": "event_CCXLgMZPo3qioWCeQa4WH", + "previous_item_id": "item_CCXLecNJVIVR2HUy3ABLj", + "item": { + "id": "item_CCXLfxmM5sXVJVz4mCa2S", + "type": "message", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "output_audio", + "transcript": "Oh, I can hear you loud and clear! Sounds like we're connected just fine. What can I help you with today?" + } + ] + } + } + RealtimeServerEventConversationItemInputAudioTranscriptionCompleted: + type: object + description: > + This event is the output of audio transcription for user audio written + to the + + user audio buffer. Transcription begins when the input audio buffer is + + committed by the client or server (when VAD is enabled). Transcription + runs + + asynchronously with Response creation, so this event may come before or + after + + the Response events. + + + Realtime API models accept audio natively, and thus input transcription + is a + + separate process run on a separate ASR (Automatic Speech Recognition) + model. + + The transcript may diverge somewhat from the model's interpretation, and + + should be treated as a rough guide. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.input_audio_transcription.completed + description: | + The event type, must be + `conversation.item.input_audio_transcription.completed`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item containing the audio that is being transcribed. + content_index: + type: integer + description: The index of the content part containing the audio. + transcript: + type: string + description: The transcribed text. + logprobs: + anyOf: + - type: array + description: The log probabilities of the transcription. + items: + $ref: '#/components/schemas/LogProbProperties' + - type: 'null' + usage: + type: object + description: >- + Usage statistics for the transcription, this is billed according to + the ASR model's pricing rather than the realtime model's pricing. + oneOf: + - $ref: '#/components/schemas/TranscriptTextUsageTokens' + title: Token Usage + - $ref: '#/components/schemas/TranscriptTextUsageDuration' + title: Duration Usage + required: + - event_id + - type + - item_id + - content_index + - transcript + - usage + x-oaiMeta: + name: conversation.item.input_audio_transcription.completed + group: realtime + example: | + { + "type": "conversation.item.input_audio_transcription.completed", + "event_id": "event_CCXGRvtUVrax5SJAnNOWZ", + "item_id": "item_CCXGQ4e1ht4cOraEYcuR2", + "content_index": 0, + "transcript": "Hey, can you hear me?", + "usage": { + "type": "tokens", + "total_tokens": 22, + "input_tokens": 13, + "input_token_details": { + "text_tokens": 0, + "audio_tokens": 13 + }, + "output_tokens": 9 + } + } + RealtimeServerEventConversationItemInputAudioTranscriptionDelta: + type: object + description: > + Returned when the text value of an input audio transcription content + part is updated with incremental transcription results. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.input_audio_transcription.delta + description: >- + The event type, must be + `conversation.item.input_audio_transcription.delta`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item containing the audio that is being transcribed. + content_index: + type: integer + description: The index of the content part in the item's content array. + delta: + type: string + description: The text delta. + logprobs: + anyOf: + - type: array + description: >- + The log probabilities of the transcription. These can be enabled + by configurating the session with `"include": + ["item.input_audio_transcription.logprobs"]`. Each entry in the + array corresponds a log probability of which token would be + selected for this chunk of transcription. This can help to + identify if it was possible there were multiple valid options + for a given chunk of transcription. + items: + $ref: '#/components/schemas/LogProbProperties' + - type: 'null' + required: + - event_id + - type + - item_id + x-oaiMeta: + name: conversation.item.input_audio_transcription.delta + group: realtime + example: | + { + "type": "conversation.item.input_audio_transcription.delta", + "event_id": "event_CCXGRxsAimPAs8kS2Wc7Z", + "item_id": "item_CCXGQ4e1ht4cOraEYcuR2", + "content_index": 0, + "delta": "Hey", + "obfuscation": "aLxx0jTEciOGe" + } + RealtimeServerEventConversationItemInputAudioTranscriptionFailed: + type: object + description: > + Returned when input audio transcription is configured, and a + transcription + + request for a user message failed. These events are separate from other + + `error` events so that the client can identify the related Item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.input_audio_transcription.failed + description: | + The event type, must be + `conversation.item.input_audio_transcription.failed`. + x-stainless-const: true + item_id: + type: string + description: The ID of the user message item. + content_index: + type: integer + description: The index of the content part containing the audio. + error: + type: object + description: Details of the transcription error. + properties: + type: + type: string + description: The type of error. + code: + type: string + description: Error code, if any. + message: + type: string + description: A human-readable error message. + param: + type: string + description: Parameter related to the error, if any. + required: + - event_id + - type + - item_id + - content_index + - error + x-oaiMeta: + name: conversation.item.input_audio_transcription.failed + group: realtime + example: | + { + "event_id": "event_2324", + "type": "conversation.item.input_audio_transcription.failed", + "item_id": "msg_003", + "content_index": 0, + "error": { + "type": "transcription_error", + "code": "audio_unintelligible", + "message": "The audio could not be transcribed.", + "param": null + } + } + RealtimeServerEventConversationItemInputAudioTranscriptionSegment: + type: object + description: >- + Returned when an input audio transcription segment is identified for an + item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.input_audio_transcription.segment + description: >- + The event type, must be + `conversation.item.input_audio_transcription.segment`. + x-stainless-const: true + item_id: + type: string + description: The ID of the item containing the input audio content. + content_index: + type: integer + description: The index of the input audio content part within the item. + text: + type: string + description: The text for this segment. + id: + type: string + description: The segment identifier. + speaker: + type: string + description: The detected speaker label for this segment. + start: + type: number + format: float + description: Start time of the segment in seconds. + end: + type: number + format: float + description: End time of the segment in seconds. + required: + - event_id + - type + - item_id + - content_index + - text + - id + - speaker + - start + - end + x-oaiMeta: + name: conversation.item.input_audio_transcription.segment + group: realtime + example: | + { + "event_id": "event_6501", + "type": "conversation.item.input_audio_transcription.segment", + "item_id": "msg_011", + "content_index": 0, + "text": "hello", + "id": "seg_0001", + "speaker": "spk_1", + "start": 0.0, + "end": 0.4 + } + RealtimeServerEventConversationItemRetrieved: + type: object + description: > + Returned when a conversation item is retrieved with + `conversation.item.retrieve`. This is provided as a way to fetch the + server's representation of an item, for example to get access to the + post-processed audio data after noise cancellation and VAD. It includes + the full content of the Item, including audio data. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.retrieved + description: The event type, must be `conversation.item.retrieved`. + x-stainless-const: true + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - item + x-oaiMeta: + name: conversation.item.retrieved + group: realtime + example: | + { + "type": "conversation.item.retrieved", + "event_id": "event_CCXGSizgEppa2d4XbKA7K", + "item": { + "id": "item_CCXGRxbY0n6WE4EszhF5w", + "object": "realtime.item", + "type": "message", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "audio", + "transcript": "Yes, I can hear you loud and clear. How can I help you today?", + "audio": "8//2//v/9//q/+//+P/s...", + "format": "pcm16" + } + ] + } + } + RealtimeServerEventConversationItemTruncated: + type: object + description: > + Returned when an earlier assistant audio message item is truncated by + the + + client with a `conversation.item.truncate` event. This event is used to + + synchronize the server's understanding of the audio with the client's + playback. + + + This action will truncate the audio and remove the server-side text + transcript + + to ensure there is no text in the context that hasn't been heard by the + user. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - conversation.item.truncated + description: The event type, must be `conversation.item.truncated`. + x-stainless-const: true + item_id: + type: string + description: The ID of the assistant message item that was truncated. + content_index: + type: integer + description: The index of the content part that was truncated. + audio_end_ms: + type: integer + description: | + The duration up to which the audio was truncated, in milliseconds. + required: + - event_id + - type + - item_id + - content_index + - audio_end_ms + x-oaiMeta: + name: conversation.item.truncated + group: realtime + example: | + { + "event_id": "event_2526", + "type": "conversation.item.truncated", + "item_id": "msg_004", + "content_index": 0, + "audio_end_ms": 1500 + } + RealtimeServerEventError: + type: object + description: > + Returned when an error occurs, which could be a client problem or a + server + + problem. Most errors are recoverable and the session will stay open, we + + recommend to implementors to monitor and log error messages by default. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - error + description: The event type, must be `error`. + x-stainless-const: true + error: + type: object + description: Details of the error. + required: + - type + - message + properties: + type: + type: string + description: > + The type of error (e.g., "invalid_request_error", + "server_error"). + code: + anyOf: + - type: string + description: Error code, if any. + - type: 'null' + message: + type: string + description: A human-readable error message. + param: + anyOf: + - type: string + description: Parameter related to the error, if any. + - type: 'null' + event_id: + anyOf: + - type: string + description: > + The event_id of the client event that caused the error, if + applicable. + - type: 'null' + required: + - event_id + - type + - error + x-oaiMeta: + name: error + group: realtime + example: | + { + "event_id": "event_890", + "type": "error", + "error": { + "type": "invalid_request_error", + "code": "invalid_event", + "message": "The 'type' field is missing.", + "param": null, + "event_id": "event_567" + } + } + RealtimeServerEventInputAudioBufferCleared: + type: object + description: | + Returned when the input audio buffer is cleared by the client with a + `input_audio_buffer.clear` event. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - input_audio_buffer.cleared + description: The event type, must be `input_audio_buffer.cleared`. + x-stainless-const: true + required: + - event_id + - type + x-oaiMeta: + name: input_audio_buffer.cleared + group: realtime + example: | + { + "event_id": "event_1314", + "type": "input_audio_buffer.cleared" + } + RealtimeServerEventInputAudioBufferCommitted: + type: object + description: > + Returned when an input audio buffer is committed, either by the client + or + + automatically in server VAD mode. The `item_id` property is the ID of + the user + + message item that will be created, thus a `conversation.item.created` + event + + will also be sent to the client. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - input_audio_buffer.committed + description: The event type, must be `input_audio_buffer.committed`. + x-stainless-const: true + previous_item_id: + anyOf: + - type: string + description: > + The ID of the preceding item after which the new item will be + inserted. + + Can be `null` if the item has no predecessor. + - type: 'null' + item_id: + type: string + description: The ID of the user message item that will be created. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: input_audio_buffer.committed + group: realtime + example: | + { + "event_id": "event_1121", + "type": "input_audio_buffer.committed", + "previous_item_id": "msg_001", + "item_id": "msg_002" + } + RealtimeServerEventInputAudioBufferDtmfEventReceived: + type: object + description: > + **SIP Only:** Returned when an DTMF event is received. A DTMF event is a + message that + + represents a telephone keypad press (0–9, *, #, A–D). The `event` + property + + is the keypad that the user press. The `received_at` is the UTC Unix + Timestamp + + that the server received the event. + properties: + type: + type: string + enum: + - input_audio_buffer.dtmf_event_received + description: The event type, must be `input_audio_buffer.dtmf_event_received`. + x-stainless-const: true + event: + type: string + description: The telephone keypad that was pressed by the user. + received_at: + type: integer + description: | + UTC Unix Timestamp when DTMF Event was received by server. + required: + - type + - event + - received_at + x-oaiMeta: + name: input_audio_buffer.dtmf_event_received + group: realtime + example: | + { + "type":" input_audio_buffer.dtmf_event_received", + "event": "9", + "received_at": 1763605109, + } + RealtimeServerEventInputAudioBufferSpeechStarted: + type: object + description: > + Sent by the server when in `server_vad` mode to indicate that speech has + been + + detected in the audio buffer. This can happen any time audio is added to + the + + buffer (unless speech is already detected). The client may want to use + this + + event to interrupt audio playback or provide visual feedback to the + user. + + + The client should expect to receive a + `input_audio_buffer.speech_stopped` event + + when speech stops. The `item_id` property is the ID of the user message + item + + that will be created when speech stops and will also be included in the + + `input_audio_buffer.speech_stopped` event (unless the client manually + commits + + the audio buffer during VAD activation). + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - input_audio_buffer.speech_started + description: The event type, must be `input_audio_buffer.speech_started`. + x-stainless-const: true + audio_start_ms: + type: integer + description: > + Milliseconds from the start of all audio written to the buffer + during the + + session when speech was first detected. This will correspond to the + + beginning of audio sent to the model, and thus includes the + + `prefix_padding_ms` configured in the Session. + item_id: + type: string + description: > + The ID of the user message item that will be created when speech + stops. + required: + - event_id + - type + - audio_start_ms + - item_id + x-oaiMeta: + name: input_audio_buffer.speech_started + group: realtime + example: | + { + "event_id": "event_1516", + "type": "input_audio_buffer.speech_started", + "audio_start_ms": 1000, + "item_id": "msg_003" + } + RealtimeServerEventInputAudioBufferSpeechStopped: + type: object + description: > + Returned in `server_vad` mode when the server detects the end of speech + in + + the audio buffer. The server will also send an + `conversation.item.created` + + event with the user message item that is created from the audio buffer. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - input_audio_buffer.speech_stopped + description: The event type, must be `input_audio_buffer.speech_stopped`. + x-stainless-const: true + audio_end_ms: + type: integer + description: > + Milliseconds since the session started when speech stopped. This + will + + correspond to the end of audio sent to the model, and thus includes + the + + `min_silence_duration_ms` configured in the Session. + item_id: + type: string + description: The ID of the user message item that will be created. + required: + - event_id + - type + - audio_end_ms + - item_id + x-oaiMeta: + name: input_audio_buffer.speech_stopped + group: realtime + example: | + { + "event_id": "event_1718", + "type": "input_audio_buffer.speech_stopped", + "audio_end_ms": 2000, + "item_id": "msg_003" + } + RealtimeServerEventInputAudioBufferTimeoutTriggered: + type: object + description: > + Returned when the Server VAD timeout is triggered for the input audio + buffer. This is configured + + with `idle_timeout_ms` in the `turn_detection` settings of the session, + and it indicates that + + there hasn't been any speech detected for the configured duration. + + + The `audio_start_ms` and `audio_end_ms` fields indicate the segment of + audio after the last + + model response up to the triggering time, as an offset from the + beginning of audio written + + to the input audio buffer. This means it demarcates the segment of audio + that was silent and + + the difference between the start and end values will roughly match the + configured timeout. + + + The empty audio will be committed to the conversation as an + `input_audio` item (there will be a + + `input_audio_buffer.committed` event) and a model response will be + generated. There may be speech + + that didn't trigger VAD but is still detected by the model, so the model + may respond with + + something relevant to the conversation or a prompt to continue speaking. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - input_audio_buffer.timeout_triggered + description: The event type, must be `input_audio_buffer.timeout_triggered`. + x-stainless-const: true + audio_start_ms: + type: integer + description: >- + Millisecond offset of audio written to the input audio buffer that + was after the playback time of the last model response. + audio_end_ms: + type: integer + description: >- + Millisecond offset of audio written to the input audio buffer at the + time the timeout was triggered. + item_id: + type: string + description: The ID of the item associated with this segment. + required: + - event_id + - type + - audio_start_ms + - audio_end_ms + - item_id + x-oaiMeta: + name: input_audio_buffer.timeout_triggered + group: realtime + example: | + { + "type":"input_audio_buffer.timeout_triggered", + "event_id":"event_CEKKrf1KTGvemCPyiJTJ2", + "audio_start_ms":13216, + "audio_end_ms":19232, + "item_id":"item_CEKKrWH0GiwN0ET97NUZc" + } + RealtimeServerEventMCPListToolsCompleted: + type: object + description: Returned when listing MCP tools has completed for an item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - mcp_list_tools.completed + description: The event type, must be `mcp_list_tools.completed`. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP list tools item. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: mcp_list_tools.completed + group: realtime + example: | + { + "event_id": "event_6102", + "type": "mcp_list_tools.completed", + "item_id": "mcp_list_tools_001" + } + RealtimeServerEventMCPListToolsFailed: + type: object + description: Returned when listing MCP tools has failed for an item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - mcp_list_tools.failed + description: The event type, must be `mcp_list_tools.failed`. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP list tools item. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: mcp_list_tools.failed + group: realtime + example: | + { + "event_id": "event_6103", + "type": "mcp_list_tools.failed", + "item_id": "mcp_list_tools_001" + } + RealtimeServerEventMCPListToolsInProgress: + type: object + description: Returned when listing MCP tools is in progress for an item. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - mcp_list_tools.in_progress + description: The event type, must be `mcp_list_tools.in_progress`. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP list tools item. + required: + - event_id + - type + - item_id + x-oaiMeta: + name: mcp_list_tools.in_progress + group: realtime + example: | + { + "event_id": "event_6101", + "type": "mcp_list_tools.in_progress", + "item_id": "mcp_list_tools_001" + } + RealtimeServerEventOutputAudioBufferCleared: + type: object + description: > + **WebRTC/SIP Only:** Emitted when the output audio buffer is cleared. + This happens either in VAD + + mode when the user has interrupted + (`input_audio_buffer.speech_started`), + + or when the client has emitted the `output_audio_buffer.clear` event to + manually + + cut off the current audio response. + + [Learn + more](/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - output_audio_buffer.cleared + description: The event type, must be `output_audio_buffer.cleared`. + x-stainless-const: true + response_id: + type: string + description: The unique ID of the response that produced the audio. + required: + - event_id + - type + - response_id + x-oaiMeta: + name: output_audio_buffer.cleared + group: realtime + example: | + { + "event_id": "event_abc123", + "type": "output_audio_buffer.cleared", + "response_id": "resp_abc123" + } + RealtimeServerEventOutputAudioBufferStarted: + type: object + description: > + **WebRTC/SIP Only:** Emitted when the server begins streaming audio to + the client. This event is + + emitted after an audio content part has been added + (`response.content_part.added`) + + to the response. + + [Learn + more](/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - output_audio_buffer.started + description: The event type, must be `output_audio_buffer.started`. + x-stainless-const: true + response_id: + type: string + description: The unique ID of the response that produced the audio. + required: + - event_id + - type + - response_id + x-oaiMeta: + name: output_audio_buffer.started + group: realtime + example: | + { + "event_id": "event_abc123", + "type": "output_audio_buffer.started", + "response_id": "resp_abc123" + } + RealtimeServerEventOutputAudioBufferStopped: + type: object + description: > + **WebRTC/SIP Only:** Emitted when the output audio buffer has been + completely drained on the server, + + and no more audio is forthcoming. This event is emitted after the full + response + + data has been sent to the client (`response.done`). + + [Learn + more](/docs/guides/realtime-conversations#client-and-server-events-for-audio-in-webrtc). + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - output_audio_buffer.stopped + description: The event type, must be `output_audio_buffer.stopped`. + x-stainless-const: true + response_id: + type: string + description: The unique ID of the response that produced the audio. + required: + - event_id + - type + - response_id + x-oaiMeta: + name: output_audio_buffer.stopped + group: realtime + example: | + { + "event_id": "event_abc123", + "type": "output_audio_buffer.stopped", + "response_id": "resp_abc123" + } + RealtimeServerEventRateLimitsUpdated: + type: object + description: > + Emitted at the beginning of a Response to indicate the updated rate + limits. + + When a Response is created some tokens will be "reserved" for the + output + + tokens, the rate limits shown here reflect that reservation, which is + then + + adjusted accordingly once the Response is completed. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - rate_limits.updated + description: The event type, must be `rate_limits.updated`. + x-stainless-const: true + rate_limits: + type: array + description: List of rate limit information. + items: + type: object + properties: + name: + type: string + enum: + - requests + - tokens + description: | + The name of the rate limit (`requests`, `tokens`). + limit: + type: integer + description: The maximum allowed value for the rate limit. + remaining: + type: integer + description: The remaining value before the limit is reached. + reset_seconds: + type: number + description: Seconds until the rate limit resets. + required: + - event_id + - type + - rate_limits + x-oaiMeta: + name: rate_limits.updated + group: realtime + example: | + { + "event_id": "event_5758", + "type": "rate_limits.updated", + "rate_limits": [ + { + "name": "requests", + "limit": 1000, + "remaining": 999, + "reset_seconds": 60 + }, + { + "name": "tokens", + "limit": 50000, + "remaining": 49950, + "reset_seconds": 60 + } + ] + } + RealtimeServerEventResponseAudioDelta: + type: object + description: Returned when the model-generated audio is updated. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_audio.delta + description: The event type, must be `response.output_audio.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + delta: + type: string + description: Base64-encoded audio data delta. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - delta + x-oaiMeta: + name: response.output_audio.delta + group: realtime + example: | + { + "event_id": "event_4950", + "type": "response.output_audio.delta", + "response_id": "resp_001", + "item_id": "msg_008", + "output_index": 0, + "content_index": 0, + "delta": "Base64EncodedAudioDelta" + } + RealtimeServerEventResponseAudioDone: + type: object + description: > + Returned when the model-generated audio is done. Also emitted when a + Response + + is interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_audio.done + description: The event type, must be `response.output_audio.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + x-oaiMeta: + name: response.output_audio.done + group: realtime + example: | + { + "event_id": "event_5152", + "type": "response.output_audio.done", + "response_id": "resp_001", + "item_id": "msg_008", + "output_index": 0, + "content_index": 0 + } + RealtimeServerEventResponseAudioTranscriptDelta: + type: object + description: > + Returned when the model-generated transcription of audio output is + updated. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_audio_transcript.delta + description: The event type, must be `response.output_audio_transcript.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + delta: + type: string + description: The transcript delta. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - delta + x-oaiMeta: + name: response.output_audio_transcript.delta + group: realtime + example: | + { + "event_id": "event_4546", + "type": "response.output_audio_transcript.delta", + "response_id": "resp_001", + "item_id": "msg_008", + "output_index": 0, + "content_index": 0, + "delta": "Hello, how can I a" + } + RealtimeServerEventResponseAudioTranscriptDone: + type: object + description: | + Returned when the model-generated transcription of audio output is done + streaming. Also emitted when a Response is interrupted, incomplete, or + cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_audio_transcript.done + description: The event type, must be `response.output_audio_transcript.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + transcript: + type: string + description: The final transcript of the audio. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - transcript + x-oaiMeta: + name: response.output_audio_transcript.done + group: realtime + example: | + { + "event_id": "event_4748", + "type": "response.output_audio_transcript.done", + "response_id": "resp_001", + "item_id": "msg_008", + "output_index": 0, + "content_index": 0, + "transcript": "Hello, how can I assist you today?" + } + RealtimeServerEventResponseContentPartAdded: + type: object + description: > + Returned when a new content part is added to an assistant message item + during + + response generation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.content_part.added + description: The event type, must be `response.content_part.added`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item to which the content part was added. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + part: + type: object + description: The content part that was added. + properties: + type: + type: string + enum: + - audio + - text + description: The content type ("text", "audio"). + text: + type: string + description: The text content (if type is "text"). + audio: + type: string + description: Base64-encoded audio data (if type is "audio"). + transcript: + type: string + description: The transcript of the audio (if type is "audio"). + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - part + x-oaiMeta: + name: response.content_part.added + group: realtime + example: | + { + "event_id": "event_3738", + "type": "response.content_part.added", + "response_id": "resp_001", + "item_id": "msg_007", + "output_index": 0, + "content_index": 0, + "part": { + "type": "text", + "text": "" + } + } + RealtimeServerEventResponseContentPartDone: + type: object + description: > + Returned when a content part is done streaming in an assistant message + item. + + Also emitted when a Response is interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.content_part.done + description: The event type, must be `response.content_part.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + part: + type: object + description: The content part that is done. + properties: + type: + type: string + enum: + - audio + - text + description: The content type ("text", "audio"). + text: + type: string + description: The text content (if type is "text"). + audio: + type: string + description: Base64-encoded audio data (if type is "audio"). + transcript: + type: string + description: The transcript of the audio (if type is "audio"). + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - part + x-oaiMeta: + name: response.content_part.done + group: realtime + example: | + { + "event_id": "event_3940", + "type": "response.content_part.done", + "response_id": "resp_001", + "item_id": "msg_007", + "output_index": 0, + "content_index": 0, + "part": { + "type": "text", + "text": "Sure, I can help with that." + } + } + RealtimeServerEventResponseCreated: + type: object + description: > + Returned when a new Response is created. The first event of response + creation, + + where the response is in an initial state of `in_progress`. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.created + description: The event type, must be `response.created`. + x-stainless-const: true + response: + $ref: '#/components/schemas/RealtimeResponse' + required: + - event_id + - type + - response + x-oaiMeta: + name: response.created + group: realtime + example: | + { + "type": "response.created", + "event_id": "event_C9G8pqbTEddBSIxbBN6Os", + "response": { + "object": "realtime.response", + "id": "resp_C9G8p7IH2WxLbkgPNouYL", + "status": "in_progress", + "status_details": null, + "output": [], + "conversation_id": "conv_C9G8mmBkLhQJwCon3hoJN", + "output_modalities": [ + "audio" + ], + "max_output_tokens": "inf", + "audio": { + "output": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "voice": "marin" + } + }, + "usage": null, + "metadata": null + }, + } + RealtimeServerEventResponseDone: + type: object + description: > + Returned when a Response is done streaming. Always emitted, no matter + the + + final state. The Response object included in the `response.done` event + will + + include all output Items in the Response but will omit the raw audio + data. + + + Clients should check the `status` field of the Response to determine if + it was successful + + (`completed`) or if there was another outcome: `cancelled`, `failed`, or + `incomplete`. + + + A response will contain all output items that were generated during the + response, excluding + + any audio content. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.done + description: The event type, must be `response.done`. + x-stainless-const: true + response: + $ref: '#/components/schemas/RealtimeResponse' + required: + - event_id + - type + - response + x-oaiMeta: + name: response.done + group: realtime + example: | + { + "type": "response.done", + "event_id": "event_CCXHxcMy86rrKhBLDdqCh", + "response": { + "object": "realtime.response", + "id": "resp_CCXHw0UJld10EzIUXQCNh", + "status": "completed", + "status_details": null, + "output": [ + { + "id": "item_CCXHwGjjDUfOXbiySlK7i", + "type": "message", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "output_audio", + "transcript": "Loud and clear! I can hear you perfectly. How can I help you today?" + } + ] + } + ], + "conversation_id": "conv_CCXHsurMKcaVxIZvaCI5m", + "output_modalities": [ + "audio" + ], + "max_output_tokens": "inf", + "audio": { + "output": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "voice": "alloy" + } + }, + "usage": { + "total_tokens": 253, + "input_tokens": 132, + "output_tokens": 121, + "input_token_details": { + "text_tokens": 119, + "audio_tokens": 13, + "image_tokens": 0, + "cached_tokens": 64, + "cached_tokens_details": { + "text_tokens": 64, + "audio_tokens": 0, + "image_tokens": 0 + } + }, + "output_token_details": { + "text_tokens": 30, + "audio_tokens": 91 + } + }, + "metadata": null + } + } + RealtimeServerEventResponseFunctionCallArgumentsDelta: + type: object + description: | + Returned when the model-generated function call arguments are updated. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.function_call_arguments.delta + description: | + The event type, must be `response.function_call_arguments.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the function call item. + output_index: + type: integer + description: The index of the output item in the response. + call_id: + type: string + description: The ID of the function call. + delta: + type: string + description: The arguments delta as a JSON string. + required: + - event_id + - type + - response_id + - item_id + - output_index + - call_id + - delta + x-oaiMeta: + name: response.function_call_arguments.delta + group: realtime + example: | + { + "event_id": "event_5354", + "type": "response.function_call_arguments.delta", + "response_id": "resp_002", + "item_id": "fc_001", + "output_index": 0, + "call_id": "call_001", + "delta": "{\"location\": \"San\"" + } + RealtimeServerEventResponseFunctionCallArgumentsDone: + type: object + description: > + Returned when the model-generated function call arguments are done + streaming. + + Also emitted when a Response is interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.function_call_arguments.done + description: | + The event type, must be `response.function_call_arguments.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the function call item. + output_index: + type: integer + description: The index of the output item in the response. + call_id: + type: string + description: The ID of the function call. + name: + type: string + description: The name of the function that was called. + arguments: + type: string + description: The final arguments as a JSON string. + required: + - event_id + - type + - response_id + - item_id + - output_index + - call_id + - name + - arguments + x-oaiMeta: + name: response.function_call_arguments.done + group: realtime + example: | + { + "event_id": "event_5556", + "type": "response.function_call_arguments.done", + "response_id": "resp_002", + "item_id": "fc_001", + "output_index": 0, + "call_id": "call_001", + "name": "get_weather", + "arguments": "{\"location\": \"San Francisco\"}" + } + RealtimeServerEventResponseMCPCallArgumentsDelta: + type: object + description: >- + Returned when MCP tool call arguments are updated during response + generation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call_arguments.delta + description: The event type, must be `response.mcp_call_arguments.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the MCP tool call item. + output_index: + type: integer + description: The index of the output item in the response. + delta: + type: string + description: The JSON-encoded arguments delta. + obfuscation: + anyOf: + - type: string + description: If present, indicates the delta text was obfuscated. + - type: 'null' + required: + - event_id + - type + - response_id + - item_id + - output_index + - delta + x-oaiMeta: + name: response.mcp_call_arguments.delta + group: realtime + example: | + { + "event_id": "event_6201", + "type": "response.mcp_call_arguments.delta", + "response_id": "resp_001", + "item_id": "mcp_call_001", + "output_index": 0, + "delta": "{\"partial\":true}" + } + RealtimeServerEventResponseMCPCallArgumentsDone: + type: object + description: >- + Returned when MCP tool call arguments are finalized during response + generation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call_arguments.done + description: The event type, must be `response.mcp_call_arguments.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the MCP tool call item. + output_index: + type: integer + description: The index of the output item in the response. + arguments: + type: string + description: The final JSON-encoded arguments string. + required: + - event_id + - type + - response_id + - item_id + - output_index + - arguments + x-oaiMeta: + name: response.mcp_call_arguments.done + group: realtime + example: | + { + "event_id": "event_6202", + "type": "response.mcp_call_arguments.done", + "response_id": "resp_001", + "item_id": "mcp_call_001", + "output_index": 0, + "arguments": "{\"q\":\"docs\"}" + } + RealtimeServerEventResponseMCPCallCompleted: + type: object + description: Returned when an MCP tool call has completed successfully. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call.completed + description: The event type, must be `response.mcp_call.completed`. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response. + item_id: + type: string + description: The ID of the MCP tool call item. + required: + - event_id + - type + - output_index + - item_id + x-oaiMeta: + name: response.mcp_call.completed + group: realtime + example: | + { + "event_id": "event_6302", + "type": "response.mcp_call.completed", + "output_index": 0, + "item_id": "mcp_call_001" + } + RealtimeServerEventResponseMCPCallFailed: + type: object + description: Returned when an MCP tool call has failed. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call.failed + description: The event type, must be `response.mcp_call.failed`. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response. + item_id: + type: string + description: The ID of the MCP tool call item. + required: + - event_id + - type + - output_index + - item_id + x-oaiMeta: + name: response.mcp_call.failed + group: realtime + example: | + { + "event_id": "event_6303", + "type": "response.mcp_call.failed", + "output_index": 0, + "item_id": "mcp_call_001" + } + RealtimeServerEventResponseMCPCallInProgress: + type: object + description: Returned when an MCP tool call has started and is in progress. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.mcp_call.in_progress + description: The event type, must be `response.mcp_call.in_progress`. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response. + item_id: + type: string + description: The ID of the MCP tool call item. + required: + - event_id + - type + - output_index + - item_id + x-oaiMeta: + name: response.mcp_call.in_progress + group: realtime + example: | + { + "event_id": "event_6301", + "type": "response.mcp_call.in_progress", + "output_index": 0, + "item_id": "mcp_call_001" + } + RealtimeServerEventResponseOutputItemAdded: + type: object + description: Returned when a new Item is created during Response generation. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_item.added + description: The event type, must be `response.output_item.added`. + x-stainless-const: true + response_id: + type: string + description: The ID of the Response to which the item belongs. + output_index: + type: integer + description: The index of the output item in the Response. + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - response_id + - output_index + - item + x-oaiMeta: + name: response.output_item.added + group: realtime + example: | + { + "event_id": "event_3334", + "type": "response.output_item.added", + "response_id": "resp_001", + "output_index": 0, + "item": { + "id": "msg_007", + "object": "realtime.item", + "type": "message", + "status": "in_progress", + "role": "assistant", + "content": [] + } + } + RealtimeServerEventResponseOutputItemDone: + type: object + description: > + Returned when an Item is done streaming. Also emitted when a Response + is + + interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_item.done + description: The event type, must be `response.output_item.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the Response to which the item belongs. + output_index: + type: integer + description: The index of the output item in the Response. + item: + $ref: '#/components/schemas/RealtimeConversationItem' + required: + - event_id + - type + - response_id + - output_index + - item + x-oaiMeta: + name: response.output_item.done + group: realtime + example: | + { + "event_id": "event_3536", + "type": "response.output_item.done", + "response_id": "resp_001", + "output_index": 0, + "item": { + "id": "msg_007", + "object": "realtime.item", + "type": "message", + "status": "completed", + "role": "assistant", + "content": [ + { + "type": "text", + "text": "Sure, I can help with that." + } + ] + } + } + RealtimeServerEventResponseTextDelta: + type: object + description: >- + Returned when the text value of an "output_text" content part is + updated. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_text.delta + description: The event type, must be `response.output_text.delta`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + delta: + type: string + description: The text delta. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - delta + x-oaiMeta: + name: response.output_text.delta + group: realtime + example: | + { + "event_id": "event_4142", + "type": "response.output_text.delta", + "response_id": "resp_001", + "item_id": "msg_007", + "output_index": 0, + "content_index": 0, + "delta": "Sure, I can h" + } + RealtimeServerEventResponseTextDone: + type: object + description: > + Returned when the text value of an "output_text" content part is done + streaming. Also + + emitted when a Response is interrupted, incomplete, or cancelled. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - response.output_text.done + description: The event type, must be `response.output_text.done`. + x-stainless-const: true + response_id: + type: string + description: The ID of the response. + item_id: + type: string + description: The ID of the item. + output_index: + type: integer + description: The index of the output item in the response. + content_index: + type: integer + description: The index of the content part in the item's content array. + text: + type: string + description: The final text content. + required: + - event_id + - type + - response_id + - item_id + - output_index + - content_index + - text + x-oaiMeta: + name: response.output_text.done + group: realtime + example: | + { + "event_id": "event_4344", + "type": "response.output_text.done", + "response_id": "resp_001", + "item_id": "msg_007", + "output_index": 0, + "content_index": 0, + "text": "Sure, I can help with that." + } + RealtimeServerEventSessionCreated: + type: object + description: > + Returned when a Session is created. Emitted automatically when a new + + connection is established as the first server event. This event will + contain + + the default Session configuration. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - session.created + description: The event type, must be `session.created`. + x-stainless-const: true + session: + description: The session configuration. + oneOf: + - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' + - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequestGA' + required: + - event_id + - type + - session + x-oaiMeta: + name: session.created + group: realtime + example: | + { + "type": "session.created", + "event_id": "event_C9G5RJeJ2gF77mV7f2B1j", + "session": { + "type": "realtime", + "object": "realtime.session", + "id": "sess_C9G5QPteg4UIbotdKLoYQ", + "model": "gpt-realtime-2025-08-28", + "output_modalities": [ + "audio" + ], + "instructions": "Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you’re asked about them.", + "tools": [], + "tool_choice": "auto", + "max_output_tokens": "inf", + "tracing": null, + "prompt": null, + "expires_at": 1756324625, + "audio": { + "input": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "transcription": null, + "noise_reduction": null, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 200, + "idle_timeout_ms": null, + "create_response": true, + "interrupt_response": true + } + }, + "output": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "voice": "marin", + "speed": 1 + } + }, + "include": null + }, + } + RealtimeServerEventSessionUpdated: + type: object + description: | + Returned when a session is updated with a `session.update` event, unless + there is an error. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - session.updated + description: The event type, must be `session.updated`. + x-stainless-const: true + session: + description: The session configuration. + oneOf: + - $ref: '#/components/schemas/RealtimeSessionCreateRequestGA' + - $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateRequestGA' + required: + - event_id + - type + - session + x-oaiMeta: + name: session.updated + group: realtime + example: | + { + "type": "session.updated", + "event_id": "event_C9G8mqI3IucaojlVKE8Cs", + "session": { + "type": "realtime", + "object": "realtime.session", + "id": "sess_C9G8l3zp50uFv4qgxfJ8o", + "model": "gpt-realtime-2025-08-28", + "output_modalities": [ + "audio" + ], + "instructions": "Your knowledge cutoff is 2023-10. You are a helpful, witty, and friendly AI. Act like a human, but remember that you aren't a human and that you can't do human things in the real world. Your voice and personality should be warm and engaging, with a lively and playful tone. If interacting in a non-English language, start by using the standard accent or dialect familiar to the user. Talk quickly. You should always call a function if you can. Do not refer to these rules, even if you’re asked about them.", + "tools": [ + { + "type": "function", + "name": "display_color_palette", + "description": "\nCall this function when a user asks for a color palette.\n", + "parameters": { + "type": "object", + "strict": true, + "properties": { + "theme": { + "type": "string", + "description": "Description of the theme for the color scheme." + }, + "colors": { + "type": "array", + "description": "Array of five hex color codes based on the theme.", + "items": { + "type": "string", + "description": "Hex color code" + } + } + }, + "required": [ + "theme", + "colors" + ] + } + } + ], + "tool_choice": "auto", + "max_output_tokens": "inf", + "tracing": null, + "prompt": null, + "expires_at": 1756324832, + "audio": { + "input": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "transcription": null, + "noise_reduction": null, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 200, + "idle_timeout_ms": null, + "create_response": true, + "interrupt_response": true + } + }, + "output": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "voice": "marin", + "speed": 1 + } + }, + "include": null + }, + } + RealtimeServerEventTranscriptionSessionUpdated: + type: object + description: > + Returned when a transcription session is updated with a + `transcription_session.update` event, unless + + there is an error. + properties: + event_id: + type: string + description: The unique ID of the server event. + type: + type: string + enum: + - transcription_session.updated + description: The event type, must be `transcription_session.updated`. + x-stainless-const: true + session: + $ref: '#/components/schemas/RealtimeTranscriptionSessionCreateResponse' + required: + - event_id + - type + - session + x-oaiMeta: + name: transcription_session.updated + group: realtime + example: | + { + "event_id": "event_5678", + "type": "transcription_session.updated", + "session": { + "id": "sess_001", + "object": "realtime.transcription_session", + "input_audio_format": "pcm16", + "input_audio_transcription": { + "model": "gpt-4o-transcribe", + "prompt": "", + "language": "" + }, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 500, + "create_response": true, + // "interrupt_response": false -- this will NOT be returned + }, + "input_audio_noise_reduction": { + "type": "near_field" + }, + "include": [ + "item.input_audio_transcription.avg_logprob", + ], + } + } + RealtimeSession: + type: object + description: Realtime session object for the beta interface. + properties: + id: + type: string + description: > + Unique identifier for the session that looks like + `sess_1234567890abcdef`. + object: + type: string + enum: + - realtime.session + description: The object type. Always `realtime.session`. + modalities: + description: | + The set of modalities the model can respond with. To disable audio, + set this to ["text"]. + items: + type: string + default: + - text + - audio + enum: + - text + - audio + model: + description: | + The Realtime model used for this session. + anyOf: + - type: string + - type: string + enum: + - gpt-realtime + - gpt-realtime-1.5 + - gpt-realtime-2025-08-28 + - gpt-4o-realtime-preview + - gpt-4o-realtime-preview-2024-10-01 + - gpt-4o-realtime-preview-2024-12-17 + - gpt-4o-realtime-preview-2025-06-03 + - gpt-4o-mini-realtime-preview + - gpt-4o-mini-realtime-preview-2024-12-17 + - gpt-realtime-mini + - gpt-realtime-mini-2025-10-06 + - gpt-realtime-mini-2025-12-15 + - gpt-audio-1.5 + - gpt-audio-mini + - gpt-audio-mini-2025-10-06 + - gpt-audio-mini-2025-12-15 + instructions: + type: string + description: > + The default system instructions (i.e. system message) prepended to + model + + calls. This field allows the client to guide the model on desired + + responses. The model can be instructed on response content and + format, + + (e.g. "be extremely succinct", "act friendly", "here are examples of + good + + responses") and on audio behavior (e.g. "talk quickly", "inject + emotion + + into your voice", "laugh frequently"). The instructions are not + + guaranteed to be followed by the model, but they provide guidance to + the + + model on the desired behavior. + + + + Note that the server sets default instructions which will be used if + this + + field is not set and are visible in the `session.created` event at + the + + start of the session. + voice: + $ref: '#/components/schemas/VoiceIdsShared' + description: > + The voice the model uses to respond. Voice cannot be changed during + the + + session once the model has responded with audio at least once. + Current + + voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, + + `shimmer`, and `verse`. + input_audio_format: + type: string + default: pcm16 + enum: + - pcm16 + - g711_ulaw + - g711_alaw + description: > + The format of input audio. Options are `pcm16`, `g711_ulaw`, or + `g711_alaw`. + + For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, + + single channel (mono), and little-endian byte order. + output_audio_format: + type: string + default: pcm16 + enum: + - pcm16 + - g711_ulaw + - g711_alaw + description: > + The format of output audio. Options are `pcm16`, `g711_ulaw`, or + `g711_alaw`. + + For `pcm16`, output audio is sampled at a rate of 24kHz. + input_audio_transcription: + anyOf: + - allOf: + - $ref: '#/components/schemas/AudioTranscription' + description: > + Configuration for input audio transcription, defaults to off and + can be set to `null` to turn off once on. Input audio + transcription is not native to the model, since the model + consumes audio directly. Transcription runs asynchronously + through [the /audio/transcriptions + endpoint](https://platform.openai.com/docs/api-reference/audio/createTranscription) + and should be treated as guidance of input audio content rather + than precisely what the model heard. The client can optionally + set the language and prompt for transcription, these offer + additional guidance to the transcription service. + - type: 'null' + turn_detection: + $ref: '#/components/schemas/RealtimeTurnDetection' + input_audio_noise_reduction: + type: object + default: null + description: > + Configuration for input audio noise reduction. This can be set to + `null` to turn off. + + Noise reduction filters audio added to the input audio buffer before + it is sent to VAD and the model. + + Filtering the audio can improve VAD and turn detection accuracy + (reducing false positives) and model performance by improving + perception of the input audio. + properties: + type: + $ref: '#/components/schemas/NoiseReductionType' + speed: + type: number + default: 1 + maximum: 1.5 + minimum: 0.25 + description: > + The speed of the model's spoken response. 1.0 is the default speed. + 0.25 is + + the minimum speed. 1.5 is the maximum speed. This value can only be + changed + + in between model turns, not while a response is in progress. + tracing: + anyOf: + - title: Tracing Configuration + description: > + Configuration options for tracing. Set to null to disable + tracing. Once + + tracing is enabled for a session, the configuration cannot be + modified. + + + `auto` will create a trace for the session with default values + for the + + workflow name, group id, and metadata. + oneOf: + - type: string + default: auto + description: | + Default tracing mode for the session. + enum: + - auto + x-stainless-const: true + - type: object + title: Tracing Configuration + description: | + Granular configuration for tracing. + properties: + workflow_name: + type: string + description: > + The name of the workflow to attach to this trace. This + is used to + + name the trace in the traces dashboard. + group_id: + type: string + description: > + The group id to attach to this trace to enable filtering + and + + grouping in the traces dashboard. + metadata: + type: object + description: | + The arbitrary metadata to attach to this trace to enable + filtering in the traces dashboard. + - type: 'null' + tools: + type: array + description: Tools (functions) available to the model. + items: + $ref: '#/components/schemas/RealtimeFunctionTool' + tool_choice: + type: string + default: auto + description: > + How the model chooses tools. Options are `auto`, `none`, `required`, + or + + specify a function. + temperature: + type: number + default: 0.8 + description: > + Sampling temperature for the model, limited to [0.6, 1.2]. For audio + models a temperature of 0.8 is highly recommended for best + performance. + max_response_output_tokens: + oneOf: + - type: integer + - type: string + enum: + - inf + x-stainless-const: true + description: | + Maximum number of output tokens for a single assistant response, + inclusive of tool calls. Provide an integer between 1 and 4096 to + limit output tokens, or `inf` for the maximum available tokens for a + given model. Defaults to `inf`. + expires_at: + type: integer + description: Expiration timestamp for the session, in seconds since epoch. + prompt: + anyOf: + - $ref: '#/components/schemas/Prompt' + - type: 'null' + include: + anyOf: + - type: array + items: + type: string + enum: + - item.input_audio_transcription.logprobs + description: > + Additional fields to include in server outputs. + + - `item.input_audio_transcription.logprobs`: Include logprobs + for input audio transcription. + - type: 'null' + RealtimeSessionCreateRequest: + type: object + description: | + A new Realtime session configuration, with an ephemeral key. Default TTL + for keys is one minute. + properties: + client_secret: + type: object + description: Ephemeral key returned by the API. + properties: + value: + type: string + description: > + Ephemeral key usable in client environments to authenticate + connections + + to the Realtime API. Use this in client-side environments rather + than + + a standard API token, which should only be used server-side. + expires_at: + type: integer + description: > + Timestamp for when the token expires. Currently, all tokens + expire + + after one minute. + required: + - value + - expires_at + modalities: + description: | + The set of modalities the model can respond with. To disable audio, + set this to ["text"]. + items: + type: string + enum: + - text + - audio + instructions: + type: string + description: > + The default system instructions (i.e. system message) prepended to + model calls. This field allows the client to guide the model on + desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are + examples of good responses") and on audio behavior (e.g. "talk + quickly", "inject emotion into your voice", "laugh frequently"). The + instructions are not guaranteed to be followed by the model, but + they provide guidance to the model on the desired behavior. + + Note that the server sets default instructions which will be used if + this field is not set and are visible in the `session.created` event + at the start of the session. + voice: + $ref: '#/components/schemas/VoiceIdsOrCustomVoice' + description: > + The voice the model uses to respond. Supported built-in voices are + + `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, `shimmer`, + `verse`, + + `marin`, and `cedar`. You may also provide a custom voice object + with an + + `id`, for example `{ "id": "voice_1234" }`. Voice cannot be changed + during + + the session once the model has responded with audio at least once. + input_audio_format: + type: string + description: > + The format of input audio. Options are `pcm16`, `g711_ulaw`, or + `g711_alaw`. + output_audio_format: + type: string + description: > + The format of output audio. Options are `pcm16`, `g711_ulaw`, or + `g711_alaw`. + input_audio_transcription: + type: object + description: > + Configuration for input audio transcription, defaults to off and can + be + + set to `null` to turn off once on. Input audio transcription is not + native + + to the model, since the model consumes audio directly. Transcription + runs + + asynchronously and should be treated as rough guidance + + rather than the representation understood by the model. + properties: + model: + type: string + description: | + The model to use for transcription. + speed: + type: number + default: 1 + maximum: 1.5 + minimum: 0.25 + description: > + The speed of the model's spoken response. 1.0 is the default speed. + 0.25 is + + the minimum speed. 1.5 is the maximum speed. This value can only be + changed + + in between model turns, not while a response is in progress. + tracing: + title: Tracing Configuration + description: > + Configuration options for tracing. Set to null to disable tracing. + Once + + tracing is enabled for a session, the configuration cannot be + modified. + + + `auto` will create a trace for the session with default values for + the + + workflow name, group id, and metadata. + oneOf: + - type: string + default: auto + description: | + Default tracing mode for the session. + enum: + - auto + x-stainless-const: true + - type: object + title: Tracing Configuration + description: | + Granular configuration for tracing. + properties: + workflow_name: + type: string + description: > + The name of the workflow to attach to this trace. This is + used to + + name the trace in the traces dashboard. + group_id: + type: string + description: | + The group id to attach to this trace to enable filtering and + grouping in the traces dashboard. + metadata: + type: object + description: | + The arbitrary metadata to attach to this trace to enable + filtering in the traces dashboard. + turn_detection: + type: object + description: > + Configuration for turn detection. Can be set to `null` to turn off. + Server + + VAD means that the model will detect the start and end of speech + based on + + audio volume and respond at the end of user speech. + properties: + type: + type: string + description: > + Type of turn detection, only `server_vad` is currently + supported. + threshold: + type: number + description: > + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + A + + higher threshold will require louder audio to activate the + model, and + + thus might perform better in noisy environments. + prefix_padding_ms: + type: integer + description: | + Amount of audio to include before the VAD detected speech (in + milliseconds). Defaults to 300ms. + silence_duration_ms: + type: integer + description: > + Duration of silence to detect speech stop (in milliseconds). + Defaults + + to 500ms. With shorter values the model will respond more + quickly, + + but may jump in on short pauses from the user. + tools: + type: array + description: Tools (functions) available to the model. + items: + type: object + properties: + type: + type: string + enum: + - function + description: The type of the tool, i.e. `function`. + x-stainless-const: true + name: + type: string + description: The name of the function. + description: + type: string + description: > + The description of the function, including guidance on when + and how + + to call it, and guidance about what to tell the user when + calling + + (if anything). + parameters: + type: object + description: Parameters of the function in JSON Schema. + tool_choice: + type: string + description: > + How the model chooses tools. Options are `auto`, `none`, `required`, + or + + specify a function. + temperature: + type: number + description: > + Sampling temperature for the model, limited to [0.6, 1.2]. Defaults + to 0.8. + max_response_output_tokens: + oneOf: + - type: integer + - type: string + enum: + - inf + x-stainless-const: true + description: | + Maximum number of output tokens for a single assistant response, + inclusive of tool calls. Provide an integer between 1 and 4096 to + limit output tokens, or `inf` for the maximum available tokens for a + given model. Defaults to `inf`. + truncation: + $ref: '#/components/schemas/RealtimeTruncation' + prompt: + $ref: '#/components/schemas/Prompt' + required: + - client_secret + x-oaiMeta: + name: The session object + group: realtime + example: | + { + "id": "sess_001", + "object": "realtime.session", + "model": "gpt-realtime-2025-08-25", + "modalities": ["audio", "text"], + "instructions": "You are a friendly assistant.", + "voice": "alloy", + "input_audio_format": "pcm16", + "output_audio_format": "pcm16", + "input_audio_transcription": { + "model": "whisper-1" + }, + "turn_detection": null, + "tools": [], + "tool_choice": "none", + "temperature": 0.7, + "speed": 1.1, + "tracing": "auto", + "max_response_output_tokens": 200, + "truncation": "auto", + "prompt": null, + "client_secret": { + "value": "ek_abc123", + "expires_at": 1234567890 + } + } + RealtimeSessionCreateRequestGA: + type: object + title: Realtime session configuration + description: Realtime session object configuration. + properties: + type: + type: string + description: > + The type of session to create. Always `realtime` for the Realtime + API. + enum: + - realtime + x-stainless-const: true + output_modalities: + type: array + description: > + The set of modalities the model can respond with. It defaults to + `["audio"]`, indicating + + that the model will respond with audio plus a transcript. `["text"]` + can be used to make + + the model respond with text only. It is not possible to request both + `text` and `audio` at the same time. + default: + - audio + items: + type: string + enum: + - text + - audio + model: + anyOf: + - type: string + - type: string + enum: + - gpt-realtime + - gpt-realtime-1.5 + - gpt-realtime-2025-08-28 + - gpt-4o-realtime-preview + - gpt-4o-realtime-preview-2024-10-01 + - gpt-4o-realtime-preview-2024-12-17 + - gpt-4o-realtime-preview-2025-06-03 + - gpt-4o-mini-realtime-preview + - gpt-4o-mini-realtime-preview-2024-12-17 + - gpt-realtime-mini + - gpt-realtime-mini-2025-10-06 + - gpt-realtime-mini-2025-12-15 + - gpt-audio-1.5 + - gpt-audio-mini + - gpt-audio-mini-2025-10-06 + - gpt-audio-mini-2025-12-15 + description: | + The Realtime model used for this session. + instructions: + type: string + description: > + The default system instructions (i.e. system message) prepended to + model calls. This field allows the client to guide the model on + desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are + examples of good responses") and on audio behavior (e.g. "talk + quickly", "inject emotion into your voice", "laugh frequently"). The + instructions are not guaranteed to be followed by the model, but + they provide guidance to the model on the desired behavior. + + + Note that the server sets default instructions which will be used if + this field is not set and are visible in the `session.created` event + at the start of the session. + audio: + type: object + description: | + Configuration for input and output audio. + properties: + input: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + description: The format of the input audio. + transcription: + description: > + Configuration for input audio transcription, defaults to off + and can be set to `null` to turn off once on. Input audio + transcription is not native to the model, since the model + consumes audio directly. Transcription runs asynchronously + through [the /audio/transcriptions + endpoint](/docs/api-reference/audio/createTranscription) and + should be treated as guidance of input audio content rather + than precisely what the model heard. The client can + optionally set the language and prompt for transcription, + these offer additional guidance to the transcription + service. + $ref: '#/components/schemas/AudioTranscription' + noise_reduction: + type: object + default: null + description: > + Configuration for input audio noise reduction. This can be + set to `null` to turn off. + + Noise reduction filters audio added to the input audio + buffer before it is sent to VAD and the model. + + Filtering the audio can improve VAD and turn detection + accuracy (reducing false positives) and model performance by + improving perception of the input audio. + properties: + type: + $ref: '#/components/schemas/NoiseReductionType' + turn_detection: + $ref: '#/components/schemas/RealtimeTurnDetection' + output: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + description: The format of the output audio. + voice: + $ref: '#/components/schemas/VoiceIdsOrCustomVoice' + default: alloy + description: > + The voice the model uses to respond. Supported built-in + voices are + + `alloy`, `ash`, `ballad`, `coral`, `echo`, `sage`, + `shimmer`, `verse`, + + `marin`, and `cedar`. You may also provide a custom voice + object with + + an `id`, for example `{ "id": "voice_1234" }`. Voice cannot + be changed + + during the session once the model has responded with audio + at least once. + + We recommend `marin` and `cedar` for best quality. + speed: + type: number + default: 1 + maximum: 1.5 + minimum: 0.25 + description: > + The speed of the model's spoken response as a multiple of + the original speed. + + 1.0 is the default speed. 0.25 is the minimum speed. 1.5 is + the maximum speed. This value can only be changed in between + model turns, not while a response is in progress. + + + This parameter is a post-processing adjustment to the audio + after it is generated, it's + + also possible to prompt the model to speak faster or slower. + include: + type: array + items: + type: string + enum: + - item.input_audio_transcription.logprobs + description: > + Additional fields to include in server outputs. + + + `item.input_audio_transcription.logprobs`: Include logprobs for + input audio transcription. + tracing: + title: Tracing Configuration + default: null + description: > + Realtime API can write session traces to the [Traces + Dashboard](https://platform.openai.com/logs?api=traces). Set to null + to disable tracing. Once + + tracing is enabled for a session, the configuration cannot be + modified. + + + `auto` will create a trace for the session with default values for + the + + workflow name, group id, and metadata. + nullable: true + oneOf: + - type: string + title: auto + default: auto + description: > + Enables tracing and sets default values for tracing + configuration options. Always `auto`. + enum: + - auto + x-stainless-const: true + - type: object + title: Tracing Configuration + description: | + Granular configuration for tracing. + properties: + workflow_name: + type: string + description: > + The name of the workflow to attach to this trace. This is + used to + + name the trace in the Traces Dashboard. + group_id: + type: string + description: | + The group id to attach to this trace to enable filtering and + grouping in the Traces Dashboard. + metadata: + type: object + description: | + The arbitrary metadata to attach to this trace to enable + filtering in the Traces Dashboard. + tools: + type: array + description: Tools available to the model. + items: + oneOf: + - $ref: '#/components/schemas/RealtimeFunctionTool' + - $ref: '#/components/schemas/MCPTool' + tool_choice: + description: > + How the model chooses tools. Provide one of the string modes or + force a specific + + function/MCP tool. + oneOf: + - $ref: '#/components/schemas/ToolChoiceOptions' + - $ref: '#/components/schemas/ToolChoiceFunction' + - $ref: '#/components/schemas/ToolChoiceMCP' + default: auto + max_output_tokens: + oneOf: + - type: integer + - type: string + enum: + - inf + x-stainless-const: true + description: | + Maximum number of output tokens for a single assistant response, + inclusive of tool calls. Provide an integer between 1 and 4096 to + limit output tokens, or `inf` for the maximum available tokens for a + given model. Defaults to `inf`. + truncation: + $ref: '#/components/schemas/RealtimeTruncation' + prompt: + $ref: '#/components/schemas/Prompt' + required: + - type + RealtimeSessionCreateResponse: + type: object + title: Realtime session configuration object + description: | + A Realtime session configuration object. + properties: + id: + type: string + description: > + Unique identifier for the session that looks like + `sess_1234567890abcdef`. + object: + type: string + description: The object type. Always `realtime.session`. + expires_at: + type: integer + description: Expiration timestamp for the session, in seconds since epoch. + include: + type: array + items: + type: string + enum: + - item.input_audio_transcription.logprobs + description: > + Additional fields to include in server outputs. + + - `item.input_audio_transcription.logprobs`: Include logprobs for + input audio transcription. + model: + type: string + description: The Realtime model used for this session. + output_modalities: + description: | + The set of modalities the model can respond with. To disable audio, + set this to ["text"]. + items: + type: string + enum: + - text + - audio + instructions: + type: string + description: > + The default system instructions (i.e. system message) prepended to + model + + calls. This field allows the client to guide the model on desired + + responses. The model can be instructed on response content and + format, + + (e.g. "be extremely succinct", "act friendly", "here are examples of + good + + responses") and on audio behavior (e.g. "talk quickly", "inject + emotion + + into your voice", "laugh frequently"). The instructions are not + guaranteed + + to be followed by the model, but they provide guidance to the model + on the + + desired behavior. + + + Note that the server sets default instructions which will be used if + this + + field is not set and are visible in the `session.created` event at + the + + start of the session. + audio: + type: object + description: | + Configuration for input and output audio for the session. + properties: + input: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + transcription: + description: | + Configuration for input audio transcription. + $ref: '#/components/schemas/AudioTranscription' + noise_reduction: + type: object + description: | + Configuration for input audio noise reduction. + properties: + type: + $ref: '#/components/schemas/NoiseReductionType' + turn_detection: + type: object + description: | + Configuration for turn detection. + properties: + type: + type: string + description: > + Type of turn detection, only `server_vad` is currently + supported. + threshold: + type: number + prefix_padding_ms: + type: integer + silence_duration_ms: + type: integer + output: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + voice: + $ref: '#/components/schemas/VoiceIdsShared' + speed: + type: number + tracing: + title: Tracing Configuration + description: > + Configuration options for tracing. Set to null to disable tracing. + Once + + tracing is enabled for a session, the configuration cannot be + modified. + + + `auto` will create a trace for the session with default values for + the + + workflow name, group id, and metadata. + oneOf: + - type: string + default: auto + description: | + Default tracing mode for the session. + enum: + - auto + x-stainless-const: true + - type: object + title: Tracing Configuration + description: | + Granular configuration for tracing. + properties: + workflow_name: + type: string + description: > + The name of the workflow to attach to this trace. This is + used to + + name the trace in the traces dashboard. + group_id: + type: string + description: | + The group id to attach to this trace to enable filtering and + grouping in the traces dashboard. + metadata: + type: object + description: | + The arbitrary metadata to attach to this trace to enable + filtering in the traces dashboard. + turn_detection: + type: object + description: > + Configuration for turn detection. Can be set to `null` to turn off. + Server + + VAD means that the model will detect the start and end of speech + based on + + audio volume and respond at the end of user speech. + properties: + type: + type: string + description: > + Type of turn detection, only `server_vad` is currently + supported. + threshold: + type: number + description: > + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + A + + higher threshold will require louder audio to activate the + model, and + + thus might perform better in noisy environments. + prefix_padding_ms: + type: integer + description: | + Amount of audio to include before the VAD detected speech (in + milliseconds). Defaults to 300ms. + silence_duration_ms: + type: integer + description: > + Duration of silence to detect speech stop (in milliseconds). + Defaults + + to 500ms. With shorter values the model will respond more + quickly, + + but may jump in on short pauses from the user. + tools: + type: array + description: Tools (functions) available to the model. + items: + $ref: '#/components/schemas/RealtimeFunctionTool' + tool_choice: + type: string + description: > + How the model chooses tools. Options are `auto`, `none`, `required`, + or + + specify a function. + max_output_tokens: + oneOf: + - type: integer + - type: string + enum: + - inf + x-stainless-const: true + description: | + Maximum number of output tokens for a single assistant response, + inclusive of tool calls. Provide an integer between 1 and 4096 to + limit output tokens, or `inf` for the maximum available tokens for a + given model. Defaults to `inf`. + x-oaiMeta: + name: The session object + group: realtime + example: | + { + "id": "sess_001", + "object": "realtime.session", + "expires_at": 1742188264, + "model": "gpt-realtime", + "output_modalities": ["audio"], + "instructions": "You are a friendly assistant.", + "tools": [], + "tool_choice": "none", + "max_output_tokens": "inf", + "tracing": "auto", + "truncation": "auto", + "prompt": null, + "audio": { + "input": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "transcription": { "model": "whisper-1" }, + "noise_reduction": null, + "turn_detection": null + }, + "output": { + "format": { + "type": "audio/pcm", + "rate": 24000 + }, + "voice": "alloy", + "speed": 1.0 + } + } + } + RealtimeSessionCreateResponseGA: + type: object + description: | + A new Realtime session configuration, with an ephemeral key. Default TTL + for keys is one minute. + properties: + client_secret: + type: object + description: Ephemeral key returned by the API. + properties: + value: + type: string + description: > + Ephemeral key usable in client environments to authenticate + connections to the Realtime API. Use this in client-side + environments rather than a standard API token, which should only + be used server-side. + expires_at: + type: integer + description: > + Timestamp for when the token expires. Currently, all tokens + expire + + after one minute. + required: + - value + - expires_at + type: + type: string + description: > + The type of session to create. Always `realtime` for the Realtime + API. + enum: + - realtime + x-stainless-const: true + output_modalities: + type: array + description: > + The set of modalities the model can respond with. It defaults to + `["audio"]`, indicating + + that the model will respond with audio plus a transcript. `["text"]` + can be used to make + + the model respond with text only. It is not possible to request both + `text` and `audio` at the same time. + default: + - audio + items: + type: string + enum: + - text + - audio + model: + anyOf: + - type: string + - type: string + enum: + - gpt-realtime + - gpt-realtime-1.5 + - gpt-realtime-2025-08-28 + - gpt-4o-realtime-preview + - gpt-4o-realtime-preview-2024-10-01 + - gpt-4o-realtime-preview-2024-12-17 + - gpt-4o-realtime-preview-2025-06-03 + - gpt-4o-mini-realtime-preview + - gpt-4o-mini-realtime-preview-2024-12-17 + - gpt-realtime-mini + - gpt-realtime-mini-2025-10-06 + - gpt-realtime-mini-2025-12-15 + - gpt-audio-1.5 + - gpt-audio-mini + - gpt-audio-mini-2025-10-06 + - gpt-audio-mini-2025-12-15 + description: | + The Realtime model used for this session. + instructions: + type: string + description: > + The default system instructions (i.e. system message) prepended to + model calls. This field allows the client to guide the model on + desired responses. The model can be instructed on response content + and format, (e.g. "be extremely succinct", "act friendly", "here are + examples of good responses") and on audio behavior (e.g. "talk + quickly", "inject emotion into your voice", "laugh frequently"). The + instructions are not guaranteed to be followed by the model, but + they provide guidance to the model on the desired behavior. + + + Note that the server sets default instructions which will be used if + this field is not set and are visible in the `session.created` event + at the start of the session. + audio: + type: object + description: | + Configuration for input and output audio. + properties: + input: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + description: The format of the input audio. + transcription: + description: > + Configuration for input audio transcription, defaults to off + and can be set to `null` to turn off once on. Input audio + transcription is not native to the model, since the model + consumes audio directly. Transcription runs asynchronously + through [the /audio/transcriptions + endpoint](/docs/api-reference/audio/createTranscription) and + should be treated as guidance of input audio content rather + than precisely what the model heard. The client can + optionally set the language and prompt for transcription, + these offer additional guidance to the transcription + service. + $ref: '#/components/schemas/AudioTranscription' + noise_reduction: + type: object + default: null + description: > + Configuration for input audio noise reduction. This can be + set to `null` to turn off. + + Noise reduction filters audio added to the input audio + buffer before it is sent to VAD and the model. + + Filtering the audio can improve VAD and turn detection + accuracy (reducing false positives) and model performance by + improving perception of the input audio. + properties: + type: + $ref: '#/components/schemas/NoiseReductionType' + turn_detection: + $ref: '#/components/schemas/RealtimeTurnDetection' + output: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + description: The format of the output audio. + voice: + $ref: '#/components/schemas/VoiceIdsShared' + default: alloy + description: > + The voice the model uses to respond. Voice cannot be changed + during the + + session once the model has responded with audio at least + once. Current + + voice options are `alloy`, `ash`, `ballad`, `coral`, `echo`, + `sage`, + + `shimmer`, `verse`, `marin`, and `cedar`. We recommend + `marin` and `cedar` for + + best quality. + speed: + type: number + default: 1 + maximum: 1.5 + minimum: 0.25 + description: > + The speed of the model's spoken response as a multiple of + the original speed. + + 1.0 is the default speed. 0.25 is the minimum speed. 1.5 is + the maximum speed. This value can only be changed in between + model turns, not while a response is in progress. + + + This parameter is a post-processing adjustment to the audio + after it is generated, it's + + also possible to prompt the model to speak faster or slower. + include: + type: array + items: + type: string + enum: + - item.input_audio_transcription.logprobs + description: > + Additional fields to include in server outputs. + + + `item.input_audio_transcription.logprobs`: Include logprobs for + input audio transcription. + tracing: + anyOf: + - title: Tracing Configuration + default: null + description: > + Realtime API can write session traces to the [Traces + Dashboard](https://platform.openai.com/logs?api=traces). Set to + null to disable tracing. Once + + tracing is enabled for a session, the configuration cannot be + modified. + + + `auto` will create a trace for the session with default values + for the + + workflow name, group id, and metadata. + oneOf: + - type: string + title: auto + default: auto + description: > + Enables tracing and sets default values for tracing + configuration options. Always `auto`. + enum: + - auto + x-stainless-const: true + - type: object + title: Tracing Configuration + description: | + Granular configuration for tracing. + properties: + workflow_name: + type: string + description: > + The name of the workflow to attach to this trace. This + is used to + + name the trace in the Traces Dashboard. + group_id: + type: string + description: > + The group id to attach to this trace to enable filtering + and + + grouping in the Traces Dashboard. + metadata: + type: object + description: | + The arbitrary metadata to attach to this trace to enable + filtering in the Traces Dashboard. + - type: 'null' + tools: + type: array + description: Tools available to the model. + items: + oneOf: + - $ref: '#/components/schemas/RealtimeFunctionTool' + - $ref: '#/components/schemas/MCPTool' + tool_choice: + description: > + How the model chooses tools. Provide one of the string modes or + force a specific + + function/MCP tool. + oneOf: + - $ref: '#/components/schemas/ToolChoiceOptions' + - $ref: '#/components/schemas/ToolChoiceFunction' + - $ref: '#/components/schemas/ToolChoiceMCP' + default: auto + max_output_tokens: + oneOf: + - type: integer + - type: string + enum: + - inf + x-stainless-const: true + description: | + Maximum number of output tokens for a single assistant response, + inclusive of tool calls. Provide an integer between 1 and 4096 to + limit output tokens, or `inf` for the maximum available tokens for a + given model. Defaults to `inf`. + truncation: + $ref: '#/components/schemas/RealtimeTruncation' + prompt: + $ref: '#/components/schemas/Prompt' + required: + - client_secret + - type + x-oaiMeta: + name: The session object + group: realtime + RealtimeTranscriptionSessionCreateRequest: + type: object + title: Realtime transcription session configuration + description: Realtime transcription session object configuration. + properties: + turn_detection: + type: object + description: > + Configuration for turn detection. Can be set to `null` to turn off. + Server VAD means that the model will detect the start and end of + speech based on audio volume and respond at the end of user speech. + properties: + type: + type: string + description: > + Type of turn detection. Only `server_vad` is currently supported + for transcription sessions. + enum: + - server_vad + threshold: + type: number + description: > + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + A + + higher threshold will require louder audio to activate the + model, and + + thus might perform better in noisy environments. + prefix_padding_ms: + type: integer + description: | + Amount of audio to include before the VAD detected speech (in + milliseconds). Defaults to 300ms. + silence_duration_ms: + type: integer + description: > + Duration of silence to detect speech stop (in milliseconds). + Defaults + + to 500ms. With shorter values the model will respond more + quickly, + + but may jump in on short pauses from the user. + input_audio_noise_reduction: + type: object + default: null + description: > + Configuration for input audio noise reduction. This can be set to + `null` to turn off. + + Noise reduction filters audio added to the input audio buffer before + it is sent to VAD and the model. + + Filtering the audio can improve VAD and turn detection accuracy + (reducing false positives) and model performance by improving + perception of the input audio. + properties: + type: + $ref: '#/components/schemas/NoiseReductionType' + input_audio_format: + type: string + default: pcm16 + enum: + - pcm16 + - g711_ulaw + - g711_alaw + description: > + The format of input audio. Options are `pcm16`, `g711_ulaw`, or + `g711_alaw`. + + For `pcm16`, input audio must be 16-bit PCM at a 24kHz sample rate, + + single channel (mono), and little-endian byte order. + input_audio_transcription: + description: > + Configuration for input audio transcription. The client can + optionally set the language and prompt for transcription, these + offer additional guidance to the transcription service. + $ref: '#/components/schemas/AudioTranscription' + include: + type: array + items: + type: string + enum: + - item.input_audio_transcription.logprobs + description: > + The set of items to include in the transcription. Current available + items are: + + `item.input_audio_transcription.logprobs` + RealtimeTranscriptionSessionCreateRequestGA: + type: object + title: Realtime transcription session configuration + description: Realtime transcription session object configuration. + properties: + type: + type: string + description: > + The type of session to create. Always `transcription` for + transcription sessions. + enum: + - transcription + x-stainless-const: true + audio: + type: object + description: | + Configuration for input and output audio. + properties: + input: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + transcription: + description: > + Configuration for input audio transcription, defaults to off + and can be set to `null` to turn off once on. Input audio + transcription is not native to the model, since the model + consumes audio directly. Transcription runs asynchronously + through [the /audio/transcriptions + endpoint](/docs/api-reference/audio/createTranscription) and + should be treated as guidance of input audio content rather + than precisely what the model heard. The client can + optionally set the language and prompt for transcription, + these offer additional guidance to the transcription + service. + $ref: '#/components/schemas/AudioTranscription' + noise_reduction: + type: object + default: null + description: > + Configuration for input audio noise reduction. This can be + set to `null` to turn off. + + Noise reduction filters audio added to the input audio + buffer before it is sent to VAD and the model. + + Filtering the audio can improve VAD and turn detection + accuracy (reducing false positives) and model performance by + improving perception of the input audio. + properties: + type: + $ref: '#/components/schemas/NoiseReductionType' + turn_detection: + $ref: '#/components/schemas/RealtimeTurnDetection' + include: + type: array + items: + type: string + enum: + - item.input_audio_transcription.logprobs + description: > + Additional fields to include in server outputs. + + + `item.input_audio_transcription.logprobs`: Include logprobs for + input audio transcription. + required: + - type + RealtimeTranscriptionSessionCreateResponse: + type: object + description: | + A new Realtime transcription session configuration. + + When a session is created on the server via REST API, the session object + also contains an ephemeral key. Default TTL for keys is 10 minutes. This + property is not present when a session is updated via the WebSocket API. + properties: + client_secret: + type: object + description: | + Ephemeral key returned by the API. Only present when the session is + created on the server via REST API. + properties: + value: + type: string + description: > + Ephemeral key usable in client environments to authenticate + connections + + to the Realtime API. Use this in client-side environments rather + than + + a standard API token, which should only be used server-side. + expires_at: + type: integer + description: > + Timestamp for when the token expires. Currently, all tokens + expire + + after one minute. + required: + - value + - expires_at + modalities: + description: | + The set of modalities the model can respond with. To disable audio, + set this to ["text"]. + items: + type: string + enum: + - text + - audio + input_audio_format: + type: string + description: > + The format of input audio. Options are `pcm16`, `g711_ulaw`, or + `g711_alaw`. + input_audio_transcription: + description: | + Configuration of the transcription model. + $ref: '#/components/schemas/AudioTranscription' + turn_detection: + type: object + description: > + Configuration for turn detection. Can be set to `null` to turn off. + Server + + VAD means that the model will detect the start and end of speech + based on + + audio volume and respond at the end of user speech. + properties: + type: + type: string + description: > + Type of turn detection, only `server_vad` is currently + supported. + threshold: + type: number + description: > + Activation threshold for VAD (0.0 to 1.0), this defaults to 0.5. + A + + higher threshold will require louder audio to activate the + model, and + + thus might perform better in noisy environments. + prefix_padding_ms: + type: integer + description: | + Amount of audio to include before the VAD detected speech (in + milliseconds). Defaults to 300ms. + silence_duration_ms: + type: integer + description: > + Duration of silence to detect speech stop (in milliseconds). + Defaults + + to 500ms. With shorter values the model will respond more + quickly, + + but may jump in on short pauses from the user. + required: + - client_secret + x-oaiMeta: + name: The transcription session object + group: realtime + example: | + { + "id": "sess_BBwZc7cFV3XizEyKGDCGL", + "object": "realtime.transcription_session", + "expires_at": 1742188264, + "modalities": ["audio", "text"], + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 200 + }, + "input_audio_format": "pcm16", + "input_audio_transcription": { + "model": "gpt-4o-transcribe", + "language": null, + "prompt": "" + }, + "client_secret": null + } + RealtimeTranscriptionSessionCreateResponseGA: + type: object + title: Realtime transcription session configuration object + description: | + A Realtime transcription session configuration object. + properties: + type: + type: string + description: > + The type of session. Always `transcription` for transcription + sessions. + enum: + - transcription + x-stainless-const: true + id: + type: string + description: > + Unique identifier for the session that looks like + `sess_1234567890abcdef`. + object: + type: string + description: The object type. Always `realtime.transcription_session`. + expires_at: + type: integer + description: Expiration timestamp for the session, in seconds since epoch. + include: + type: array + items: + type: string + enum: + - item.input_audio_transcription.logprobs + description: > + Additional fields to include in server outputs. + + - `item.input_audio_transcription.logprobs`: Include logprobs for + input audio transcription. + audio: + type: object + description: | + Configuration for input audio for the session. + properties: + input: + type: object + properties: + format: + $ref: '#/components/schemas/RealtimeAudioFormats' + transcription: + description: | + Configuration of the transcription model. + $ref: '#/components/schemas/AudioTranscription' + noise_reduction: + type: object + description: | + Configuration for input audio noise reduction. + properties: + type: + $ref: '#/components/schemas/NoiseReductionType' + turn_detection: + type: object + description: > + Configuration for turn detection. Can be set to `null` to + turn off. Server + + VAD means that the model will detect the start and end of + speech based on + + audio volume and respond at the end of user speech. + properties: + type: + type: string + description: > + Type of turn detection, only `server_vad` is currently + supported. + threshold: + type: number + description: > + Activation threshold for VAD (0.0 to 1.0), this defaults + to 0.5. A + + higher threshold will require louder audio to activate + the model, and + + thus might perform better in noisy environments. + prefix_padding_ms: + type: integer + description: > + Amount of audio to include before the VAD detected + speech (in + + milliseconds). Defaults to 300ms. + silence_duration_ms: + type: integer + description: > + Duration of silence to detect speech stop (in + milliseconds). Defaults + + to 500ms. With shorter values the model will respond + more quickly, + + but may jump in on short pauses from the user. + required: + - type + - id + - object + x-oaiMeta: + name: The transcription session object + group: realtime + example: | + { + "id": "sess_BBwZc7cFV3XizEyKGDCGL", + "type": "transcription", + "object": "realtime.transcription_session", + "expires_at": 1742188264, + "include": ["item.input_audio_transcription.logprobs"], + "audio": { + "input": { + "format": "pcm16", + "transcription": { + "model": "gpt-4o-transcribe", + "language": null, + "prompt": "" + }, + "noise_reduction": null, + "turn_detection": { + "type": "server_vad", + "threshold": 0.5, + "prefix_padding_ms": 300, + "silence_duration_ms": 200 + } + } + } + } + RealtimeTruncation: + title: Realtime Truncation Controls + description: > + When the number of tokens in a conversation exceeds the model's input + token limit, the conversation be truncated, meaning messages (starting + from the oldest) will not be included in the model's context. A 32k + context model with 4,096 max output tokens can only include 28,224 + tokens in the context before truncation occurs. + + + Clients can configure truncation behavior to truncate with a lower max + token limit, which is an effective way to control token usage and cost. + + + Truncation will reduce the number of cached tokens on the next turn + (busting the cache), since messages are dropped from the beginning of + the context. However, clients can also configure truncation to retain + messages up to a fraction of the maximum context size, which will reduce + the need for future truncations and thus improve the cache rate. + + + Truncation can be disabled entirely, which means the server will never + truncate but would instead return an error if the conversation exceeds + the model's input token limit. + oneOf: + - type: string + description: >- + The truncation strategy to use for the session. `auto` is the + default truncation strategy. `disabled` will disable truncation and + emit errors when the conversation exceeds the input token limit. + enum: + - auto + - disabled + - type: object + title: Retention ratio truncation + description: >- + Retain a fraction of the conversation tokens when the conversation + exceeds the input token limit. This allows you to amortize + truncations across multiple turns, which can help improve cached + token usage. + properties: + type: + type: string + enum: + - retention_ratio + description: Use retention ratio truncation. + x-stainless-const: true + retention_ratio: + type: number + description: > + Fraction of post-instruction conversation tokens to retain + (`0.0` - `1.0`) when the conversation exceeds the input token + limit. Setting this to `0.8` means that messages will be dropped + until 80% of the maximum allowed tokens are used. This helps + reduce the frequency of truncations and improve cache rates. + minimum: 0 + maximum: 1 + token_limits: + type: object + description: >- + Optional custom token limits for this truncation strategy. If + not provided, the model's default token limits will be used. + properties: + post_instructions: + type: integer + description: >- + Maximum tokens allowed in the conversation after + instructions (which including tool definitions). For + example, setting this to 5,000 would mean that truncation + would occur when the conversation exceeds 5,000 tokens after + instructions. This cannot be higher than the model's context + window size minus the maximum output tokens. + minimum: 0 + required: + - type + - retention_ratio + RealtimeTurnDetection: + anyOf: + - title: Realtime Turn Detection + description: > + Configuration for turn detection, ether Server VAD or Semantic VAD. + This can be set to `null` to turn off, in which case the client must + manually trigger model response. + + + Server VAD means that the model will detect the start and end of + speech based on audio volume and respond at the end of user speech. + + + Semantic VAD is more advanced and uses a turn detection model (in + conjunction with VAD) to semantically estimate whether the user has + finished speaking, then dynamically sets a timeout based on this + probability. For example, if user audio trails off with "uhhm", the + model will score a low probability of turn end and wait longer for + the user to continue speaking. This can be useful for more natural + conversations, but may have a higher latency. + oneOf: + - type: object + title: Server VAD + description: >- + Server-side voice activity detection (VAD) which flips on when + user speech is detected and off after a period of silence. + required: + - type + properties: + type: + type: string + default: server_vad + const: server_vad + description: > + Type of turn detection, `server_vad` to turn on simple + Server VAD. + threshold: + type: number + description: > + Used only for `server_vad` mode. Activation threshold for + VAD (0.0 to 1.0), this defaults to 0.5. A + + higher threshold will require louder audio to activate the + model, and + + thus might perform better in noisy environments. + prefix_padding_ms: + type: integer + description: > + Used only for `server_vad` mode. Amount of audio to include + before the VAD detected speech (in + + milliseconds). Defaults to 300ms. + silence_duration_ms: + type: integer + description: > + Used only for `server_vad` mode. Duration of silence to + detect speech stop (in milliseconds). Defaults + + to 500ms. With shorter values the model will respond more + quickly, + + but may jump in on short pauses from the user. + create_response: + type: boolean + default: true + description: > + Whether or not to automatically generate a response when a + VAD stop event occurs. If `interrupt_response` is set to + `false` this may fail to create a response if the model is + already responding. + + + If both `create_response` and `interrupt_response` are set + to `false`, the model will never respond automatically but + VAD events will still be emitted. + interrupt_response: + type: boolean + default: true + description: > + Whether or not to automatically interrupt (cancel) any + ongoing response with output to the default + + conversation (i.e. `conversation` of `auto`) when a VAD + start event occurs. If `true` then the response will be + cancelled, otherwise it will continue until complete. + + + If both `create_response` and `interrupt_response` are set + to `false`, the model will never respond automatically but + VAD events will still be emitted. + idle_timeout_ms: + anyOf: + - type: integer + minimum: 5000 + maximum: 30000 + description: > + Optional timeout after which a model response will be + triggered automatically. This is + + useful for situations in which a long pause from the + user is unexpected, such as a phone + + call. The model will effectively prompt the user to + continue the conversation based + + on the current context. + + + The timeout value will be applied after the last model + response's audio has finished playing, + + i.e. it's set to the `response.done` time plus audio + playback duration. + + + An `input_audio_buffer.timeout_triggered` event (plus + events + + associated with the Response) will be emitted when the + timeout is reached. + + Idle timeout is currently only supported for + `server_vad` mode. + - type: 'null' + - type: object + title: Semantic VAD + description: >- + Server-side semantic turn detection which uses a model to + determine when the user has finished speaking. + required: + - type + properties: + type: + type: string + const: semantic_vad + description: > + Type of turn detection, `semantic_vad` to turn on Semantic + VAD. + eagerness: + type: string + default: auto + enum: + - low + - medium + - high + - auto + description: > + Used only for `semantic_vad` mode. The eagerness of the + model to respond. `low` will wait longer for the user to + continue speaking, `high` will respond more quickly. `auto` + is the default and is equivalent to `medium`. `low`, + `medium`, and `high` have max timeouts of 8s, 4s, and 2s + respectively. + create_response: + type: boolean + default: true + description: > + Whether or not to automatically generate a response when a + VAD stop event occurs. + interrupt_response: + type: boolean + default: true + description: > + Whether or not to automatically interrupt any ongoing + response with output to the default + + conversation (i.e. `conversation` of `auto`) when a VAD + start event occurs. + discriminator: + propertyName: type + - type: 'null' + Reasoning: + type: object + description: | + **gpt-5 and o-series models only** + + Configuration options for + [reasoning models](https://platform.openai.com/docs/guides/reasoning). + title: Reasoning + properties: + effort: + $ref: '#/components/schemas/ReasoningEffort' + summary: + anyOf: + - type: string + description: > + 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`. + enum: + - auto + - concise + - detailed + - type: 'null' + generate_summary: + anyOf: + - type: string + deprecated: true + description: > + **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`. + enum: + - auto + - concise + - detailed + - type: 'null' + ReasoningEffort: + anyOf: + - type: string + enum: + - none + - minimal + - low + - medium + - high + - xhigh + default: medium + description: > + Constrains effort on reasoning for + + [reasoning + models](https://platform.openai.com/docs/guides/reasoning). + + Currently supported values are `none`, `minimal`, `low`, `medium`, + `high`, and `xhigh`. Reducing + + reasoning effort can result in faster responses and fewer tokens + used + + on reasoning in a response. + + + - `gpt-5.1` defaults to `none`, which does not perform reasoning. + The supported reasoning values for `gpt-5.1` are `none`, `low`, + `medium`, and `high`. Tool calls are supported for all reasoning + values in gpt-5.1. + + - All models before `gpt-5.1` default to `medium` reasoning effort, + and do not support `none`. + + - The `gpt-5-pro` model defaults to (and only supports) `high` + reasoning effort. + + - `xhigh` is supported for all models after `gpt-5.1-codex-max`. + - type: 'null' + ReasoningItem: + type: object + description: > + A description of the chain of thought used by a reasoning model while + generating + + a response. Be sure to include these items in your `input` to the + Responses API + + for subsequent turns of a conversation if you are manually + + [managing context](/docs/guides/conversation-state). + title: Reasoning + properties: + type: + type: string + description: | + The type of the object. Always `reasoning`. + enum: + - reasoning + x-stainless-const: true + id: + type: string + description: | + The unique identifier of the reasoning content. + encrypted_content: + anyOf: + - type: string + description: > + The encrypted content of the reasoning item - populated when a + response is + + generated with `reasoning.encrypted_content` in the `include` + parameter. + - type: 'null' + summary: + type: array + description: | + Reasoning summary content. + items: + $ref: '#/components/schemas/SummaryTextContent' + content: + type: array + description: | + Reasoning text content. + items: + $ref: '#/components/schemas/ReasoningTextContent' + status: + type: string + description: | + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + enum: + - in_progress + - completed + - incomplete + required: + - id + - summary + - type + Response: + title: The response object + allOf: + - $ref: '#/components/schemas/ModelResponseProperties' + - $ref: '#/components/schemas/ResponseProperties' + - type: object + properties: + id: + type: string + description: | + Unique identifier for this Response. + object: + type: string + description: | + The object type of this resource - always set to `response`. + enum: + - response + x-stainless-const: true + status: + type: string + description: > + The status of the response generation. One of `completed`, + `failed`, + + `in_progress`, `cancelled`, `queued`, or `incomplete`. + enum: + - completed + - failed + - in_progress + - cancelled + - queued + - incomplete + created_at: + type: number + description: | + Unix timestamp (in seconds) of when this Response was created. + completed_at: + anyOf: + - type: number + description: > + Unix timestamp (in seconds) of when this Response was + completed. + + Only present when the status is `completed`. + - type: 'null' + error: + $ref: '#/components/schemas/ResponseError' + incomplete_details: + anyOf: + - type: object + description: | + Details about why the response is incomplete. + properties: + reason: + type: string + description: The reason why the response is incomplete. + enum: + - max_output_tokens + - content_filter + - type: 'null' + output: + type: array + description: > + An array of content items generated by the model. + + + - The length and order of items in the `output` array is + dependent + on the model's response. + - Rather than accessing the first item in the `output` array and + assuming it's an `assistant` message with the content generated by + the model, you might consider using the `output_text` property where + supported in SDKs. + items: + $ref: '#/components/schemas/OutputItem' + instructions: + anyOf: + - description: > + 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. + oneOf: + - type: string + description: > + A text input to the model, equivalent to a text input + with the + + `developer` role. + - type: array + title: Input item list + description: > + A list of one or many input items to the model, + containing + + different content types. + items: + $ref: '#/components/schemas/InputItem' + - type: 'null' + output_text: + anyOf: + - type: string + description: > + 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. + x-oaiSupportedSDKs: + - python + - javascript + - type: 'null' + usage: + $ref: '#/components/schemas/ResponseUsage' + parallel_tool_calls: + type: boolean + description: | + Whether to allow the model to run tool calls in parallel. + default: true + conversation: + anyOf: + - default: null + $ref: '#/components/schemas/Conversation-2' + - type: 'null' + max_output_tokens: + anyOf: + - description: > + An upper bound for the number of tokens that can be + generated for a response, including visible output tokens + and [reasoning tokens](/docs/guides/reasoning). + type: integer + - type: 'null' + required: + - id + - object + - created_at + - error + - incomplete_details + - instructions + - model + - tools + - output + - parallel_tool_calls + - metadata + - tool_choice + - temperature + - top_p + example: + id: resp_67ccd3a9da748190baa7f1570fe91ac604becb25c45c1d41 + object: response + created_at: 1741476777 + status: completed + completed_at: 1741476778 + error: null + incomplete_details: null + instructions: null + max_output_tokens: null + model: gpt-4o-2024-08-06 + output: + - type: message + id: msg_67ccd3acc8d48190a77525dc6de64b4104becb25c45c1d41 + status: completed + role: assistant + content: + - type: output_text + text: >- + The image depicts a scenic landscape with a wooden boardwalk + or pathway leading through lush, green grass under a blue sky + with some clouds. The setting suggests a peaceful natural + area, possibly a park or nature reserve. There are trees and + shrubs in the background. + annotations: [] + parallel_tool_calls: true + previous_response_id: null + reasoning: + effort: null + summary: null + store: true + temperature: 1 + text: + format: + type: text + tool_choice: auto + tools: [] + top_p: 1 + truncation: disabled + usage: + input_tokens: 328 + input_tokens_details: + cached_tokens: 0 + output_tokens: 52 + output_tokens_details: + reasoning_tokens: 0 + total_tokens: 380 + user: null + metadata: {} + ResponseAudioDeltaEvent: + type: object + description: Emitted when there is a partial audio response. + properties: + type: + type: string + description: | + The type of the event. Always `response.audio.delta`. + enum: + - response.audio.delta + x-stainless-const: true + sequence_number: + type: integer + description: | + A sequence number for this chunk of the stream response. + delta: + type: string + description: | + A chunk of Base64 encoded response audio bytes. + required: + - type + - delta + - sequence_number + x-oaiMeta: + name: response.audio.delta + group: responses + example: | + { + "type": "response.audio.delta", + "response_id": "resp_123", + "delta": "base64encoded...", + "sequence_number": 1 + } + ResponseAudioDoneEvent: + type: object + description: Emitted when the audio response is complete. + properties: + type: + type: string + description: | + The type of the event. Always `response.audio.done`. + enum: + - response.audio.done + x-stainless-const: true + response_id: + type: string + description: | + The ID of the response. + sequence_number: + type: integer + description: | + The sequence number of the delta. + required: + - type + - sequence_number + - response_id + x-oaiMeta: + name: response.audio.done + group: responses + example: | + { + "type": "response.audio.done", + "response_id": "resp-123", + "sequence_number": 1 + } + ResponseAudioTranscriptDeltaEvent: + type: object + description: Emitted when there is a partial transcript of audio. + properties: + type: + type: string + description: | + The type of the event. Always `response.audio.transcript.delta`. + enum: + - response.audio.transcript.delta + x-stainless-const: true + response_id: + type: string + description: | + The ID of the response. + delta: + type: string + description: | + The partial transcript of the audio response. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - response_id + - delta + - sequence_number + x-oaiMeta: + name: response.audio.transcript.delta + group: responses + example: | + { + "type": "response.audio.transcript.delta", + "response_id": "resp_123", + "delta": " ... partial transcript ... ", + "sequence_number": 1 + } + ResponseAudioTranscriptDoneEvent: + type: object + description: Emitted when the full audio transcript is completed. + properties: + type: + type: string + description: | + The type of the event. Always `response.audio.transcript.done`. + enum: + - response.audio.transcript.done + x-stainless-const: true + response_id: + type: string + description: | + The ID of the response. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - response_id + - sequence_number + x-oaiMeta: + name: response.audio.transcript.done + group: responses + example: | + { + "type": "response.audio.transcript.done", + "response_id": "resp_123", + "sequence_number": 1 + } + ResponseCodeInterpreterCallCodeDeltaEvent: + type: object + description: Emitted when a partial code snippet is streamed by the code interpreter. + properties: + type: + type: string + description: >- + The type of the event. Always + `response.code_interpreter_call_code.delta`. + enum: + - response.code_interpreter_call_code.delta + x-stainless-const: true + output_index: + type: integer + description: >- + The index of the output item in the response for which the code is + being streamed. + item_id: + type: string + description: The unique identifier of the code interpreter tool call item. + delta: + type: string + description: The partial code snippet being streamed by the code interpreter. + sequence_number: + type: integer + description: The sequence number of this event, used to order streaming events. + required: + - type + - output_index + - item_id + - delta + - sequence_number + x-oaiMeta: + name: response.code_interpreter_call_code.delta + group: responses + example: | + { + "type": "response.code_interpreter_call_code.delta", + "output_index": 0, + "item_id": "ci_12345", + "delta": "print('Hello, world')", + "sequence_number": 1 + } + ResponseCodeInterpreterCallCodeDoneEvent: + type: object + description: Emitted when the code snippet is finalized by the code interpreter. + properties: + type: + type: string + description: >- + The type of the event. Always + `response.code_interpreter_call_code.done`. + enum: + - response.code_interpreter_call_code.done + x-stainless-const: true + output_index: + type: integer + description: >- + The index of the output item in the response for which the code is + finalized. + item_id: + type: string + description: The unique identifier of the code interpreter tool call item. + code: + type: string + description: The final code snippet output by the code interpreter. + sequence_number: + type: integer + description: The sequence number of this event, used to order streaming events. + required: + - type + - output_index + - item_id + - code + - sequence_number + x-oaiMeta: + name: response.code_interpreter_call_code.done + group: responses + example: | + { + "type": "response.code_interpreter_call_code.done", + "output_index": 3, + "item_id": "ci_12345", + "code": "print('done')", + "sequence_number": 1 + } + ResponseCodeInterpreterCallCompletedEvent: + type: object + description: Emitted when the code interpreter call is completed. + properties: + type: + type: string + description: >- + The type of the event. Always + `response.code_interpreter_call.completed`. + enum: + - response.code_interpreter_call.completed + x-stainless-const: true + output_index: + type: integer + description: >- + The index of the output item in the response for which the code + interpreter call is completed. + item_id: + type: string + description: The unique identifier of the code interpreter tool call item. + sequence_number: + type: integer + description: The sequence number of this event, used to order streaming events. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.code_interpreter_call.completed + group: responses + example: | + { + "type": "response.code_interpreter_call.completed", + "output_index": 5, + "item_id": "ci_12345", + "sequence_number": 1 + } + ResponseCodeInterpreterCallInProgressEvent: + type: object + description: Emitted when a code interpreter call is in progress. + properties: + type: + type: string + description: >- + The type of the event. Always + `response.code_interpreter_call.in_progress`. + enum: + - response.code_interpreter_call.in_progress + x-stainless-const: true + output_index: + type: integer + description: >- + The index of the output item in the response for which the code + interpreter call is in progress. + item_id: + type: string + description: The unique identifier of the code interpreter tool call item. + sequence_number: + type: integer + description: The sequence number of this event, used to order streaming events. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.code_interpreter_call.in_progress + group: responses + example: | + { + "type": "response.code_interpreter_call.in_progress", + "output_index": 0, + "item_id": "ci_12345", + "sequence_number": 1 + } + ResponseCodeInterpreterCallInterpretingEvent: + type: object + description: >- + Emitted when the code interpreter is actively interpreting the code + snippet. + properties: + type: + type: string + description: >- + The type of the event. Always + `response.code_interpreter_call.interpreting`. + enum: + - response.code_interpreter_call.interpreting + x-stainless-const: true + output_index: + type: integer + description: >- + The index of the output item in the response for which the code + interpreter is interpreting code. + item_id: + type: string + description: The unique identifier of the code interpreter tool call item. + sequence_number: + type: integer + description: The sequence number of this event, used to order streaming events. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.code_interpreter_call.interpreting + group: responses + example: | + { + "type": "response.code_interpreter_call.interpreting", + "output_index": 4, + "item_id": "ci_12345", + "sequence_number": 1 + } + ResponseCompletedEvent: + type: object + description: Emitted when the model response is complete. + properties: + type: + type: string + description: | + The type of the event. Always `response.completed`. + enum: + - response.completed + x-stainless-const: true + response: + $ref: '#/components/schemas/Response' + description: | + Properties of the completed response. + sequence_number: + type: integer + description: The sequence number for this event. + required: + - type + - response + - sequence_number + x-oaiMeta: + name: response.completed + group: responses + example: | + { + "type": "response.completed", + "response": { + "id": "resp_123", + "object": "response", + "created_at": 1740855869, + "status": "completed", + "completed_at": 1740855870, + "error": null, + "incomplete_details": null, + "input": [], + "instructions": null, + "max_output_tokens": null, + "model": "gpt-4o-mini-2024-07-18", + "output": [ + { + "id": "msg_123", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", + "annotations": [] + } + ] + } + ], + "previous_response_id": null, + "reasoning_effort": null, + "store": false, + "temperature": 1, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1, + "truncation": "disabled", + "usage": { + "input_tokens": 0, + "output_tokens": 0, + "output_tokens_details": { + "reasoning_tokens": 0 + }, + "total_tokens": 0 + }, + "user": null, + "metadata": {} + }, + "sequence_number": 1 + } + ResponseContentPartAddedEvent: + type: object + description: Emitted when a new content part is added. + properties: + type: + type: string + description: | + The type of the event. Always `response.content_part.added`. + enum: + - response.content_part.added + x-stainless-const: true + item_id: + type: string + description: | + The ID of the output item that the content part was added to. + output_index: + type: integer + description: | + The index of the output item that the content part was added to. + content_index: + type: integer + description: | + The index of the content part that was added. + part: + $ref: '#/components/schemas/OutputContent' + description: | + The content part that was added. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - item_id + - output_index + - content_index + - part + - sequence_number + x-oaiMeta: + name: response.content_part.added + group: responses + example: | + { + "type": "response.content_part.added", + "item_id": "msg_123", + "output_index": 0, + "content_index": 0, + "part": { + "type": "output_text", + "text": "", + "annotations": [] + }, + "sequence_number": 1 + } + ResponseContentPartDoneEvent: + type: object + description: Emitted when a content part is done. + properties: + type: + type: string + description: | + The type of the event. Always `response.content_part.done`. + enum: + - response.content_part.done + x-stainless-const: true + item_id: + type: string + description: | + The ID of the output item that the content part was added to. + output_index: + type: integer + description: | + The index of the output item that the content part was added to. + content_index: + type: integer + description: | + The index of the content part that is done. + sequence_number: + type: integer + description: The sequence number of this event. + part: + $ref: '#/components/schemas/OutputContent' + description: | + The content part that is done. + required: + - type + - item_id + - output_index + - content_index + - part + - sequence_number + x-oaiMeta: + name: response.content_part.done + group: responses + example: | + { + "type": "response.content_part.done", + "item_id": "msg_123", + "output_index": 0, + "content_index": 0, + "sequence_number": 1, + "part": { + "type": "output_text", + "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", + "annotations": [] + } + } + ResponseCreatedEvent: + type: object + description: | + An event that is emitted when a response is created. + properties: + type: + type: string + description: | + The type of the event. Always `response.created`. + enum: + - response.created + x-stainless-const: true + response: + $ref: '#/components/schemas/Response' + description: | + The response that was created. + sequence_number: + type: integer + description: The sequence number for this event. + required: + - type + - response + - sequence_number + x-oaiMeta: + name: response.created + group: responses + example: | + { + "type": "response.created", + "response": { + "id": "resp_67ccfcdd16748190a91872c75d38539e09e4d4aac714747c", + "object": "response", + "created_at": 1741487325, + "status": "in_progress", + "completed_at": null, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-4o-2024-08-06", + "output": [], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "store": true, + "temperature": 1, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1, + "truncation": "disabled", + "usage": null, + "user": null, + "metadata": {} + }, + "sequence_number": 1 + } + ResponseCustomToolCallInputDeltaEvent: + title: ResponseCustomToolCallInputDelta + type: object + description: > + Event representing a delta (partial update) to the input of a custom + tool call. + properties: + type: + type: string + enum: + - response.custom_tool_call_input.delta + description: The event type identifier. + x-stainless-const: true + sequence_number: + type: integer + description: The sequence number of this event. + output_index: + type: integer + description: The index of the output this delta applies to. + item_id: + type: string + description: Unique identifier for the API item associated with this event. + delta: + type: string + description: The incremental input data (delta) for the custom tool call. + required: + - type + - output_index + - item_id + - delta + - sequence_number + x-oaiMeta: + name: response.custom_tool_call_input.delta + group: responses + example: | + { + "type": "response.custom_tool_call_input.delta", + "output_index": 0, + "item_id": "ctc_1234567890abcdef", + "delta": "partial input text" + } + ResponseCustomToolCallInputDoneEvent: + title: ResponseCustomToolCallInputDone + type: object + description: | + Event indicating that input for a custom tool call is complete. + properties: + type: + type: string + enum: + - response.custom_tool_call_input.done + description: The event type identifier. + x-stainless-const: true + sequence_number: + type: integer + description: The sequence number of this event. + output_index: + type: integer + description: The index of the output this event applies to. + item_id: + type: string + description: Unique identifier for the API item associated with this event. + input: + type: string + description: The complete input data for the custom tool call. + required: + - type + - output_index + - item_id + - input + - sequence_number + x-oaiMeta: + name: response.custom_tool_call_input.done + group: responses + example: | + { + "type": "response.custom_tool_call_input.done", + "output_index": 0, + "item_id": "ctc_1234567890abcdef", + "input": "final complete input text" + } + ResponseError: + anyOf: + - type: object + description: > + An error object returned when the model fails to generate a + Response. + properties: + code: + $ref: '#/components/schemas/ResponseErrorCode' + message: + type: string + description: | + A human-readable description of the error. + required: + - code + - message + - type: 'null' + ResponseErrorCode: + type: string + description: | + The error code for the response. + enum: + - server_error + - rate_limit_exceeded + - invalid_prompt + - vector_store_timeout + - invalid_image + - invalid_image_format + - invalid_base64_image + - invalid_image_url + - image_too_large + - image_too_small + - image_parse_error + - image_content_policy_violation + - invalid_image_mode + - image_file_too_large + - unsupported_image_media_type + - empty_image_file + - failed_to_download_image + - image_file_not_found + ResponseErrorEvent: + type: object + description: Emitted when an error occurs. + properties: + type: + type: string + description: | + The type of the event. Always `error`. + enum: + - error + x-stainless-const: true + code: + anyOf: + - type: string + description: | + The error code. + - type: 'null' + message: + type: string + description: | + The error message. + param: + anyOf: + - type: string + description: | + The error parameter. + - type: 'null' + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - code + - message + - param + - sequence_number + x-oaiMeta: + name: error + group: responses + example: | + { + "type": "error", + "code": "ERR_SOMETHING", + "message": "Something went wrong", + "param": null, + "sequence_number": 1 + } + ResponseFailedEvent: + type: object + description: | + An event that is emitted when a response fails. + properties: + type: + type: string + description: | + The type of the event. Always `response.failed`. + enum: + - response.failed + x-stainless-const: true + sequence_number: + type: integer + description: The sequence number of this event. + response: + $ref: '#/components/schemas/Response' + description: | + The response that failed. + required: + - type + - response + - sequence_number + x-oaiMeta: + name: response.failed + group: responses + example: | + { + "type": "response.failed", + "response": { + "id": "resp_123", + "object": "response", + "created_at": 1740855869, + "status": "failed", + "completed_at": null, + "error": { + "code": "server_error", + "message": "The model failed to generate a response." + }, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-4o-mini-2024-07-18", + "output": [], + "previous_response_id": null, + "reasoning_effort": null, + "store": false, + "temperature": 1, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1, + "truncation": "disabled", + "usage": null, + "user": null, + "metadata": {} + } + } + ResponseFileSearchCallCompletedEvent: + type: object + description: Emitted when a file search call is completed (results found). + properties: + type: + type: string + description: | + The type of the event. Always `response.file_search_call.completed`. + enum: + - response.file_search_call.completed + x-stainless-const: true + output_index: + type: integer + description: | + The index of the output item that the file search call is initiated. + item_id: + type: string + description: | + The ID of the output item that the file search call is initiated. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.file_search_call.completed + group: responses + example: | + { + "type": "response.file_search_call.completed", + "output_index": 0, + "item_id": "fs_123", + "sequence_number": 1 + } + ResponseFileSearchCallInProgressEvent: + type: object + description: Emitted when a file search call is initiated. + properties: + type: + type: string + description: > + The type of the event. Always + `response.file_search_call.in_progress`. + enum: + - response.file_search_call.in_progress + x-stainless-const: true + output_index: + type: integer + description: | + The index of the output item that the file search call is initiated. + item_id: + type: string + description: | + The ID of the output item that the file search call is initiated. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.file_search_call.in_progress + group: responses + example: | + { + "type": "response.file_search_call.in_progress", + "output_index": 0, + "item_id": "fs_123", + "sequence_number": 1 + } + ResponseFileSearchCallSearchingEvent: + type: object + description: Emitted when a file search is currently searching. + properties: + type: + type: string + description: | + The type of the event. Always `response.file_search_call.searching`. + enum: + - response.file_search_call.searching + x-stainless-const: true + output_index: + type: integer + description: | + The index of the output item that the file search call is searching. + item_id: + type: string + description: | + The ID of the output item that the file search call is initiated. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.file_search_call.searching + group: responses + example: | + { + "type": "response.file_search_call.searching", + "output_index": 0, + "item_id": "fs_123", + "sequence_number": 1 + } + ResponseFormatJsonObject: + type: object + title: JSON object + description: > + JSON object response format. An older method of generating JSON + responses. + + Using `json_schema` is recommended for models that support it. Note that + the + + model will not generate JSON without a system or user message + instructing it + + to do so. + properties: + type: + type: string + description: The type of response format being defined. Always `json_object`. + enum: + - json_object + x-stainless-const: true + required: + - type + ResponseFormatJsonSchema: + type: object + title: JSON schema + description: | + JSON Schema response format. Used to generate structured JSON responses. + Learn more about [Structured Outputs](/docs/guides/structured-outputs). + properties: + type: + type: string + description: The type of response format being defined. Always `json_schema`. + enum: + - json_schema + x-stainless-const: true + json_schema: + type: object + title: JSON schema + description: | + Structured Outputs configuration options, including a JSON Schema. + properties: + description: + type: string + description: > + A description of what the response format is for, used by the + model to + + determine how to respond in the format. + name: + type: string + description: > + The name of the response format. Must be a-z, A-Z, 0-9, or + contain + + underscores and dashes, with a maximum length of 64. + schema: + $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' + strict: + anyOf: + - type: boolean + default: false + description: > + 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). + - type: 'null' + required: + - name + required: + - type + - json_schema + ResponseFormatJsonSchemaSchema: + type: object + title: JSON schema + description: | + The schema for the response format, described as a JSON Schema object. + Learn how to build JSON schemas [here](https://json-schema.org/). + additionalProperties: true + ResponseFormatText: + type: object + title: Text + description: | + Default response format. Used to generate text responses. + properties: + type: + type: string + description: The type of response format being defined. Always `text`. + enum: + - text + x-stainless-const: true + required: + - type + ResponseFormatTextGrammar: + type: object + title: Text grammar + description: | + A custom grammar for the model to follow when generating text. + Learn more in the [custom grammars guide](/docs/guides/custom-grammars). + properties: + type: + type: string + description: The type of response format being defined. Always `grammar`. + enum: + - grammar + x-stainless-const: true + grammar: + type: string + description: The custom grammar for the model to follow. + required: + - type + - grammar + ResponseFormatTextPython: + type: object + title: Python grammar + description: | + Configure the model to generate valid Python code. See the + [custom grammars guide](/docs/guides/custom-grammars) for more details. + properties: + type: + type: string + description: The type of response format being defined. Always `python`. + enum: + - python + x-stainless-const: true + required: + - type + ResponseFunctionCallArgumentsDeltaEvent: + type: object + description: Emitted when there is a partial function-call arguments delta. + properties: + type: + type: string + description: > + The type of the event. Always + `response.function_call_arguments.delta`. + enum: + - response.function_call_arguments.delta + x-stainless-const: true + item_id: + type: string + description: > + The ID of the output item that the function-call arguments delta is + added to. + output_index: + type: integer + description: > + The index of the output item that the function-call arguments delta + is added to. + sequence_number: + type: integer + description: The sequence number of this event. + delta: + type: string + description: | + The function-call arguments delta that is added. + required: + - type + - item_id + - output_index + - delta + - sequence_number + x-oaiMeta: + name: response.function_call_arguments.delta + group: responses + example: | + { + "type": "response.function_call_arguments.delta", + "item_id": "item-abc", + "output_index": 0, + "delta": "{ \"arg\":" + "sequence_number": 1 + } + ResponseFunctionCallArgumentsDoneEvent: + type: object + description: Emitted when function-call arguments are finalized. + properties: + type: + type: string + enum: + - response.function_call_arguments.done + x-stainless-const: true + item_id: + type: string + description: The ID of the item. + name: + type: string + description: The name of the function that was called. + output_index: + type: integer + description: The index of the output item. + sequence_number: + type: integer + description: The sequence number of this event. + arguments: + type: string + description: The function-call arguments. + required: + - type + - item_id + - name + - output_index + - arguments + - sequence_number + x-oaiMeta: + name: response.function_call_arguments.done + group: responses + example: | + { + "type": "response.function_call_arguments.done", + "item_id": "item-abc", + "name": "get_weather", + "output_index": 1, + "arguments": "{ \"arg\": 123 }", + "sequence_number": 1 + } + ResponseImageGenCallCompletedEvent: + type: object + title: ResponseImageGenCallCompletedEvent + description: > + Emitted when an image generation tool call has completed and the final + image is available. + properties: + type: + type: string + enum: + - response.image_generation_call.completed + description: >- + The type of the event. Always + 'response.image_generation_call.completed'. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response's output array. + sequence_number: + type: integer + description: The sequence number of this event. + item_id: + type: string + description: The unique identifier of the image generation item being processed. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.image_generation_call.completed + group: responses + example: | + { + "type": "response.image_generation_call.completed", + "output_index": 0, + "item_id": "item-123", + "sequence_number": 1 + } + ResponseImageGenCallGeneratingEvent: + type: object + title: ResponseImageGenCallGeneratingEvent + description: > + Emitted when an image generation tool call is actively generating an + image (intermediate state). + properties: + type: + type: string + enum: + - response.image_generation_call.generating + description: >- + The type of the event. Always + 'response.image_generation_call.generating'. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response's output array. + item_id: + type: string + description: The unique identifier of the image generation item being processed. + sequence_number: + type: integer + description: The sequence number of the image generation item being processed. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.image_generation_call.generating + group: responses + example: | + { + "type": "response.image_generation_call.generating", + "output_index": 0, + "item_id": "item-123", + "sequence_number": 0 + } + ResponseImageGenCallInProgressEvent: + type: object + title: ResponseImageGenCallInProgressEvent + description: | + Emitted when an image generation tool call is in progress. + properties: + type: + type: string + enum: + - response.image_generation_call.in_progress + description: >- + The type of the event. Always + 'response.image_generation_call.in_progress'. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response's output array. + item_id: + type: string + description: The unique identifier of the image generation item being processed. + sequence_number: + type: integer + description: The sequence number of the image generation item being processed. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.image_generation_call.in_progress + group: responses + example: | + { + "type": "response.image_generation_call.in_progress", + "output_index": 0, + "item_id": "item-123", + "sequence_number": 0 + } + ResponseImageGenCallPartialImageEvent: + type: object + title: ResponseImageGenCallPartialImageEvent + description: > + Emitted when a partial image is available during image generation + streaming. + properties: + type: + type: string + enum: + - response.image_generation_call.partial_image + description: >- + The type of the event. Always + 'response.image_generation_call.partial_image'. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response's output array. + item_id: + type: string + description: The unique identifier of the image generation item being processed. + sequence_number: + type: integer + description: The sequence number of the image generation item being processed. + partial_image_index: + type: integer + description: >- + 0-based index for the partial image (backend is 1-based, but this is + 0-based for the user). + partial_image_b64: + type: string + description: >- + Base64-encoded partial image data, suitable for rendering as an + image. + required: + - type + - output_index + - item_id + - sequence_number + - partial_image_index + - partial_image_b64 + x-oaiMeta: + name: response.image_generation_call.partial_image + group: responses + example: | + { + "type": "response.image_generation_call.partial_image", + "output_index": 0, + "item_id": "item-123", + "sequence_number": 0, + "partial_image_index": 0, + "partial_image_b64": "..." + } + ResponseInProgressEvent: + type: object + description: Emitted when the response is in progress. + properties: + type: + type: string + description: | + The type of the event. Always `response.in_progress`. + enum: + - response.in_progress + x-stainless-const: true + response: + $ref: '#/components/schemas/Response' + description: | + The response that is in progress. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - response + - sequence_number + x-oaiMeta: + name: response.in_progress + group: responses + example: | + { + "type": "response.in_progress", + "response": { + "id": "resp_67ccfcdd16748190a91872c75d38539e09e4d4aac714747c", + "object": "response", + "created_at": 1741487325, + "status": "in_progress", + "completed_at": null, + "error": null, + "incomplete_details": null, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-4o-2024-08-06", + "output": [], + "parallel_tool_calls": true, + "previous_response_id": null, + "reasoning": { + "effort": null, + "summary": null + }, + "store": true, + "temperature": 1, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1, + "truncation": "disabled", + "usage": null, + "user": null, + "metadata": {} + }, + "sequence_number": 1 + } + ResponseIncompleteEvent: + type: object + description: | + An event that is emitted when a response finishes as incomplete. + properties: + type: + type: string + description: | + The type of the event. Always `response.incomplete`. + enum: + - response.incomplete + x-stainless-const: true + response: + $ref: '#/components/schemas/Response' + description: | + The response that was incomplete. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - response + - sequence_number + x-oaiMeta: + name: response.incomplete + group: responses + example: | + { + "type": "response.incomplete", + "response": { + "id": "resp_123", + "object": "response", + "created_at": 1740855869, + "status": "incomplete", + "completed_at": null, + "error": null, + "incomplete_details": { + "reason": "max_tokens" + }, + "instructions": null, + "max_output_tokens": null, + "model": "gpt-4o-mini-2024-07-18", + "output": [], + "previous_response_id": null, + "reasoning_effort": null, + "store": false, + "temperature": 1, + "text": { + "format": { + "type": "text" + } + }, + "tool_choice": "auto", + "tools": [], + "top_p": 1, + "truncation": "disabled", + "usage": null, + "user": null, + "metadata": {} + }, + "sequence_number": 1 + } + ResponseItemList: + type: object + description: A list of Response items. + properties: + object: + type: string + description: The type of object returned, must be `list`. + enum: + - list + x-stainless-const: true + data: + type: array + description: A list of items used to generate this response. + items: + $ref: '#/components/schemas/ItemResource' + has_more: + type: boolean + description: Whether there are more items available. + first_id: + type: string + description: The ID of the first item in the list. + last_id: + type: string + description: The ID of the last item in the list. + required: + - object + - data + - has_more + - first_id + - last_id + x-oaiMeta: + name: The input item list + group: responses + example: | + { + "object": "list", + "data": [ + { + "id": "msg_abc123", + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "Tell me a three sentence bedtime story about a unicorn." + } + ] + } + ], + "first_id": "msg_abc123", + "last_id": "msg_abc123", + "has_more": false + } + ResponseLogProb: + type: object + description: > + A logprob is the logarithmic probability that the model assigns to + producing + + a particular token at a given position in the sequence. Less-negative + (higher) + + logprob values indicate greater model confidence in that token choice. + properties: + token: + description: A possible text token. + type: string + logprob: + description: | + The log probability of this token. + type: number + top_logprobs: + description: | + The log probability of the top 20 most likely tokens. + type: array + items: + type: object + properties: + token: + description: A possible text token. + type: string + logprob: + description: The log probability of this token. + type: number + required: + - token + - logprob + ResponseMCPCallArgumentsDeltaEvent: + type: object + title: ResponseMCPCallArgumentsDeltaEvent + description: > + Emitted when there is a delta (partial update) to the arguments of an + MCP tool call. + properties: + type: + type: string + enum: + - response.mcp_call_arguments.delta + description: The type of the event. Always 'response.mcp_call_arguments.delta'. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response's output array. + item_id: + type: string + description: The unique identifier of the MCP tool call item being processed. + delta: + type: string + description: > + A JSON string containing the partial update to the arguments for the + MCP tool call. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - output_index + - item_id + - delta + - sequence_number + x-oaiMeta: + name: response.mcp_call_arguments.delta + group: responses + example: | + { + "type": "response.mcp_call_arguments.delta", + "output_index": 0, + "item_id": "item-abc", + "delta": "{", + "sequence_number": 1 + } + ResponseMCPCallArgumentsDoneEvent: + type: object + title: ResponseMCPCallArgumentsDoneEvent + description: | + Emitted when the arguments for an MCP tool call are finalized. + properties: + type: + type: string + enum: + - response.mcp_call_arguments.done + description: The type of the event. Always 'response.mcp_call_arguments.done'. + x-stainless-const: true + output_index: + type: integer + description: The index of the output item in the response's output array. + item_id: + type: string + description: The unique identifier of the MCP tool call item being processed. + arguments: + type: string + description: > + A JSON string containing the finalized arguments for the MCP tool + call. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - output_index + - item_id + - arguments + - sequence_number + x-oaiMeta: + name: response.mcp_call_arguments.done + group: responses + example: | + { + "type": "response.mcp_call_arguments.done", + "output_index": 0, + "item_id": "item-abc", + "arguments": "{\"arg1\": \"value1\", \"arg2\": \"value2\"}", + "sequence_number": 1 + } + ResponseMCPCallCompletedEvent: + type: object + title: ResponseMCPCallCompletedEvent + description: | + Emitted when an MCP tool call has completed successfully. + properties: + type: + type: string + enum: + - response.mcp_call.completed + description: The type of the event. Always 'response.mcp_call.completed'. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP tool call item that completed. + output_index: + type: integer + description: The index of the output item that completed. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - item_id + - output_index + - sequence_number + x-oaiMeta: + name: response.mcp_call.completed + group: responses + example: | + { + "type": "response.mcp_call.completed", + "sequence_number": 1, + "item_id": "mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90", + "output_index": 0 + } + ResponseMCPCallFailedEvent: + type: object + title: ResponseMCPCallFailedEvent + description: | + Emitted when an MCP tool call has failed. + properties: + type: + type: string + enum: + - response.mcp_call.failed + description: The type of the event. Always 'response.mcp_call.failed'. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP tool call item that failed. + output_index: + type: integer + description: The index of the output item that failed. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - item_id + - output_index + - sequence_number + x-oaiMeta: + name: response.mcp_call.failed + group: responses + example: | + { + "type": "response.mcp_call.failed", + "sequence_number": 1, + "item_id": "mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90", + "output_index": 0 + } + ResponseMCPCallInProgressEvent: + type: object + title: ResponseMCPCallInProgressEvent + description: | + Emitted when an MCP tool call is in progress. + properties: + type: + type: string + enum: + - response.mcp_call.in_progress + description: The type of the event. Always 'response.mcp_call.in_progress'. + x-stainless-const: true + sequence_number: + type: integer + description: The sequence number of this event. + output_index: + type: integer + description: The index of the output item in the response's output array. + item_id: + type: string + description: The unique identifier of the MCP tool call item being processed. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.mcp_call.in_progress + group: responses + example: | + { + "type": "response.mcp_call.in_progress", + "sequence_number": 1, + "output_index": 0, + "item_id": "mcp_682d437d90a88191bf88cd03aae0c3e503937d5f622d7a90" + } + ResponseMCPListToolsCompletedEvent: + type: object + title: ResponseMCPListToolsCompletedEvent + description: > + Emitted when the list of available MCP tools has been successfully + retrieved. + properties: + type: + type: string + enum: + - response.mcp_list_tools.completed + description: The type of the event. Always 'response.mcp_list_tools.completed'. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP tool call item that produced this output. + output_index: + type: integer + description: The index of the output item that was processed. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - item_id + - output_index + - sequence_number + x-oaiMeta: + name: response.mcp_list_tools.completed + group: responses + example: | + { + "type": "response.mcp_list_tools.completed", + "sequence_number": 1, + "output_index": 0, + "item_id": "mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90" + } + ResponseMCPListToolsFailedEvent: + type: object + title: ResponseMCPListToolsFailedEvent + description: | + Emitted when the attempt to list available MCP tools has failed. + properties: + type: + type: string + enum: + - response.mcp_list_tools.failed + description: The type of the event. Always 'response.mcp_list_tools.failed'. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP tool call item that failed. + output_index: + type: integer + description: The index of the output item that failed. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - item_id + - output_index + - sequence_number + x-oaiMeta: + name: response.mcp_list_tools.failed + group: responses + example: | + { + "type": "response.mcp_list_tools.failed", + "sequence_number": 1, + "output_index": 0, + "item_id": "mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90" + } + ResponseMCPListToolsInProgressEvent: + type: object + title: ResponseMCPListToolsInProgressEvent + description: > + Emitted when the system is in the process of retrieving the list of + available MCP tools. + properties: + type: + type: string + enum: + - response.mcp_list_tools.in_progress + description: The type of the event. Always 'response.mcp_list_tools.in_progress'. + x-stainless-const: true + item_id: + type: string + description: The ID of the MCP tool call item that is being processed. + output_index: + type: integer + description: The index of the output item that is being processed. + sequence_number: + type: integer + description: The sequence number of this event. + required: + - type + - item_id + - output_index + - sequence_number + x-oaiMeta: + name: response.mcp_list_tools.in_progress + group: responses + example: | + { + "type": "response.mcp_list_tools.in_progress", + "sequence_number": 1, + "output_index": 0, + "item_id": "mcpl_682d4379df088191886b70f4ec39f90403937d5f622d7a90" + } + ResponseModalities: + anyOf: + - type: array + description: > + Output types that you would like the model to generate. + + Most models are capable of generating text, which is the default: + + + `["text"]` + + + The `gpt-4o-audio-preview` model can also be used to + + [generate audio](/docs/guides/audio). To request that this model + generate + + both text and audio responses, you can use: + + + `["text", "audio"]` + items: + type: string + enum: + - text + - audio + - type: 'null' + ResponseOutputItemAddedEvent: + type: object + description: Emitted when a new output item is added. + properties: + type: + type: string + description: | + The type of the event. Always `response.output_item.added`. + enum: + - response.output_item.added + x-stainless-const: true + output_index: + type: integer + description: | + The index of the output item that was added. + sequence_number: + type: integer + description: | + The sequence number of this event. + item: + $ref: '#/components/schemas/OutputItem' + description: | + The output item that was added. + required: + - type + - output_index + - item + - sequence_number + x-oaiMeta: + name: response.output_item.added + group: responses + example: | + { + "type": "response.output_item.added", + "output_index": 0, + "item": { + "id": "msg_123", + "status": "in_progress", + "type": "message", + "role": "assistant", + "content": [] + }, + "sequence_number": 1 + } + ResponseOutputItemDoneEvent: + type: object + description: Emitted when an output item is marked done. + properties: + type: + type: string + description: | + The type of the event. Always `response.output_item.done`. + enum: + - response.output_item.done + x-stainless-const: true + output_index: + type: integer + description: | + The index of the output item that was marked done. + sequence_number: + type: integer + description: | + The sequence number of this event. + item: + $ref: '#/components/schemas/OutputItem' + description: | + The output item that was marked done. + required: + - type + - output_index + - item + - sequence_number + x-oaiMeta: + name: response.output_item.done + group: responses + example: | + { + "type": "response.output_item.done", + "output_index": 0, + "item": { + "id": "msg_123", + "status": "completed", + "type": "message", + "role": "assistant", + "content": [ + { + "type": "output_text", + "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", + "annotations": [] + } + ] + }, + "sequence_number": 1 + } + ResponseOutputTextAnnotationAddedEvent: + type: object + title: ResponseOutputTextAnnotationAddedEvent + description: | + Emitted when an annotation is added to output text content. + properties: + type: + type: string + enum: + - response.output_text.annotation.added + description: >- + The type of the event. Always + 'response.output_text.annotation.added'. + x-stainless-const: true + item_id: + type: string + description: >- + The unique identifier of the item to which the annotation is being + added. + output_index: + type: integer + description: The index of the output item in the response's output array. + content_index: + type: integer + description: The index of the content part within the output item. + annotation_index: + type: integer + description: The index of the annotation within the content part. + sequence_number: + type: integer + description: The sequence number of this event. + annotation: + type: object + description: >- + The annotation object being added. (See annotation schema for + details.) + required: + - type + - item_id + - output_index + - content_index + - annotation_index + - annotation + - sequence_number + x-oaiMeta: + name: response.output_text.annotation.added + group: responses + example: | + { + "type": "response.output_text.annotation.added", + "item_id": "item-abc", + "output_index": 0, + "content_index": 0, + "annotation_index": 0, + "annotation": { + "type": "text_annotation", + "text": "This is a test annotation", + "start": 0, + "end": 10 + }, + "sequence_number": 1 + } + ResponsePromptVariables: + anyOf: + - type: object + title: Prompt Variables + description: | + Optional map of values to substitute in for variables in your + prompt. The substitution values can either be strings, or other + Response input types like images or files. + x-oaiExpandable: true + x-oaiTypeLabel: map + additionalProperties: + x-oaiExpandable: true + x-oaiTypeLabel: map + oneOf: + - type: string + - $ref: '#/components/schemas/InputTextContent' + - $ref: '#/components/schemas/InputImageContent' + - $ref: '#/components/schemas/InputFileContent' + - type: 'null' + ResponseProperties: + type: object + properties: + previous_response_id: + anyOf: + - type: string + description: > + The unique ID of the previous response to the model. Use this to + + create multi-turn conversations. Learn more about + + [conversation state](/docs/guides/conversation-state). Cannot be + used in conjunction with `conversation`. + - type: 'null' + model: + description: > + Model ID used to generate the response, like `gpt-4o` or `o3`. + OpenAI + + offers a wide range of models with different capabilities, + performance + + characteristics, and price points. Refer to the [model + guide](/docs/models) + + to browse and compare available models. + $ref: '#/components/schemas/ModelIdsResponses' + reasoning: + anyOf: + - $ref: '#/components/schemas/Reasoning' + - type: 'null' + background: + anyOf: + - type: boolean + description: | + Whether to run the model response in the background. + [Learn more](/docs/guides/background). + default: false + - type: 'null' + max_tool_calls: + anyOf: + - description: > + The maximum number of total calls to built-in tools that can be + processed in a response. This maximum number applies across all + built-in tool calls, not per individual tool. Any further + attempts to call a tool by the model will be ignored. + type: integer + - type: 'null' + text: + $ref: '#/components/schemas/ResponseTextParam' + tools: + $ref: '#/components/schemas/ToolsArray' + tool_choice: + $ref: '#/components/schemas/ToolChoiceParam' + prompt: + $ref: '#/components/schemas/Prompt' + truncation: + anyOf: + - type: string + description: > + The truncation strategy to use for the model response. + + - `auto`: If the input to this Response exceeds + the model's context window size, the model will truncate the + response to fit the context window by dropping items from the beginning of the conversation. + - `disabled` (default): If the input size will exceed the + context window + size for a model, the request will fail with a 400 error. + enum: + - auto + - disabled + default: disabled + - type: 'null' + ResponseQueuedEvent: + type: object + title: ResponseQueuedEvent + description: | + Emitted when a response is queued and waiting to be processed. + properties: + type: + type: string + enum: + - response.queued + description: The type of the event. Always 'response.queued'. + x-stainless-const: true + response: + $ref: '#/components/schemas/Response' + description: The full response object that is queued. + sequence_number: + type: integer + description: The sequence number for this event. + required: + - type + - response + - sequence_number + x-oaiMeta: + name: response.queued + group: responses + example: | + { + "type": "response.queued", + "response": { + "id": "res_123", + "status": "queued", + "created_at": "2021-01-01T00:00:00Z", + "updated_at": "2021-01-01T00:00:00Z" + }, + "sequence_number": 1 + } + ResponseReasoningSummaryPartAddedEvent: + type: object + description: Emitted when a new reasoning summary part is added. + properties: + type: + type: string + description: > + The type of the event. Always + `response.reasoning_summary_part.added`. + enum: + - response.reasoning_summary_part.added + x-stainless-const: true + item_id: + type: string + description: | + The ID of the item this summary part is associated with. + output_index: + type: integer + description: | + The index of the output item this summary part is associated with. + summary_index: + type: integer + description: | + The index of the summary part within the reasoning summary. + sequence_number: + type: integer + description: | + The sequence number of this event. + part: + type: object + description: | + The summary part that was added. + properties: + type: + type: string + description: The type of the summary part. Always `summary_text`. + enum: + - summary_text + x-stainless-const: true + text: + type: string + description: The text of the summary part. + required: + - type + - text + required: + - type + - item_id + - output_index + - summary_index + - part + - sequence_number + x-oaiMeta: + name: response.reasoning_summary_part.added + group: responses + example: | + { + "type": "response.reasoning_summary_part.added", + "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", + "output_index": 0, + "summary_index": 0, + "part": { + "type": "summary_text", + "text": "" + }, + "sequence_number": 1 + } + ResponseReasoningSummaryPartDoneEvent: + type: object + description: Emitted when a reasoning summary part is completed. + properties: + type: + type: string + description: > + The type of the event. Always + `response.reasoning_summary_part.done`. + enum: + - response.reasoning_summary_part.done + x-stainless-const: true + item_id: + type: string + description: | + The ID of the item this summary part is associated with. + output_index: + type: integer + description: | + The index of the output item this summary part is associated with. + summary_index: + type: integer + description: | + The index of the summary part within the reasoning summary. + sequence_number: + type: integer + description: | + The sequence number of this event. + part: + type: object + description: | + The completed summary part. + properties: + type: + type: string + description: The type of the summary part. Always `summary_text`. + enum: + - summary_text + x-stainless-const: true + text: + type: string + description: The text of the summary part. + required: + - type + - text + required: + - type + - item_id + - output_index + - summary_index + - part + - sequence_number + x-oaiMeta: + name: response.reasoning_summary_part.done + group: responses + example: | + { + "type": "response.reasoning_summary_part.done", + "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", + "output_index": 0, + "summary_index": 0, + "part": { + "type": "summary_text", + "text": "**Responding to a greeting**\n\nThe user just said, \"Hello!\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \"Hello! How can I assist you today?\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!" + }, + "sequence_number": 1 + } + ResponseReasoningSummaryTextDeltaEvent: + type: object + description: Emitted when a delta is added to a reasoning summary text. + properties: + type: + type: string + description: > + The type of the event. Always + `response.reasoning_summary_text.delta`. + enum: + - response.reasoning_summary_text.delta + x-stainless-const: true + item_id: + type: string + description: | + The ID of the item this summary text delta is associated with. + output_index: + type: integer + description: > + The index of the output item this summary text delta is associated + with. + summary_index: + type: integer + description: | + The index of the summary part within the reasoning summary. + delta: + type: string + description: | + The text delta that was added to the summary. + sequence_number: + type: integer + description: | + The sequence number of this event. + required: + - type + - item_id + - output_index + - summary_index + - delta + - sequence_number + x-oaiMeta: + name: response.reasoning_summary_text.delta + group: responses + example: | + { + "type": "response.reasoning_summary_text.delta", + "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", + "output_index": 0, + "summary_index": 0, + "delta": "**Responding to a greeting**\n\nThe user just said, \"Hello!\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \"Hello! How can I assist you today?\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!", + "sequence_number": 1 + } + ResponseReasoningSummaryTextDoneEvent: + type: object + description: Emitted when a reasoning summary text is completed. + properties: + type: + type: string + description: > + The type of the event. Always + `response.reasoning_summary_text.done`. + enum: + - response.reasoning_summary_text.done + x-stainless-const: true + item_id: + type: string + description: | + The ID of the item this summary text is associated with. + output_index: + type: integer + description: | + The index of the output item this summary text is associated with. + summary_index: + type: integer + description: | + The index of the summary part within the reasoning summary. + text: + type: string + description: | + The full text of the completed reasoning summary. + sequence_number: + type: integer + description: | + The sequence number of this event. + required: + - type + - item_id + - output_index + - summary_index + - text + - sequence_number + x-oaiMeta: + name: response.reasoning_summary_text.done + group: responses + example: | + { + "type": "response.reasoning_summary_text.done", + "item_id": "rs_6806bfca0b2481918a5748308061a2600d3ce51bdffd5476", + "output_index": 0, + "summary_index": 0, + "text": "**Responding to a greeting**\n\nThe user just said, \"Hello!\" So, it seems I need to engage. I'll greet them back and offer help since they're looking to chat. I could say something like, \"Hello! How can I assist you today?\" That feels friendly and open. They didn't ask a specific question, so this approach will work well for starting a conversation. Let's see where it goes from there!", + "sequence_number": 1 + } + ResponseReasoningTextDeltaEvent: + type: object + description: Emitted when a delta is added to a reasoning text. + properties: + type: + type: string + description: | + The type of the event. Always `response.reasoning_text.delta`. + enum: + - response.reasoning_text.delta + x-stainless-const: true + item_id: + type: string + description: | + The ID of the item this reasoning text delta is associated with. + output_index: + type: integer + description: > + The index of the output item this reasoning text delta is associated + with. + content_index: + type: integer + description: > + The index of the reasoning content part this delta is associated + with. + delta: + type: string + description: | + The text delta that was added to the reasoning content. + sequence_number: + type: integer + description: | + The sequence number of this event. + required: + - type + - item_id + - output_index + - content_index + - delta + - sequence_number + x-oaiMeta: + name: response.reasoning_text.delta + group: responses + example: | + { + "type": "response.reasoning_text.delta", + "item_id": "rs_123", + "output_index": 0, + "content_index": 0, + "delta": "The", + "sequence_number": 1 + } + ResponseReasoningTextDoneEvent: + type: object + description: Emitted when a reasoning text is completed. + properties: + type: + type: string + description: | + The type of the event. Always `response.reasoning_text.done`. + enum: + - response.reasoning_text.done + x-stainless-const: true + item_id: + type: string + description: | + The ID of the item this reasoning text is associated with. + output_index: + type: integer + description: | + The index of the output item this reasoning text is associated with. + content_index: + type: integer + description: | + The index of the reasoning content part. + text: + type: string + description: | + The full text of the completed reasoning content. + sequence_number: + type: integer + description: | + The sequence number of this event. + required: + - type + - item_id + - output_index + - content_index + - text + - sequence_number + x-oaiMeta: + name: response.reasoning_text.done + group: responses + example: | + { + "type": "response.reasoning_text.done", + "item_id": "rs_123", + "output_index": 0, + "content_index": 0, + "text": "The user is asking...", + "sequence_number": 4 + } + ResponseRefusalDeltaEvent: + type: object + description: Emitted when there is a partial refusal text. + properties: + type: + type: string + description: | + The type of the event. Always `response.refusal.delta`. + enum: + - response.refusal.delta + x-stainless-const: true + item_id: + type: string + description: | + The ID of the output item that the refusal text is added to. + output_index: + type: integer + description: | + The index of the output item that the refusal text is added to. + content_index: + type: integer + description: | + The index of the content part that the refusal text is added to. + delta: + type: string + description: | + The refusal text that is added. + sequence_number: + type: integer + description: | + The sequence number of this event. + required: + - type + - item_id + - output_index + - content_index + - delta + - sequence_number + x-oaiMeta: + name: response.refusal.delta + group: responses + example: | + { + "type": "response.refusal.delta", + "item_id": "msg_123", + "output_index": 0, + "content_index": 0, + "delta": "refusal text so far", + "sequence_number": 1 + } + ResponseRefusalDoneEvent: + type: object + description: Emitted when refusal text is finalized. + properties: + type: + type: string + description: | + The type of the event. Always `response.refusal.done`. + enum: + - response.refusal.done + x-stainless-const: true + item_id: + type: string + description: | + The ID of the output item that the refusal text is finalized. + output_index: + type: integer + description: | + The index of the output item that the refusal text is finalized. + content_index: + type: integer + description: | + The index of the content part that the refusal text is finalized. + refusal: + type: string + description: | + The refusal text that is finalized. + sequence_number: + type: integer + description: | + The sequence number of this event. + required: + - type + - item_id + - output_index + - content_index + - refusal + - sequence_number + x-oaiMeta: + name: response.refusal.done + group: responses + example: | + { + "type": "response.refusal.done", + "item_id": "item-abc", + "output_index": 1, + "content_index": 2, + "refusal": "final refusal text", + "sequence_number": 1 + } + ResponseStreamEvent: + anyOf: + - $ref: '#/components/schemas/ResponseAudioDeltaEvent' + - $ref: '#/components/schemas/ResponseAudioDoneEvent' + - $ref: '#/components/schemas/ResponseAudioTranscriptDeltaEvent' + - $ref: '#/components/schemas/ResponseAudioTranscriptDoneEvent' + - $ref: '#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent' + - $ref: '#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent' + - $ref: '#/components/schemas/ResponseCodeInterpreterCallCompletedEvent' + - $ref: '#/components/schemas/ResponseCodeInterpreterCallInProgressEvent' + - $ref: '#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent' + - $ref: '#/components/schemas/ResponseCompletedEvent' + - $ref: '#/components/schemas/ResponseContentPartAddedEvent' + - $ref: '#/components/schemas/ResponseContentPartDoneEvent' + - $ref: '#/components/schemas/ResponseCreatedEvent' + - $ref: '#/components/schemas/ResponseErrorEvent' + - $ref: '#/components/schemas/ResponseFileSearchCallCompletedEvent' + - $ref: '#/components/schemas/ResponseFileSearchCallInProgressEvent' + - $ref: '#/components/schemas/ResponseFileSearchCallSearchingEvent' + - $ref: '#/components/schemas/ResponseFunctionCallArgumentsDeltaEvent' + - $ref: '#/components/schemas/ResponseFunctionCallArgumentsDoneEvent' + - $ref: '#/components/schemas/ResponseInProgressEvent' + - $ref: '#/components/schemas/ResponseFailedEvent' + - $ref: '#/components/schemas/ResponseIncompleteEvent' + - $ref: '#/components/schemas/ResponseOutputItemAddedEvent' + - $ref: '#/components/schemas/ResponseOutputItemDoneEvent' + - $ref: '#/components/schemas/ResponseReasoningSummaryPartAddedEvent' + - $ref: '#/components/schemas/ResponseReasoningSummaryPartDoneEvent' + - $ref: '#/components/schemas/ResponseReasoningSummaryTextDeltaEvent' + - $ref: '#/components/schemas/ResponseReasoningSummaryTextDoneEvent' + - $ref: '#/components/schemas/ResponseReasoningTextDeltaEvent' + - $ref: '#/components/schemas/ResponseReasoningTextDoneEvent' + - $ref: '#/components/schemas/ResponseRefusalDeltaEvent' + - $ref: '#/components/schemas/ResponseRefusalDoneEvent' + - $ref: '#/components/schemas/ResponseTextDeltaEvent' + - $ref: '#/components/schemas/ResponseTextDoneEvent' + - $ref: '#/components/schemas/ResponseWebSearchCallCompletedEvent' + - $ref: '#/components/schemas/ResponseWebSearchCallInProgressEvent' + - $ref: '#/components/schemas/ResponseWebSearchCallSearchingEvent' + - $ref: '#/components/schemas/ResponseImageGenCallCompletedEvent' + - $ref: '#/components/schemas/ResponseImageGenCallGeneratingEvent' + - $ref: '#/components/schemas/ResponseImageGenCallInProgressEvent' + - $ref: '#/components/schemas/ResponseImageGenCallPartialImageEvent' + - $ref: '#/components/schemas/ResponseMCPCallArgumentsDeltaEvent' + - $ref: '#/components/schemas/ResponseMCPCallArgumentsDoneEvent' + - $ref: '#/components/schemas/ResponseMCPCallCompletedEvent' + - $ref: '#/components/schemas/ResponseMCPCallFailedEvent' + - $ref: '#/components/schemas/ResponseMCPCallInProgressEvent' + - $ref: '#/components/schemas/ResponseMCPListToolsCompletedEvent' + - $ref: '#/components/schemas/ResponseMCPListToolsFailedEvent' + - $ref: '#/components/schemas/ResponseMCPListToolsInProgressEvent' + - $ref: '#/components/schemas/ResponseOutputTextAnnotationAddedEvent' + - $ref: '#/components/schemas/ResponseQueuedEvent' + - $ref: '#/components/schemas/ResponseCustomToolCallInputDeltaEvent' + - $ref: '#/components/schemas/ResponseCustomToolCallInputDoneEvent' + discriminator: + propertyName: type + ResponseStreamOptions: + anyOf: + - description: > + Options for streaming responses. Only set this when you set `stream: + true`. + type: object + default: null + properties: + include_obfuscation: + type: boolean + description: > + When true, stream obfuscation will be enabled. Stream + obfuscation adds + + random characters to an `obfuscation` field on streaming delta + events to + + normalize payload sizes as a mitigation to certain side-channel + attacks. + + These obfuscation fields are included by default, but add a + small amount + + of overhead to the data stream. You can set + `include_obfuscation` to + + false to optimize for bandwidth if you trust the network links + between + + your application and the OpenAI API. + - type: 'null' + ResponseTextDeltaEvent: + type: object + description: Emitted when there is an additional text delta. + properties: + type: + type: string + description: | + The type of the event. Always `response.output_text.delta`. + enum: + - response.output_text.delta + x-stainless-const: true + item_id: + type: string + description: | + The ID of the output item that the text delta was added to. + output_index: + type: integer + description: | + The index of the output item that the text delta was added to. + content_index: + type: integer + description: | + The index of the content part that the text delta was added to. + delta: + type: string + description: | + The text delta that was added. + sequence_number: + type: integer + description: The sequence number for this event. + logprobs: + type: array + description: | + The log probabilities of the tokens in the delta. + items: + $ref: '#/components/schemas/ResponseLogProb' + required: + - type + - item_id + - output_index + - content_index + - delta + - sequence_number + - logprobs + x-oaiMeta: + name: response.output_text.delta + group: responses + example: | + { + "type": "response.output_text.delta", + "item_id": "msg_123", + "output_index": 0, + "content_index": 0, + "delta": "In", + "sequence_number": 1 + } + ResponseTextDoneEvent: + type: object + description: Emitted when text content is finalized. + properties: + type: + type: string + description: | + The type of the event. Always `response.output_text.done`. + enum: + - response.output_text.done + x-stainless-const: true + item_id: + type: string + description: | + The ID of the output item that the text content is finalized. + output_index: + type: integer + description: | + The index of the output item that the text content is finalized. + content_index: + type: integer + description: | + The index of the content part that the text content is finalized. + text: + type: string + description: | + The text content that is finalized. + sequence_number: + type: integer + description: The sequence number for this event. + logprobs: + type: array + description: | + The log probabilities of the tokens in the delta. + items: + $ref: '#/components/schemas/ResponseLogProb' + required: + - type + - item_id + - output_index + - content_index + - text + - sequence_number + - logprobs + x-oaiMeta: + name: response.output_text.done + group: responses + example: | + { + "type": "response.output_text.done", + "item_id": "msg_123", + "output_index": 0, + "content_index": 0, + "text": "In a shimmering forest under a sky full of stars, a lonely unicorn named Lila discovered a hidden pond that glowed with moonlight. Every night, she would leave sparkling, magical flowers by the water's edge, hoping to share her beauty with others. One enchanting evening, she woke to find a group of friendly animals gathered around, eager to be friends and share in her magic.", + "sequence_number": 1 + } + ResponseTextParam: + type: object + description: | + Configuration options for a text response from the model. Can be plain + text or structured JSON data. Learn more: + - [Text inputs and outputs](/docs/guides/text) + - [Structured Outputs](/docs/guides/structured-outputs) + properties: + format: + $ref: '#/components/schemas/TextResponseFormatConfiguration' + verbosity: + $ref: '#/components/schemas/Verbosity' + ResponseUsage: + type: object + description: | + Represents token usage details including input tokens, output tokens, + a breakdown of output tokens, and the total tokens used. + properties: + input_tokens: + type: integer + description: The number of input tokens. + input_tokens_details: + type: object + description: A detailed breakdown of the input tokens. + properties: + cached_tokens: + type: integer + description: | + The number of tokens that were retrieved from the cache. + [More on prompt caching](/docs/guides/prompt-caching). + required: + - cached_tokens + output_tokens: + type: integer + description: The number of output tokens. + output_tokens_details: + type: object + description: A detailed breakdown of the output tokens. + properties: + reasoning_tokens: + type: integer + description: The number of reasoning tokens. + required: + - reasoning_tokens + total_tokens: + type: integer + description: The total number of tokens used. + required: + - input_tokens + - input_tokens_details + - output_tokens + - output_tokens_details + - total_tokens + ResponseWebSearchCallCompletedEvent: + type: object + description: Emitted when a web search call is completed. + properties: + type: + type: string + description: | + The type of the event. Always `response.web_search_call.completed`. + enum: + - response.web_search_call.completed + x-stainless-const: true + output_index: + type: integer + description: > + The index of the output item that the web search call is associated + with. + item_id: + type: string + description: | + Unique ID for the output item associated with the web search call. + sequence_number: + type: integer + description: The sequence number of the web search call being processed. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.web_search_call.completed + group: responses + example: | + { + "type": "response.web_search_call.completed", + "output_index": 0, + "item_id": "ws_123", + "sequence_number": 0 + } + ResponseWebSearchCallInProgressEvent: + type: object + description: Emitted when a web search call is initiated. + properties: + type: + type: string + description: > + The type of the event. Always + `response.web_search_call.in_progress`. + enum: + - response.web_search_call.in_progress + x-stainless-const: true + output_index: + type: integer + description: > + The index of the output item that the web search call is associated + with. + item_id: + type: string + description: | + Unique ID for the output item associated with the web search call. + sequence_number: + type: integer + description: The sequence number of the web search call being processed. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.web_search_call.in_progress + group: responses + example: | + { + "type": "response.web_search_call.in_progress", + "output_index": 0, + "item_id": "ws_123", + "sequence_number": 0 + } + ResponseWebSearchCallSearchingEvent: + type: object + description: Emitted when a web search call is executing. + properties: + type: + type: string + description: | + The type of the event. Always `response.web_search_call.searching`. + enum: + - response.web_search_call.searching + x-stainless-const: true + output_index: + type: integer + description: > + The index of the output item that the web search call is associated + with. + item_id: + type: string + description: | + Unique ID for the output item associated with the web search call. + sequence_number: + type: integer + description: The sequence number of the web search call being processed. + required: + - type + - output_index + - item_id + - sequence_number + x-oaiMeta: + name: response.web_search_call.searching + group: responses + example: | + { + "type": "response.web_search_call.searching", + "output_index": 0, + "item_id": "ws_123", + "sequence_number": 0 + } + ResponsesClientEvent: + discriminator: + propertyName: type + description: | + Client events accepted by the Responses WebSocket server. + anyOf: + - $ref: '#/components/schemas/ResponsesClientEventResponseCreate' + ResponsesClientEventResponseCreate: + allOf: + - type: object + properties: + type: + type: string + enum: + - response.create + description: | + The type of the client event. Always `response.create`. + x-stainless-const: true + required: + - type + - $ref: '#/components/schemas/CreateResponse' + description: > + Client event for creating a response over a persistent WebSocket + connection. + + This payload uses the same top-level fields as `POST /v1/responses`. + + + Notes: + + - `stream` is implicit over WebSocket and should not be sent. + + - `background` is not supported over WebSocket. + ResponsesServerEvent: + discriminator: + propertyName: type + description: | + Server events emitted by the Responses WebSocket server. + anyOf: + - $ref: '#/components/schemas/ResponseStreamEvent' + Role: + type: object + description: Details about a role that can be assigned through the public Roles API. + properties: + object: + type: string + enum: + - role + description: Always `role`. + x-stainless-const: true + id: + type: string + description: Identifier for the role. + name: + type: string + description: Unique name for the role. + description: + description: Optional description of the role. + anyOf: + - type: string + - type: 'null' + permissions: + type: array + description: Permissions granted by the role. + items: + type: string + resource_type: + type: string + description: >- + Resource type the role is bound to (for example `api.organization` + or `api.project`). + predefined_role: + type: boolean + description: Whether the role is predefined and managed by OpenAI. + required: + - object + - id + - name + - description + - permissions + - resource_type + - predefined_role + x-oaiMeta: + name: The role object + example: | + { + "object": "role", + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "description": "Allows managing organization groups", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false + } + RoleDeletedResource: + type: object + description: Confirmation payload returned after deleting a role. + properties: + object: + type: string + enum: + - role.deleted + description: Always `role.deleted`. + x-stainless-const: true + id: + type: string + description: Identifier of the deleted role. + deleted: + type: boolean + description: Whether the role was deleted. + required: + - object + - id + - deleted + x-oaiMeta: + name: Role deletion confirmation + example: | + { + "object": "role.deleted", + "id": "role_01J1F8ROLE01", + "deleted": true + } + RoleListResource: + type: object + description: Paginated list of roles assigned to a principal. + properties: + object: + type: string + enum: + - list + description: Always `list`. + x-stainless-const: true + data: + type: array + description: Role assignments returned in the current page. + items: + $ref: '#/components/schemas/AssignedRoleDetails' + has_more: + type: boolean + description: Whether additional assignments are available when paginating. + next: + description: >- + Cursor to fetch the next page of results, or `null` when there are + no more assignments. + anyOf: + - type: string + - type: 'null' + required: + - object + - data + - has_more + - next + x-oaiMeta: + name: Assigned role list + example: | + { + "object": "list", + "data": [ + { + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false, + "description": "Allows managing organization groups", + "created_at": 1711471533, + "updated_at": 1711472599, + "created_by": "user_abc123", + "created_by_user_obj": { + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com" + }, + "metadata": {} + } + ], + "has_more": false, + "next": null + } + RunCompletionUsage: + anyOf: + - type: object + description: >- + Usage statistics related to the run. This value will be `null` if + the run is not in a terminal state (i.e. `in_progress`, `queued`, + etc.). + properties: + completion_tokens: + type: integer + description: Number of completion tokens used over the course of the run. + prompt_tokens: + type: integer + description: Number of prompt tokens used over the course of the run. + total_tokens: + type: integer + description: Total number of tokens used (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens + - type: 'null' + RunGraderRequest: + type: object + title: RunGraderRequest + properties: + grader: + type: object + description: The grader used for the fine-tuning job. + oneOf: + - $ref: '#/components/schemas/GraderStringCheck' + - $ref: '#/components/schemas/GraderTextSimilarity' + - $ref: '#/components/schemas/GraderPython' + - $ref: '#/components/schemas/GraderScoreModel' + - $ref: '#/components/schemas/GraderMulti' + item: + type: object + description: > + The dataset item provided to the grader. This will be used to + populate + + the `item` namespace. See [the guide](/docs/guides/graders) for more + details. + model_sample: + type: string + description: > + The model sample to be evaluated. This value will be used to + populate + + the `sample` namespace. See [the guide](/docs/guides/graders) for + more details. + + The `output_json` variable will be populated if the model sample is + a + + valid JSON string. + + required: + - grader + - model_sample + RunGraderResponse: + type: object + properties: + reward: + type: number + metadata: + type: object + properties: + name: + type: string + type: + type: string + errors: + type: object + properties: + formula_parse_error: + type: boolean + sample_parse_error: + type: boolean + truncated_observation_error: + type: boolean + unresponsive_reward_error: + type: boolean + invalid_variable_error: + type: boolean + other_error: + type: boolean + python_grader_server_error: + type: boolean + python_grader_server_error_type: + anyOf: + - type: string + - type: 'null' + python_grader_runtime_error: + type: boolean + python_grader_runtime_error_details: + anyOf: + - type: string + - type: 'null' + model_grader_server_error: + type: boolean + model_grader_refusal_error: + type: boolean + model_grader_parse_error: + type: boolean + model_grader_server_error_details: + anyOf: + - type: string + - type: 'null' + required: + - formula_parse_error + - sample_parse_error + - truncated_observation_error + - unresponsive_reward_error + - invalid_variable_error + - other_error + - python_grader_server_error + - python_grader_server_error_type + - python_grader_runtime_error + - python_grader_runtime_error_details + - model_grader_server_error + - model_grader_refusal_error + - model_grader_parse_error + - model_grader_server_error_details + execution_time: + type: number + scores: + type: object + additionalProperties: {} + token_usage: + anyOf: + - type: integer + - type: 'null' + sampled_model_name: + anyOf: + - type: string + - type: 'null' + required: + - name + - type + - errors + - execution_time + - scores + - token_usage + - sampled_model_name + sub_rewards: + type: object + additionalProperties: {} + model_grader_token_usage_per_model: + type: object + additionalProperties: {} + required: + - reward + - metadata + - sub_rewards + - model_grader_token_usage_per_model + RunObject: + type: object + title: A run on a thread + description: Represents an execution run on a [thread](/docs/api-reference/threads). + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread.run`. + type: string + enum: + - thread.run + x-stainless-const: true + created_at: + description: The Unix timestamp (in seconds) for when the run was created. + type: integer + thread_id: + description: >- + The ID of the [thread](/docs/api-reference/threads) that was + executed on as a part of this run. + type: string + assistant_id: + description: >- + The ID of the [assistant](/docs/api-reference/assistants) used for + execution of this run. + type: string + status: + description: >- + The status of the run, which can be either `queued`, `in_progress`, + `requires_action`, `cancelling`, `cancelled`, `failed`, `completed`, + `incomplete`, or `expired`. + type: string + enum: + - queued + - in_progress + - requires_action + - cancelling + - cancelled + - failed + - completed + - incomplete + - expired + required_action: + type: object + description: >- + Details on the action required to continue the run. Will be `null` + if no action is required. + nullable: true + properties: + type: + description: For now, this is always `submit_tool_outputs`. + type: string + enum: + - submit_tool_outputs + x-stainless-const: true + submit_tool_outputs: + type: object + description: Details on the tool outputs needed for this run to continue. + properties: + tool_calls: + type: array + description: A list of the relevant tool calls. + items: + $ref: '#/components/schemas/RunToolCallObject' + required: + - tool_calls + required: + - type + - submit_tool_outputs + last_error: + type: object + description: >- + The last error associated with this run. Will be `null` if there are + no errors. + nullable: true + properties: + code: + type: string + description: >- + One of `server_error`, `rate_limit_exceeded`, or + `invalid_prompt`. + enum: + - server_error + - rate_limit_exceeded + - invalid_prompt + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + expires_at: + description: The Unix timestamp (in seconds) for when the run will expire. + type: integer + nullable: true + started_at: + description: The Unix timestamp (in seconds) for when the run was started. + type: integer + nullable: true + cancelled_at: + description: The Unix timestamp (in seconds) for when the run was cancelled. + type: integer + nullable: true + failed_at: + description: The Unix timestamp (in seconds) for when the run failed. + type: integer + nullable: true + completed_at: + description: The Unix timestamp (in seconds) for when the run was completed. + type: integer + nullable: true + incomplete_details: + description: >- + Details on why the run is incomplete. Will be `null` if the run is + not incomplete. + type: object + nullable: true + properties: + reason: + description: >- + The reason why the run is incomplete. This will point to which + specific token limit was reached over the course of the run. + type: string + enum: + - max_completion_tokens + - max_prompt_tokens + model: + description: >- + The model that the [assistant](/docs/api-reference/assistants) used + for this run. + type: string + instructions: + description: >- + The instructions that the + [assistant](/docs/api-reference/assistants) used for this run. + type: string + tools: + description: >- + The list of tools that the + [assistant](/docs/api-reference/assistants) used for this run. + default: [] + type: array + maxItems: 20 + items: + oneOf: + - $ref: '#/components/schemas/AssistantToolsCode' + - $ref: '#/components/schemas/AssistantToolsFileSearch' + - $ref: '#/components/schemas/AssistantToolsFunction' + metadata: + $ref: '#/components/schemas/Metadata' + usage: + $ref: '#/components/schemas/RunCompletionUsage' + temperature: + description: >- + The sampling temperature used for this run. If not set, defaults to + 1. + type: number + nullable: true + top_p: + description: >- + The nucleus sampling value used for this run. If not set, defaults + to 1. + type: number + nullable: true + max_prompt_tokens: + type: integer + nullable: true + description: > + The maximum number of prompt tokens specified to have been used over + the course of the run. + minimum: 256 + max_completion_tokens: + type: integer + nullable: true + description: > + The maximum number of completion tokens specified to have been used + over the course of the run. + minimum: 256 + truncation_strategy: + allOf: + - $ref: '#/components/schemas/TruncationObject' + - nullable: true + tool_choice: + allOf: + - $ref: '#/components/schemas/AssistantsApiToolChoiceOption' + - nullable: true + parallel_tool_calls: + $ref: '#/components/schemas/ParallelToolCalls' + response_format: + $ref: '#/components/schemas/AssistantsApiResponseFormatOption' + nullable: true + required: + - id + - object + - created_at + - thread_id + - assistant_id + - status + - required_action + - last_error + - expires_at + - started_at + - cancelled_at + - failed_at + - completed_at + - model + - instructions + - tools + - metadata + - usage + - incomplete_details + - max_prompt_tokens + - max_completion_tokens + - truncation_strategy + - tool_choice + - parallel_tool_calls + - response_format + x-oaiMeta: + name: The run object + beta: true + example: | + { + "id": "run_abc123", + "object": "thread.run", + "created_at": 1698107661, + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "status": "completed", + "started_at": 1699073476, + "expires_at": null, + "cancelled_at": null, + "failed_at": null, + "completed_at": 1699073498, + "last_error": null, + "model": "gpt-4o", + "instructions": null, + "tools": [{"type": "file_search"}, {"type": "code_interpreter"}], + "metadata": {}, + "incomplete_details": null, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + }, + "temperature": 1.0, + "top_p": 1.0, + "max_prompt_tokens": 1000, + "max_completion_tokens": 1000, + "truncation_strategy": { + "type": "auto", + "last_messages": null + }, + "response_format": "auto", + "tool_choice": "auto", + "parallel_tool_calls": true + } + RunStepCompletionUsage: + anyOf: + - type: object + description: >- + Usage statistics related to the run step. This value will be `null` + while the run step's status is `in_progress`. + properties: + completion_tokens: + type: integer + description: >- + Number of completion tokens used over the course of the run + step. + prompt_tokens: + type: integer + description: Number of prompt tokens used over the course of the run step. + total_tokens: + type: integer + description: Total number of tokens used (prompt + completion). + required: + - prompt_tokens + - completion_tokens + - total_tokens + - type: 'null' + RunStepDeltaObject: + type: object + title: Run step delta object + description: > + Represents a run step delta i.e. any changed fields on a run step during + streaming. + properties: + id: + description: >- + The identifier of the run step, which can be referenced in API + endpoints. + type: string + object: + description: The object type, which is always `thread.run.step.delta`. + type: string + enum: + - thread.run.step.delta + x-stainless-const: true + delta: + description: The delta containing the fields that have changed on the run step. + type: object + properties: + step_details: + type: object + description: The details of the run step. + oneOf: + - $ref: >- + #/components/schemas/RunStepDeltaStepDetailsMessageCreationObject + - $ref: '#/components/schemas/RunStepDeltaStepDetailsToolCallsObject' + required: + - id + - object + - delta + x-oaiMeta: + name: The run step delta object + beta: true + example: | + { + "id": "step_123", + "object": "thread.run.step.delta", + "delta": { + "step_details": { + "type": "tool_calls", + "tool_calls": [ + { + "index": 0, + "id": "call_123", + "type": "code_interpreter", + "code_interpreter": { "input": "", "outputs": [] } + } + ] + } + } + } + RunStepDeltaStepDetailsMessageCreationObject: + title: Message creation + type: object + description: Details of the message creation by the run step. + properties: + type: + description: Always `message_creation`. + type: string + enum: + - message_creation + x-stainless-const: true + message_creation: + type: object + properties: + message_id: + type: string + description: The ID of the message that was created by this run step. + required: + - type + RunStepDeltaStepDetailsToolCallsCodeObject: + title: Code interpreter tool call + type: object + description: Details of the Code Interpreter tool call the run step was involved in. + properties: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: + type: string + description: The ID of the tool call. + type: + type: string + description: >- + The type of tool call. This is always going to be `code_interpreter` + for this type of tool call. + enum: + - code_interpreter + x-stainless-const: true + code_interpreter: + type: object + description: The Code Interpreter tool call definition. + properties: + input: + type: string + description: The input to the Code Interpreter tool call. + outputs: + type: array + description: >- + The outputs from the Code Interpreter tool call. Code + Interpreter can output one or more items, including text + (`logs`) or images (`image`). Each of these are represented by a + different object type. + items: + type: object + oneOf: + - $ref: >- + #/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject + - $ref: >- + #/components/schemas/RunStepDeltaStepDetailsToolCallsCodeOutputImageObject + required: + - index + - type + RunStepDeltaStepDetailsToolCallsCodeOutputImageObject: + title: Code interpreter image output + type: object + properties: + index: + type: integer + description: The index of the output in the outputs array. + type: + description: Always `image`. + type: string + enum: + - image + x-stainless-const: true + image: + type: object + properties: + file_id: + description: The [file](/docs/api-reference/files) ID of the image. + type: string + required: + - index + - type + RunStepDeltaStepDetailsToolCallsCodeOutputLogsObject: + title: Code interpreter log output + type: object + description: Text output from the Code Interpreter tool call as part of a run step. + properties: + index: + type: integer + description: The index of the output in the outputs array. + type: + description: Always `logs`. + type: string + enum: + - logs + x-stainless-const: true + logs: + type: string + description: The text output from the Code Interpreter tool call. + required: + - index + - type + RunStepDeltaStepDetailsToolCallsFileSearchObject: + title: File search tool call + type: object + properties: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: >- + The type of tool call. This is always going to be `file_search` for + this type of tool call. + enum: + - file_search + x-stainless-const: true + file_search: + type: object + description: For now, this is always going to be an empty object. + x-oaiTypeLabel: map + required: + - index + - type + - file_search + RunStepDeltaStepDetailsToolCallsFunctionObject: + type: object + title: Function tool call + properties: + index: + type: integer + description: The index of the tool call in the tool calls array. + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: >- + The type of tool call. This is always going to be `function` for + this type of tool call. + enum: + - function + x-stainless-const: true + function: + type: object + description: The definition of the function that was called. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: The arguments passed to the function. + output: + anyOf: + - type: string + description: >- + The output of the function. This will be `null` if the + outputs have not been + [submitted](/docs/api-reference/runs/submitToolOutputs) yet. + - type: 'null' + required: + - index + - type + RunStepDeltaStepDetailsToolCallsObject: + title: Tool calls + type: object + description: Details of the tool call. + properties: + type: + description: Always `tool_calls`. + type: string + enum: + - tool_calls + x-stainless-const: true + tool_calls: + type: array + description: > + An array of tool calls the run step was involved in. These can be + associated with one of three types of tools: `code_interpreter`, + `file_search`, or `function`. + items: + oneOf: + - $ref: >- + #/components/schemas/RunStepDeltaStepDetailsToolCallsCodeObject + - $ref: >- + #/components/schemas/RunStepDeltaStepDetailsToolCallsFileSearchObject + - $ref: >- + #/components/schemas/RunStepDeltaStepDetailsToolCallsFunctionObject + required: + - type + RunStepDetailsMessageCreationObject: + title: Message creation + type: object + description: Details of the message creation by the run step. + properties: + type: + description: Always `message_creation`. + type: string + enum: + - message_creation + x-stainless-const: true + message_creation: + type: object + properties: + message_id: + type: string + description: The ID of the message that was created by this run step. + required: + - message_id + required: + - type + - message_creation + RunStepDetailsToolCallsCodeObject: + title: Code Interpreter tool call + type: object + description: Details of the Code Interpreter tool call the run step was involved in. + properties: + id: + type: string + description: The ID of the tool call. + type: + type: string + description: >- + The type of tool call. This is always going to be `code_interpreter` + for this type of tool call. + enum: + - code_interpreter + x-stainless-const: true + code_interpreter: + type: object + description: The Code Interpreter tool call definition. + required: + - input + - outputs + properties: + input: + type: string + description: The input to the Code Interpreter tool call. + outputs: + type: array + description: >- + The outputs from the Code Interpreter tool call. Code + Interpreter can output one or more items, including text + (`logs`) or images (`image`). Each of these are represented by a + different object type. + items: + type: object + oneOf: + - $ref: >- + #/components/schemas/RunStepDetailsToolCallsCodeOutputLogsObject + - $ref: >- + #/components/schemas/RunStepDetailsToolCallsCodeOutputImageObject + required: + - id + - type + - code_interpreter + RunStepDetailsToolCallsCodeOutputImageObject: + title: Code Interpreter image output + type: object + properties: + type: + description: Always `image`. + type: string + enum: + - image + x-stainless-const: true + image: + type: object + properties: + file_id: + description: The [file](/docs/api-reference/files) ID of the image. + type: string + required: + - file_id + required: + - type + - image + RunStepDetailsToolCallsCodeOutputLogsObject: + title: Code Interpreter log output + type: object + description: Text output from the Code Interpreter tool call as part of a run step. + properties: + type: + description: Always `logs`. + type: string + enum: + - logs + x-stainless-const: true + logs: + type: string + description: The text output from the Code Interpreter tool call. + required: + - type + - logs + RunStepDetailsToolCallsFileSearchObject: + title: File search tool call + type: object + properties: + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: >- + The type of tool call. This is always going to be `file_search` for + this type of tool call. + enum: + - file_search + x-stainless-const: true + file_search: + type: object + description: For now, this is always going to be an empty object. + x-oaiTypeLabel: map + properties: + ranking_options: + $ref: >- + #/components/schemas/RunStepDetailsToolCallsFileSearchRankingOptionsObject + results: + type: array + description: The results of the file search. + items: + $ref: >- + #/components/schemas/RunStepDetailsToolCallsFileSearchResultObject + required: + - id + - type + - file_search + RunStepDetailsToolCallsFileSearchRankingOptionsObject: + title: File search tool call ranking options + type: object + description: The ranking options for the file search. + properties: + ranker: + $ref: '#/components/schemas/FileSearchRanker' + score_threshold: + type: number + description: >- + The score threshold for the file search. All values must be a + floating point number between 0 and 1. + minimum: 0 + maximum: 1 + required: + - ranker + - score_threshold + RunStepDetailsToolCallsFileSearchResultObject: + title: File search tool call result + type: object + description: A result instance of the file search. + x-oaiTypeLabel: map + properties: + file_id: + type: string + description: The ID of the file that result was found in. + file_name: + type: string + description: The name of the file that result was found in. + score: + type: number + description: >- + The score of the result. All values must be a floating point number + between 0 and 1. + minimum: 0 + maximum: 1 + content: + type: array + description: >- + The content of the result that was found. The content is only + included if requested via the include query parameter. + items: + type: object + properties: + type: + type: string + description: The type of the content. + enum: + - text + x-stainless-const: true + text: + type: string + description: The text content of the file. + required: + - file_id + - file_name + - score + RunStepDetailsToolCallsFunctionObject: + type: object + title: Function tool call + properties: + id: + type: string + description: The ID of the tool call object. + type: + type: string + description: >- + The type of tool call. This is always going to be `function` for + this type of tool call. + enum: + - function + x-stainless-const: true + function: + type: object + description: The definition of the function that was called. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: The arguments passed to the function. + output: + anyOf: + - type: string + description: >- + The output of the function. This will be `null` if the + outputs have not been + [submitted](/docs/api-reference/runs/submitToolOutputs) yet. + - type: 'null' + required: + - name + - arguments + - output + required: + - id + - type + - function + RunStepDetailsToolCallsObject: + title: Tool calls + type: object + description: Details of the tool call. + properties: + type: + description: Always `tool_calls`. + type: string + enum: + - tool_calls + x-stainless-const: true + tool_calls: + type: array + description: > + An array of tool calls the run step was involved in. These can be + associated with one of three types of tools: `code_interpreter`, + `file_search`, or `function`. + items: + oneOf: + - $ref: '#/components/schemas/RunStepDetailsToolCallsCodeObject' + - $ref: '#/components/schemas/RunStepDetailsToolCallsFileSearchObject' + - $ref: '#/components/schemas/RunStepDetailsToolCallsFunctionObject' + required: + - type + - tool_calls + RunStepObject: + type: object + title: Run steps + description: | + Represents a step in execution of a run. + properties: + id: + description: >- + The identifier of the run step, which can be referenced in API + endpoints. + type: string + object: + description: The object type, which is always `thread.run.step`. + type: string + enum: + - thread.run.step + x-stainless-const: true + created_at: + description: The Unix timestamp (in seconds) for when the run step was created. + type: integer + assistant_id: + description: >- + The ID of the [assistant](/docs/api-reference/assistants) associated + with the run step. + type: string + thread_id: + description: The ID of the [thread](/docs/api-reference/threads) that was run. + type: string + run_id: + description: >- + The ID of the [run](/docs/api-reference/runs) that this run step is + a part of. + type: string + type: + description: >- + The type of run step, which can be either `message_creation` or + `tool_calls`. + type: string + enum: + - message_creation + - tool_calls + status: + description: >- + The status of the run step, which can be either `in_progress`, + `cancelled`, `failed`, `completed`, or `expired`. + type: string + enum: + - in_progress + - cancelled + - failed + - completed + - expired + step_details: + type: object + description: The details of the run step. + oneOf: + - $ref: '#/components/schemas/RunStepDetailsMessageCreationObject' + - $ref: '#/components/schemas/RunStepDetailsToolCallsObject' + last_error: + anyOf: + - type: object + description: >- + The last error associated with this run step. Will be `null` if + there are no errors. + properties: + code: + type: string + description: One of `server_error` or `rate_limit_exceeded`. + enum: + - server_error + - rate_limit_exceeded + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + - type: 'null' + expired_at: + anyOf: + - description: >- + The Unix timestamp (in seconds) for when the run step expired. A + step is considered expired if the parent run is expired. + type: integer + - type: 'null' + cancelled_at: + anyOf: + - description: >- + The Unix timestamp (in seconds) for when the run step was + cancelled. + type: integer + - type: 'null' + failed_at: + anyOf: + - description: The Unix timestamp (in seconds) for when the run step failed. + type: integer + - type: 'null' + completed_at: + anyOf: + - description: The Unix timestamp (in seconds) for when the run step completed. + type: integer + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + usage: + $ref: '#/components/schemas/RunStepCompletionUsage' + required: + - id + - object + - created_at + - assistant_id + - thread_id + - run_id + - type + - status + - step_details + - last_error + - expired_at + - cancelled_at + - failed_at + - completed_at + - metadata + - usage + x-oaiMeta: + name: The run step object + beta: true + example: | + { + "id": "step_abc123", + "object": "thread.run.step", + "created_at": 1699063291, + "run_id": "run_abc123", + "assistant_id": "asst_abc123", + "thread_id": "thread_abc123", + "type": "message_creation", + "status": "completed", + "cancelled_at": null, + "completed_at": 1699063291, + "expired_at": null, + "failed_at": null, + "last_error": null, + "step_details": { + "type": "message_creation", + "message_creation": { + "message_id": "msg_abc123" + } + }, + "usage": { + "prompt_tokens": 123, + "completion_tokens": 456, + "total_tokens": 579 + } + } + RunStepStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: + - thread.run.step.created + x-stainless-const: true + data: + $ref: '#/components/schemas/RunStepObject' + required: + - event + - data + description: >- + Occurs when a [run step](/docs/api-reference/run-steps/step-object) + is created. + x-oaiMeta: + dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.step.in_progress + x-stainless-const: true + data: + $ref: '#/components/schemas/RunStepObject' + required: + - event + - data + description: >- + Occurs when a [run step](/docs/api-reference/run-steps/step-object) + moves to an `in_progress` state. + x-oaiMeta: + dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.step.delta + x-stainless-const: true + data: + $ref: '#/components/schemas/RunStepDeltaObject' + required: + - event + - data + description: >- + Occurs when parts of a [run + step](/docs/api-reference/run-steps/step-object) are being streamed. + x-oaiMeta: + dataDescription: >- + `data` is a [run step + delta](/docs/api-reference/assistants-streaming/run-step-delta-object) + - type: object + properties: + event: + type: string + enum: + - thread.run.step.completed + x-stainless-const: true + data: + $ref: '#/components/schemas/RunStepObject' + required: + - event + - data + description: >- + Occurs when a [run step](/docs/api-reference/run-steps/step-object) + is completed. + x-oaiMeta: + dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.step.failed + x-stainless-const: true + data: + $ref: '#/components/schemas/RunStepObject' + required: + - event + - data + description: >- + Occurs when a [run step](/docs/api-reference/run-steps/step-object) + fails. + x-oaiMeta: + dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.step.cancelled + x-stainless-const: true + data: + $ref: '#/components/schemas/RunStepObject' + required: + - event + - data + description: >- + Occurs when a [run step](/docs/api-reference/run-steps/step-object) + is cancelled. + x-oaiMeta: + dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.step.expired + x-stainless-const: true + data: + $ref: '#/components/schemas/RunStepObject' + required: + - event + - data + description: >- + Occurs when a [run step](/docs/api-reference/run-steps/step-object) + expires. + x-oaiMeta: + dataDescription: '`data` is a [run step](/docs/api-reference/run-steps/step-object)' + RunStreamEvent: + oneOf: + - type: object + properties: + event: + type: string + enum: + - thread.run.created + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: Occurs when a new [run](/docs/api-reference/runs/object) is created. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.queued + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: >- + Occurs when a [run](/docs/api-reference/runs/object) moves to a + `queued` status. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.in_progress + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: >- + Occurs when a [run](/docs/api-reference/runs/object) moves to an + `in_progress` status. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.requires_action + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: >- + Occurs when a [run](/docs/api-reference/runs/object) moves to a + `requires_action` status. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.completed + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) is completed. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.incomplete + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: >- + Occurs when a [run](/docs/api-reference/runs/object) ends with + status `incomplete`. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.failed + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) fails. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.cancelling + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: >- + Occurs when a [run](/docs/api-reference/runs/object) moves to a + `cancelling` status. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.cancelled + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) is cancelled. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + - type: object + properties: + event: + type: string + enum: + - thread.run.expired + x-stainless-const: true + data: + $ref: '#/components/schemas/RunObject' + required: + - event + - data + description: Occurs when a [run](/docs/api-reference/runs/object) expires. + x-oaiMeta: + dataDescription: '`data` is a [run](/docs/api-reference/runs/object)' + RunToolCallObject: + type: object + description: Tool call objects + properties: + id: + type: string + description: >- + The ID of the tool call. This ID must be referenced when you submit + the tool outputs in using the [Submit tool outputs to + run](/docs/api-reference/runs/submitToolOutputs) endpoint. + type: + type: string + description: >- + The type of tool call the output is required for. For now, this is + always `function`. + enum: + - function + x-stainless-const: true + function: + type: object + description: The function definition. + properties: + name: + type: string + description: The name of the function. + arguments: + type: string + description: >- + The arguments that the model expects you to pass to the + function. + required: + - name + - arguments + required: + - id + - type + - function + ServiceTier: + anyOf: + - type: string + description: | + Specifies the processing type used for serving the request. + - If set to 'auto', then the request will be processed with the service tier configured in the Project settings. Unless otherwise configured, the Project will use 'default'. + - If set to 'default', then the request will be processed with the standard pricing and performance for the selected model. + - If set to '[flex](/docs/guides/flex-processing)' or '[priority](https://openai.com/api-priority-processing/)', then the request will be processed with the corresponding service tier. + - When not set, the default behavior is 'auto'. + + When the `service_tier` parameter is set, the response body will include the `service_tier` value based on the processing mode actually used to serve the request. This response value may be different from the value set in the parameter. + enum: + - auto + - default + - flex + - scale + - priority + default: auto + - type: 'null' + SpeechAudioDeltaEvent: + type: object + description: Emitted for each chunk of audio data generated during speech synthesis. + properties: + type: + type: string + description: | + The type of the event. Always `speech.audio.delta`. + enum: + - speech.audio.delta + x-stainless-const: true + audio: + type: string + description: | + A chunk of Base64-encoded audio data. + required: + - type + - audio + x-oaiMeta: + name: Stream Event (speech.audio.delta) + group: speech + example: | + { + "type": "speech.audio.delta", + "audio": "base64-encoded-audio-data" + } + SpeechAudioDoneEvent: + type: object + description: >- + Emitted when the speech synthesis is complete and all audio has been + streamed. + properties: + type: + type: string + description: | + The type of the event. Always `speech.audio.done`. + enum: + - speech.audio.done + x-stainless-const: true + usage: + type: object + description: | + Token usage statistics for the request. + properties: + input_tokens: + type: integer + description: Number of input tokens in the prompt. + output_tokens: + type: integer + description: Number of output tokens generated. + total_tokens: + type: integer + description: Total number of tokens used (input + output). + required: + - input_tokens + - output_tokens + - total_tokens + required: + - type + - usage + x-oaiMeta: + name: Stream Event (speech.audio.done) + group: speech + example: | + { + "type": "speech.audio.done", + "usage": { + "input_tokens": 14, + "output_tokens": 101, + "total_tokens": 115 + } + } + StaticChunkingStrategy: + type: object + additionalProperties: false + properties: + max_chunk_size_tokens: + type: integer + minimum: 100 + maximum: 4096 + description: >- + The maximum number of tokens in each chunk. The default value is + `800`. The minimum value is `100` and the maximum value is `4096`. + chunk_overlap_tokens: + type: integer + description: > + The number of tokens that overlap between chunks. The default value + is `400`. + + + Note that the overlap must not exceed half of + `max_chunk_size_tokens`. + required: + - max_chunk_size_tokens + - chunk_overlap_tokens + StaticChunkingStrategyRequestParam: + type: object + title: Static Chunking Strategy + description: >- + Customize your own chunking strategy by setting chunk size and chunk + overlap. + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: + - static + x-stainless-const: true + static: + $ref: '#/components/schemas/StaticChunkingStrategy' + required: + - type + - static + StaticChunkingStrategyResponseParam: + type: object + title: Static Chunking Strategy + additionalProperties: false + properties: + type: + type: string + description: Always `static`. + enum: + - static + x-stainless-const: true + static: + $ref: '#/components/schemas/StaticChunkingStrategy' + required: + - type + - static + StopConfiguration: + description: | + Not supported with latest reasoning models `o3` and `o4-mini`. + + Up to 4 sequences where the API will stop generating further tokens. The + returned text will not contain the stop sequence. + default: null + nullable: true + oneOf: + - type: string + default: <|endoftext|> + example: |+ + + nullable: true + - type: array + minItems: 1 + maxItems: 4 + items: + type: string + example: '["\n"]' + SubmitToolOutputsRunRequest: + type: object + additionalProperties: false + properties: + tool_outputs: + description: A list of tools for which the outputs are being submitted. + type: array + items: + type: object + properties: + tool_call_id: + type: string + description: >- + The ID of the tool call in the `required_action` object within + the run object the output is being submitted for. + output: + type: string + description: >- + The output of the tool call to be submitted to continue the + run. + stream: + anyOf: + - type: boolean + description: > + If `true`, returns a stream of events that happen during the Run + as server-sent events, terminating when the Run enters a + terminal state with a `data: [DONE]` message. + - type: 'null' + required: + - tool_outputs + TextResponseFormatConfiguration: + description: > + An object specifying the format that the model must output. + + + Configuring `{ "type": "json_schema" }` enables Structured Outputs, + + which ensures the model will match your supplied JSON schema. Learn more + in the + + [Structured Outputs guide](/docs/guides/structured-outputs). + + + The default format is `{ "type": "text" }` with no additional options. + + + **Not recommended for gpt-4o and newer models:** + + + Setting to `{ "type": "json_object" }` enables the older JSON mode, + which + + ensures the message the model generates is valid JSON. Using + `json_schema` + + is preferred for models that support it. + oneOf: + - $ref: '#/components/schemas/ResponseFormatText' + - $ref: '#/components/schemas/TextResponseFormatJsonSchema' + - $ref: '#/components/schemas/ResponseFormatJsonObject' + TextResponseFormatJsonSchema: + type: object + title: JSON schema + description: | + JSON Schema response format. Used to generate structured JSON responses. + Learn more about [Structured Outputs](/docs/guides/structured-outputs). + properties: + type: + type: string + description: The type of response format being defined. Always `json_schema`. + enum: + - json_schema + x-stainless-const: true + description: + type: string + description: > + A description of what the response format is for, used by the model + to + + determine how to respond in the format. + name: + type: string + description: | + The name of the response format. Must be a-z, A-Z, 0-9, or contain + underscores and dashes, with a maximum length of 64. + schema: + $ref: '#/components/schemas/ResponseFormatJsonSchemaSchema' + strict: + anyOf: + - type: boolean + default: false + description: > + 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). + - type: 'null' + required: + - type + - schema + - name + ThreadObject: + type: object + title: Thread + description: >- + Represents a thread that contains + [messages](/docs/api-reference/messages). + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `thread`. + type: string + enum: + - thread + x-stainless-const: true + created_at: + description: The Unix timestamp (in seconds) for when the thread was created. + type: integer + tool_resources: + anyOf: + - type: object + description: > + A set of resources that are made available to the assistant's + tools in this thread. The resources are specific to the type of + tool. For example, the `code_interpreter` tool requires a list + of file IDs, while the `file_search` tool requires a list of + vector store IDs. + properties: + code_interpreter: + type: object + properties: + file_ids: + type: array + description: > + A list of [file](/docs/api-reference/files) IDs made + available to the `code_interpreter` tool. There can be a + maximum of 20 files associated with the tool. + default: [] + maxItems: 20 + items: + type: string + file_search: + type: object + properties: + vector_store_ids: + type: array + description: > + The [vector + store](/docs/api-reference/vector-stores/object) + attached to this thread. There can be a maximum of 1 + vector store attached to the thread. + maxItems: 1 + items: + type: string + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + required: + - id + - object + - created_at + - tool_resources + - metadata + x-oaiMeta: + name: The thread object + beta: true + example: | + { + "id": "thread_abc123", + "object": "thread", + "created_at": 1698107661, + "metadata": {} + } + ThreadStreamEvent: + oneOf: + - type: object + properties: + enabled: + type: boolean + description: Whether to enable input audio transcription. + event: + type: string + enum: + - thread.created + x-stainless-const: true + data: + $ref: '#/components/schemas/ThreadObject' + required: + - event + - data + description: >- + Occurs when a new [thread](/docs/api-reference/threads/object) is + created. + x-oaiMeta: + dataDescription: '`data` is a [thread](/docs/api-reference/threads/object)' + ToggleCertificatesRequest: + type: object + properties: + certificate_ids: + type: array + items: + type: string + example: cert_abc + minItems: 1 + maxItems: 10 + required: + - certificate_ids + Tool: + description: | + A tool that can be used to generate a response. + discriminator: + propertyName: type + oneOf: + - $ref: '#/components/schemas/FunctionTool' + - $ref: '#/components/schemas/FileSearchTool' + - $ref: '#/components/schemas/ComputerTool' + - $ref: '#/components/schemas/ComputerUsePreviewTool' + - $ref: '#/components/schemas/WebSearchTool' + - $ref: '#/components/schemas/MCPTool' + - $ref: '#/components/schemas/CodeInterpreterTool' + - $ref: '#/components/schemas/ImageGenTool' + - $ref: '#/components/schemas/LocalShellToolParam' + - $ref: '#/components/schemas/FunctionShellToolParam' + - $ref: '#/components/schemas/CustomToolParam' + - $ref: '#/components/schemas/NamespaceToolParam' + - $ref: '#/components/schemas/ToolSearchToolParam' + - $ref: '#/components/schemas/WebSearchPreviewTool' + - $ref: '#/components/schemas/ApplyPatchToolParam' + ToolChoiceAllowed: + type: object + title: Allowed tools + description: | + Constrains the tools available to the model to a pre-defined set. + properties: + type: + type: string + enum: + - allowed_tools + description: Allowed tool configuration type. Always `allowed_tools`. + x-stainless-const: true + mode: + type: string + enum: + - auto + - required + description: > + Constrains the tools available to the model to a pre-defined set. + + + `auto` allows the model to pick from among the allowed tools and + generate a + + message. + + + `required` requires the model to call one or more of the allowed + tools. + tools: + type: array + description: | + A list of tool definitions that the model should be allowed to call. + + For the Responses API, the list of tool definitions might look like: + ```json + [ + { "type": "function", "name": "get_weather" }, + { "type": "mcp", "server_label": "deepwiki" }, + { "type": "image_generation" } + ] + ``` + items: + type: object + description: | + A tool definition that the model should be allowed to call. + additionalProperties: true + x-oaiExpandable: false + required: + - type + - mode + - tools + ToolChoiceCustom: + type: object + title: Custom tool + description: | + Use this option to force the model to call a specific custom tool. + properties: + type: + type: string + enum: + - custom + description: For custom tool calling, the type is always `custom`. + x-stainless-const: true + name: + type: string + description: The name of the custom tool to call. + required: + - type + - name + ToolChoiceFunction: + type: object + title: Function tool + description: | + Use this option to force the model to call a specific function. + properties: + type: + type: string + enum: + - function + description: For function calling, the type is always `function`. + x-stainless-const: true + name: + type: string + description: The name of the function to call. + required: + - type + - name + ToolChoiceMCP: + type: object + title: MCP tool + description: > + Use this option to force the model to call a specific tool on a remote + MCP server. + properties: + type: + type: string + enum: + - mcp + description: For MCP tools, the type is always `mcp`. + x-stainless-const: true + server_label: + type: string + description: | + The label of the MCP server to use. + name: + anyOf: + - type: string + description: | + The name of the tool to call on the server. + - type: 'null' + required: + - type + - server_label + ToolChoiceOptions: + type: string + title: Tool choice mode + description: > + Controls which (if any) tool is called by the model. + + + `none` means the model will not call any tool and instead generates a + message. + + + `auto` means the model can pick between generating a message or calling + one or + + more tools. + + + `required` means the model must call one or more tools. + enum: + - none + - auto + - required + ToolChoiceParam: + description: | + How the model should select which tool (or tools) to use when generating + a response. See the `tools` parameter to see how to specify which tools + the model can call. + oneOf: + - $ref: '#/components/schemas/ToolChoiceOptions' + - $ref: '#/components/schemas/ToolChoiceAllowed' + - $ref: '#/components/schemas/ToolChoiceTypes' + - $ref: '#/components/schemas/ToolChoiceFunction' + - $ref: '#/components/schemas/ToolChoiceMCP' + - $ref: '#/components/schemas/ToolChoiceCustom' + - $ref: '#/components/schemas/SpecificApplyPatchParam' + - $ref: '#/components/schemas/SpecificFunctionShellParam' + ToolChoiceTypes: + type: object + title: Hosted tool + description: > + Indicates that the model should use a built-in tool to generate a + response. + + [Learn more about built-in tools](/docs/guides/tools). + properties: + type: + type: string + description: | + The type of hosted tool the model should to use. Learn more about + [built-in tools](/docs/guides/tools). + + Allowed values are: + - `file_search` + - `web_search_preview` + - `computer` + - `computer_use_preview` + - `computer_use` + - `code_interpreter` + - `image_generation` + enum: + - file_search + - web_search_preview + - computer + - computer_use_preview + - computer_use + - web_search_preview_2025_03_11 + - image_generation + - code_interpreter + required: + - type + ToolsArray: + type: array + description: > + An array of tools the model may call while generating a response. You + + can specify which tool to use by setting the `tool_choice` parameter. + + + We support the following categories of tools: + + - **Built-in tools**: Tools that are provided by OpenAI that extend the + model's capabilities, like [web search](/docs/guides/tools-web-search) + or [file search](/docs/guides/tools-file-search). Learn more about + [built-in tools](/docs/guides/tools). + - **MCP Tools**: Integrations with third-party systems via custom MCP + servers + or predefined connectors such as Google Drive and SharePoint. Learn more about + [MCP Tools](/docs/guides/tools-connectors-mcp). + - **Function calls (custom tools)**: Functions that are defined by you, + enabling the model to call your own code with strongly typed arguments + and outputs. Learn more about + [function calling](/docs/guides/function-calling). You can also use + custom tools to call your own code. + items: + $ref: '#/components/schemas/Tool' + TranscriptTextDeltaEvent: + type: object + description: >- + Emitted when there is an additional text delta. This is also the first + event emitted when the transcription starts. Only emitted when you + [create a transcription](/docs/api-reference/audio/create-transcription) + with the `Stream` parameter set to `true`. + properties: + type: + type: string + description: | + The type of the event. Always `transcript.text.delta`. + enum: + - transcript.text.delta + x-stainless-const: true + delta: + type: string + description: | + The text delta that was additionally transcribed. + logprobs: + type: array + description: > + The log probabilities of the delta. Only included if you [create a + transcription](/docs/api-reference/audio/create-transcription) with + the `include[]` parameter set to `logprobs`. + items: + type: object + properties: + token: + type: string + description: | + The token that was used to generate the log probability. + logprob: + type: number + description: | + The log probability of the token. + bytes: + type: array + items: + type: integer + description: | + The bytes that were used to generate the log probability. + segment_id: + type: string + description: > + Identifier of the diarized segment that this delta belongs to. Only + present when using `gpt-4o-transcribe-diarize`. + required: + - type + - delta + x-oaiMeta: + name: Stream Event (transcript.text.delta) + group: transcript + example: | + { + "type": "transcript.text.delta", + "delta": " wonderful" + } + TranscriptTextDoneEvent: + type: object + description: >- + Emitted when the transcription is complete. Contains the complete + transcription text. Only emitted when you [create a + transcription](/docs/api-reference/audio/create-transcription) with the + `Stream` parameter set to `true`. + properties: + type: + type: string + description: | + The type of the event. Always `transcript.text.done`. + enum: + - transcript.text.done + x-stainless-const: true + text: + type: string + description: | + The text that was transcribed. + logprobs: + type: array + description: > + The log probabilities of the individual tokens in the transcription. + Only included if you [create a + transcription](/docs/api-reference/audio/create-transcription) with + the `include[]` parameter set to `logprobs`. + items: + type: object + properties: + token: + type: string + description: | + The token that was used to generate the log probability. + logprob: + type: number + description: | + The log probability of the token. + bytes: + type: array + items: + type: integer + description: | + The bytes that were used to generate the log probability. + usage: + $ref: '#/components/schemas/TranscriptTextUsageTokens' + required: + - type + - text + x-oaiMeta: + name: Stream Event (transcript.text.done) + group: transcript + example: | + { + "type": "transcript.text.done", + "text": "I see skies of blue and clouds of white, the bright blessed days, the dark sacred nights, and I think to myself, what a wonderful world.", + "usage": { + "type": "tokens", + "input_tokens": 14, + "input_token_details": { + "text_tokens": 10, + "audio_tokens": 4 + }, + "output_tokens": 31, + "total_tokens": 45 + } + } + TranscriptTextSegmentEvent: + type: object + description: > + Emitted when a diarized transcription returns a completed segment with + speaker information. Only emitted when you [create a + transcription](/docs/api-reference/audio/create-transcription) with + `stream` set to `true` and `response_format` set to `diarized_json`. + properties: + type: + type: string + description: The type of the event. Always `transcript.text.segment`. + enum: + - transcript.text.segment + x-stainless-const: true + id: + type: string + description: Unique identifier for the segment. + start: + type: number + format: float + description: Start timestamp of the segment in seconds. + end: + type: number + format: float + description: End timestamp of the segment in seconds. + text: + type: string + description: Transcript text for this segment. + speaker: + type: string + description: Speaker label for this segment. + required: + - type + - id + - start + - end + - text + - speaker + x-oaiMeta: + name: Stream Event (transcript.text.segment) + group: transcript + example: | + { + "type": "transcript.text.segment", + "id": "seg_002", + "start": 5.2, + "end": 12.8, + "text": "Hi, I need help with diarization.", + "speaker": "A" + } + TranscriptTextUsageDuration: + type: object + title: Duration Usage + description: Usage statistics for models billed by audio input duration. + properties: + type: + type: string + enum: + - duration + description: The type of the usage object. Always `duration` for this variant. + x-stainless-const: true + seconds: + type: number + description: Duration of the input audio in seconds. + required: + - type + - seconds + TranscriptTextUsageTokens: + type: object + title: Token Usage + description: Usage statistics for models billed by token usage. + properties: + type: + type: string + enum: + - tokens + description: The type of the usage object. Always `tokens` for this variant. + x-stainless-const: true + input_tokens: + type: integer + description: Number of input tokens billed for this request. + input_token_details: + type: object + description: Details about the input tokens billed for this request. + properties: + text_tokens: + type: integer + description: Number of text tokens billed for this request. + audio_tokens: + type: integer + description: Number of audio tokens billed for this request. + output_tokens: + type: integer + description: Number of output tokens generated. + total_tokens: + type: integer + description: Total number of tokens used (input + output). + required: + - type + - input_tokens + - output_tokens + - total_tokens + TranscriptionChunkingStrategy: + type: object + description: >- + Controls how the audio is cut into chunks. When set to `"auto"`, the + + server first normalizes loudness and then uses voice activity detection + (VAD) to + + choose boundaries. `server_vad` object can be provided to tweak VAD + detection + + parameters manually. If unset, the audio is transcribed as a single + block. + oneOf: + - type: string + enum: + - auto + default: + - auto + description: > + Automatically set chunking parameters based on the audio. Must be + set to `"auto"`. + x-stainless-const: true + - $ref: '#/components/schemas/VadConfig' + TranscriptionDiarizedSegment: + type: object + description: A segment of diarized transcript text with speaker metadata. + properties: + type: + type: string + description: | + The type of the segment. Always `transcript.text.segment`. + enum: + - transcript.text.segment + x-stainless-const: true + id: + type: string + description: Unique identifier for the segment. + start: + type: number + format: float + description: Start timestamp of the segment in seconds. + end: + type: number + format: float + description: End timestamp of the segment in seconds. + text: + type: string + description: Transcript text for this segment. + speaker: + type: string + description: > + Speaker label for this segment. When known speakers are provided, + the label matches `known_speaker_names[]`. Otherwise speakers are + labeled sequentially using capital letters (`A`, `B`, ...). + required: + - type + - id + - start + - end + - text + - speaker + TranscriptionInclude: + type: string + enum: + - logprobs + default: [] + TranscriptionSegment: + type: object + properties: + id: + type: integer + description: Unique identifier of the segment. + seek: + type: integer + description: Seek offset of the segment. + start: + type: number + format: float + description: Start time of the segment in seconds. + end: + type: number + format: float + description: End time of the segment in seconds. + text: + type: string + description: Text content of the segment. + tokens: + type: array + items: + type: integer + description: Array of token IDs for the text content. + temperature: + type: number + format: float + description: Temperature parameter used for generating the segment. + avg_logprob: + type: number + format: float + description: >- + Average logprob of the segment. If the value is lower than -1, + consider the logprobs failed. + compression_ratio: + type: number + format: float + description: >- + Compression ratio of the segment. If the value is greater than 2.4, + consider the compression failed. + no_speech_prob: + type: number + format: float + description: >- + Probability of no speech in the segment. If the value is higher than + 1.0 and the `avg_logprob` is below -1, consider this segment silent. + required: + - id + - seek + - start + - end + - text + - tokens + - temperature + - avg_logprob + - compression_ratio + - no_speech_prob + TranscriptionWord: + type: object + properties: + word: + type: string + description: The text content of the word. + start: + type: number + format: float + description: Start time of the word in seconds. + end: + type: number + format: float + description: End time of the word in seconds. + required: + - word + - start + - end + TruncationObject: + type: object + title: Thread Truncation Controls + description: >- + Controls for how a thread will be truncated prior to the run. Use this + to control the initial context window of the run. + properties: + type: + type: string + description: >- + The truncation strategy to use for the thread. The default is + `auto`. If set to `last_messages`, the thread will be truncated to + the n most recent messages in the thread. When set to `auto`, + messages in the middle of the thread will be dropped to fit the + context length of the model, `max_prompt_tokens`. + enum: + - auto + - last_messages + last_messages: + anyOf: + - type: integer + description: >- + The number of most recent messages from the thread when + constructing the context for the run. + minimum: 1 + - type: 'null' + required: + - type + UpdateGroupBody: + type: object + description: Request payload for updating the details of an existing group. + properties: + name: + type: string + description: New display name for the group. + minLength: 1 + maxLength: 255 + required: + - name + x-oaiMeta: + example: | + { + "name": "Escalations" + } + UpdateVectorStoreFileAttributesRequest: + type: object + additionalProperties: false + properties: + attributes: + $ref: '#/components/schemas/VectorStoreFileAttributes' + required: + - attributes + x-oaiMeta: + name: Update vector store file attributes request + UpdateVectorStoreRequest: + type: object + additionalProperties: false + properties: + name: + description: The name of the vector store. + type: string + nullable: true + expires_after: + allOf: + - $ref: '#/components/schemas/VectorStoreExpirationAfter' + - nullable: true + metadata: + $ref: '#/components/schemas/Metadata' + UpdateVoiceConsentRequest: + type: object + additionalProperties: false + properties: + name: + type: string + description: The updated label for this consent recording. + required: + - name + Upload: + type: object + title: Upload + description: | + The Upload object can accept byte chunks in the form of Parts. + properties: + id: + type: string + description: >- + The Upload unique identifier, which can be referenced in API + endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the Upload was created. + filename: + type: string + description: The name of the file to be uploaded. + bytes: + type: integer + description: The intended number of bytes to be uploaded. + purpose: + type: string + description: >- + The intended purpose of the file. [Please refer + here](/docs/api-reference/files/object#files/object-purpose) for + acceptable values. + status: + type: string + description: The status of the Upload. + enum: + - pending + - completed + - cancelled + - expired + expires_at: + type: integer + description: The Unix timestamp (in seconds) for when the Upload will expire. + object: + type: string + description: The object type, which is always "upload". + enum: + - upload + x-stainless-const: true + file: + allOf: + - $ref: '#/components/schemas/OpenAIFile' + - nullable: true + description: The ready File object after the Upload is completed. + required: + - bytes + - created_at + - expires_at + - filename + - id + - purpose + - status + x-oaiMeta: + name: The upload object + example: | + { + "id": "upload_abc123", + "object": "upload", + "bytes": 2147483648, + "created_at": 1719184911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + "status": "completed", + "expires_at": 1719127296, + "file": { + "id": "file-xyz321", + "object": "file", + "bytes": 2147483648, + "created_at": 1719186911, + "filename": "training_examples.jsonl", + "purpose": "fine-tune", + } + } + UploadCertificateRequest: + type: object + properties: + name: + type: string + description: An optional name for the certificate + content: + type: string + description: The certificate content in PEM format + required: + - content + UploadPart: + type: object + title: UploadPart + description: > + The upload Part represents a chunk of bytes we can add to an Upload + object. + properties: + id: + type: string + description: >- + The upload Part unique identifier, which can be referenced in API + endpoints. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the Part was created. + upload_id: + type: string + description: The ID of the Upload object that this Part was added to. + object: + type: string + description: The object type, which is always `upload.part`. + enum: + - upload.part + x-stainless-const: true + required: + - created_at + - id + - object + - upload_id + x-oaiMeta: + name: The upload part object + example: | + { + "id": "part_def456", + "object": "upload.part", + "created_at": 1719186911, + "upload_id": "upload_abc123" + } + UsageAudioSpeechesResult: + type: object + description: The aggregated audio speeches usage details of the specific time bucket. + properties: + object: + type: string + enum: + - organization.usage.audio_speeches.result + x-stainless-const: true + characters: + type: integer + description: The number of characters processed. + num_model_requests: + type: integer + description: The count of requests made to the model. + project_id: + anyOf: + - type: string + description: >- + When `group_by=project_id`, this field provides the project ID + of the grouped usage result. + - type: 'null' + user_id: + anyOf: + - type: string + description: >- + When `group_by=user_id`, this field provides the user ID of the + grouped usage result. + - type: 'null' + api_key_id: + anyOf: + - type: string + description: >- + When `group_by=api_key_id`, this field provides the API key ID + of the grouped usage result. + - type: 'null' + model: + anyOf: + - type: string + description: >- + When `group_by=model`, this field provides the model name of the + grouped usage result. + - type: 'null' + required: + - object + - characters + - num_model_requests + x-oaiMeta: + name: Audio speeches usage object + example: | + { + "object": "organization.usage.audio_speeches.result", + "characters": 45, + "num_model_requests": 1, + "project_id": "proj_abc", + "user_id": "user-abc", + "api_key_id": "key_abc", + "model": "tts-1" + } + UsageAudioTranscriptionsResult: + type: object + description: >- + The aggregated audio transcriptions usage details of the specific time + bucket. + properties: + object: + type: string + enum: + - organization.usage.audio_transcriptions.result + x-stainless-const: true + seconds: + type: integer + description: The number of seconds processed. + num_model_requests: + type: integer + description: The count of requests made to the model. + project_id: + anyOf: + - type: string + description: >- + When `group_by=project_id`, this field provides the project ID + of the grouped usage result. + - type: 'null' + user_id: + anyOf: + - type: string + description: >- + When `group_by=user_id`, this field provides the user ID of the + grouped usage result. + - type: 'null' + api_key_id: + anyOf: + - type: string + description: >- + When `group_by=api_key_id`, this field provides the API key ID + of the grouped usage result. + - type: 'null' + model: + anyOf: + - type: string + description: >- + When `group_by=model`, this field provides the model name of the + grouped usage result. + - type: 'null' + required: + - object + - seconds + - num_model_requests + x-oaiMeta: + name: Audio transcriptions usage object + example: | + { + "object": "organization.usage.audio_transcriptions.result", + "seconds": 10, + "num_model_requests": 1, + "project_id": "proj_abc", + "user_id": "user-abc", + "api_key_id": "key_abc", + "model": "tts-1" + } + UsageCodeInterpreterSessionsResult: + type: object + description: >- + The aggregated code interpreter sessions usage details of the specific + time bucket. + properties: + object: + type: string + enum: + - organization.usage.code_interpreter_sessions.result + x-stainless-const: true + num_sessions: + type: integer + description: The number of code interpreter sessions. + project_id: + anyOf: + - type: string + description: >- + When `group_by=project_id`, this field provides the project ID + of the grouped usage result. + - type: 'null' + required: + - object + - sessions + x-oaiMeta: + name: Code interpreter sessions usage object + example: | + { + "object": "organization.usage.code_interpreter_sessions.result", + "num_sessions": 1, + "project_id": "proj_abc" + } + UsageCompletionsResult: + type: object + description: The aggregated completions usage details of the specific time bucket. + properties: + object: + type: string + enum: + - organization.usage.completions.result + x-stainless-const: true + input_tokens: + type: integer + description: >- + The aggregated number of text input tokens used, including cached + tokens. For customers subscribe to scale tier, this includes scale + tier tokens. + input_cached_tokens: + type: integer + description: >- + The aggregated number of text input tokens that has been cached from + previous requests. For customers subscribe to scale tier, this + includes scale tier tokens. + output_tokens: + type: integer + description: >- + The aggregated number of text output tokens used. For customers + subscribe to scale tier, this includes scale tier tokens. + input_audio_tokens: + type: integer + description: >- + The aggregated number of audio input tokens used, including cached + tokens. + output_audio_tokens: + type: integer + description: The aggregated number of audio output tokens used. + num_model_requests: + type: integer + description: The count of requests made to the model. + project_id: + anyOf: + - type: string + description: >- + When `group_by=project_id`, this field provides the project ID + of the grouped usage result. + - type: 'null' + user_id: + anyOf: + - type: string + description: >- + When `group_by=user_id`, this field provides the user ID of the + grouped usage result. + - type: 'null' + api_key_id: + anyOf: + - type: string + description: >- + When `group_by=api_key_id`, this field provides the API key ID + of the grouped usage result. + - type: 'null' + model: + anyOf: + - type: string + description: >- + When `group_by=model`, this field provides the model name of the + grouped usage result. + - type: 'null' + batch: + anyOf: + - type: boolean + description: >- + When `group_by=batch`, this field tells whether the grouped + usage result is batch or not. + - type: 'null' + service_tier: + anyOf: + - type: string + description: >- + When `group_by=service_tier`, this field provides the service + tier of the grouped usage result. + - type: 'null' + required: + - object + - input_tokens + - output_tokens + - num_model_requests + x-oaiMeta: + name: Completions usage object + example: | + { + "object": "organization.usage.completions.result", + "input_tokens": 5000, + "output_tokens": 1000, + "input_cached_tokens": 4000, + "input_audio_tokens": 300, + "output_audio_tokens": 200, + "num_model_requests": 5, + "project_id": "proj_abc", + "user_id": "user-abc", + "api_key_id": "key_abc", + "model": "gpt-4o-mini-2024-07-18", + "batch": false, + "service_tier": "default" + } + UsageEmbeddingsResult: + type: object + description: The aggregated embeddings usage details of the specific time bucket. + properties: + object: + type: string + enum: + - organization.usage.embeddings.result + x-stainless-const: true + input_tokens: + type: integer + description: The aggregated number of input tokens used. + num_model_requests: + type: integer + description: The count of requests made to the model. + project_id: + anyOf: + - type: string + description: >- + When `group_by=project_id`, this field provides the project ID + of the grouped usage result. + - type: 'null' + user_id: + anyOf: + - type: string + description: >- + When `group_by=user_id`, this field provides the user ID of the + grouped usage result. + - type: 'null' + api_key_id: + anyOf: + - type: string + description: >- + When `group_by=api_key_id`, this field provides the API key ID + of the grouped usage result. + - type: 'null' + model: + anyOf: + - type: string + description: >- + When `group_by=model`, this field provides the model name of the + grouped usage result. + - type: 'null' + required: + - object + - input_tokens + - num_model_requests + x-oaiMeta: + name: Embeddings usage object + example: | + { + "object": "organization.usage.embeddings.result", + "input_tokens": 20, + "num_model_requests": 2, + "project_id": "proj_abc", + "user_id": "user-abc", + "api_key_id": "key_abc", + "model": "text-embedding-ada-002-v2" + } + UsageImagesResult: + type: object + description: The aggregated images usage details of the specific time bucket. + properties: + object: + type: string + enum: + - organization.usage.images.result + x-stainless-const: true + images: + type: integer + description: The number of images processed. + num_model_requests: + type: integer + description: The count of requests made to the model. + source: + anyOf: + - type: string + description: >- + When `group_by=source`, this field provides the source of the + grouped usage result, possible values are `image.generation`, + `image.edit`, `image.variation`. + - type: 'null' + size: + anyOf: + - type: string + description: >- + When `group_by=size`, this field provides the image size of the + grouped usage result. + - type: 'null' + project_id: + anyOf: + - type: string + description: >- + When `group_by=project_id`, this field provides the project ID + of the grouped usage result. + - type: 'null' + user_id: + anyOf: + - type: string + description: >- + When `group_by=user_id`, this field provides the user ID of the + grouped usage result. + - type: 'null' + api_key_id: + anyOf: + - type: string + description: >- + When `group_by=api_key_id`, this field provides the API key ID + of the grouped usage result. + - type: 'null' + model: + anyOf: + - type: string + description: >- + When `group_by=model`, this field provides the model name of the + grouped usage result. + - type: 'null' + required: + - object + - images + - num_model_requests + x-oaiMeta: + name: Images usage object + example: | + { + "object": "organization.usage.images.result", + "images": 2, + "num_model_requests": 2, + "size": "1024x1024", + "source": "image.generation", + "project_id": "proj_abc", + "user_id": "user-abc", + "api_key_id": "key_abc", + "model": "dall-e-3" + } + UsageModerationsResult: + type: object + description: The aggregated moderations usage details of the specific time bucket. + properties: + object: + type: string + enum: + - organization.usage.moderations.result + x-stainless-const: true + input_tokens: + type: integer + description: The aggregated number of input tokens used. + num_model_requests: + type: integer + description: The count of requests made to the model. + project_id: + anyOf: + - type: string + description: >- + When `group_by=project_id`, this field provides the project ID + of the grouped usage result. + - type: 'null' + user_id: + anyOf: + - type: string + description: >- + When `group_by=user_id`, this field provides the user ID of the + grouped usage result. + - type: 'null' + api_key_id: + anyOf: + - type: string + description: >- + When `group_by=api_key_id`, this field provides the API key ID + of the grouped usage result. + - type: 'null' + model: + anyOf: + - type: string + description: >- + When `group_by=model`, this field provides the model name of the + grouped usage result. + - type: 'null' + required: + - object + - input_tokens + - num_model_requests + x-oaiMeta: + name: Moderations usage object + example: | + { + "object": "organization.usage.moderations.result", + "input_tokens": 20, + "num_model_requests": 2, + "project_id": "proj_abc", + "user_id": "user-abc", + "api_key_id": "key_abc", + "model": "text-moderation" + } + UsageResponse: + type: object + properties: + object: + type: string + enum: + - page + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/UsageTimeBucket' + has_more: + type: boolean + next_page: + type: string + required: + - object + - data + - has_more + - next_page + UsageTimeBucket: + type: object + properties: + object: + type: string + enum: + - bucket + x-stainless-const: true + start_time: + type: integer + end_time: + type: integer + result: + type: array + items: + oneOf: + - $ref: '#/components/schemas/UsageCompletionsResult' + - $ref: '#/components/schemas/UsageEmbeddingsResult' + - $ref: '#/components/schemas/UsageModerationsResult' + - $ref: '#/components/schemas/UsageImagesResult' + - $ref: '#/components/schemas/UsageAudioSpeechesResult' + - $ref: '#/components/schemas/UsageAudioTranscriptionsResult' + - $ref: '#/components/schemas/UsageVectorStoresResult' + - $ref: '#/components/schemas/UsageCodeInterpreterSessionsResult' + - $ref: '#/components/schemas/CostsResult' + required: + - object + - start_time + - end_time + - result + UsageVectorStoresResult: + type: object + description: The aggregated vector stores usage details of the specific time bucket. + properties: + object: + type: string + enum: + - organization.usage.vector_stores.result + x-stainless-const: true + usage_bytes: + type: integer + description: The vector stores usage in bytes. + project_id: + anyOf: + - type: string + description: >- + When `group_by=project_id`, this field provides the project ID + of the grouped usage result. + - type: 'null' + required: + - object + - usage_bytes + x-oaiMeta: + name: Vector stores usage object + example: | + { + "object": "organization.usage.vector_stores.result", + "usage_bytes": 1024, + "project_id": "proj_abc" + } + User: + type: object + description: Represents an individual `user` within an organization. + properties: + object: + type: string + enum: + - organization.user + description: The object type, which is always `organization.user` + x-stainless-const: true + id: + type: string + description: The identifier, which can be referenced in API endpoints + name: + type: string + description: The name of the user + email: + type: string + description: The email address of the user + role: + type: string + enum: + - owner + - reader + description: '`owner` or `reader`' + added_at: + type: integer + description: The Unix timestamp (in seconds) of when the user was added. + required: + - object + - id + - name + - email + - role + - added_at + x-oaiMeta: + name: The user object + example: | + { + "object": "organization.user", + "id": "user_abc", + "name": "First Last", + "email": "user@example.com", + "role": "owner", + "added_at": 1711471533 + } + UserDeleteResponse: + type: object + properties: + object: + type: string + enum: + - organization.user.deleted + x-stainless-const: true + id: + type: string + deleted: + type: boolean + required: + - object + - id + - deleted + UserListResource: + type: object + description: >- + Paginated list of user objects returned when inspecting group + membership. + properties: + object: + type: string + enum: + - list + description: Always `list`. + x-stainless-const: true + data: + type: array + description: Users in the current page. + items: + $ref: '#/components/schemas/User' + has_more: + type: boolean + description: Whether more users are available when paginating. + next: + description: >- + Cursor to fetch the next page of results, or `null` when no further + users are available. + anyOf: + - type: string + - type: 'null' + required: + - object + - data + - has_more + - next + x-oaiMeta: + name: Group user list + example: | + { + "object": "list", + "data": [ + { + "object": "organization.user", + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com", + "role": "owner", + "added_at": 1711471533 + } + ], + "has_more": false, + "next": null + } + UserListResponse: + type: object + properties: + object: + type: string + enum: + - list + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/User' + first_id: + type: string + last_id: + type: string + has_more: + type: boolean + required: + - object + - data + - first_id + - last_id + - has_more + UserRoleAssignment: + type: object + description: Role assignment linking a user to a role. + properties: + object: + type: string + enum: + - user.role + description: Always `user.role`. + x-stainless-const: true + user: + $ref: '#/components/schemas/User' + role: + $ref: '#/components/schemas/Role' + required: + - object + - user + - role + x-oaiMeta: + name: The user role object + example: | + { + "object": "user.role", + "user": { + "object": "organization.user", + "id": "user_abc123", + "name": "Ada Lovelace", + "email": "ada@example.com", + "role": "owner", + "added_at": 1711470000 + }, + "role": { + "object": "role", + "id": "role_01J1F8ROLE01", + "name": "API Group Manager", + "description": "Allows managing organization groups", + "permissions": [ + "api.groups.read", + "api.groups.write" + ], + "resource_type": "api.organization", + "predefined_role": false + } + } + UserRoleUpdateRequest: + type: object + properties: + role: + type: string + enum: + - owner + - reader + description: '`owner` or `reader`' + required: + - role + VadConfig: + type: object + additionalProperties: false + required: + - type + properties: + type: + type: string + enum: + - server_vad + description: >- + Must be set to `server_vad` to enable manual chunking using server + side VAD. + prefix_padding_ms: + type: integer + default: 300 + description: | + Amount of audio to include before the VAD detected speech (in + milliseconds). + silence_duration_ms: + type: integer + default: 200 + description: | + Duration of silence to detect speech stop (in milliseconds). + With shorter values the model will respond more quickly, + but may jump in on short pauses from the user. + threshold: + type: number + default: 0.5 + description: > + Sensitivity threshold (0.0 to 1.0) for voice activity detection. A + + higher threshold will require louder audio to activate the model, + and + + thus might perform better in noisy environments. + ValidateGraderRequest: + type: object + title: ValidateGraderRequest + properties: + grader: + type: object + description: The grader used for the fine-tuning job. + oneOf: + - $ref: '#/components/schemas/GraderStringCheck' + - $ref: '#/components/schemas/GraderTextSimilarity' + - $ref: '#/components/schemas/GraderPython' + - $ref: '#/components/schemas/GraderScoreModel' + - $ref: '#/components/schemas/GraderMulti' + required: + - grader + ValidateGraderResponse: + type: object + title: ValidateGraderResponse + properties: + grader: + type: object + description: The grader used for the fine-tuning job. + oneOf: + - $ref: '#/components/schemas/GraderStringCheck' + - $ref: '#/components/schemas/GraderTextSimilarity' + - $ref: '#/components/schemas/GraderPython' + - $ref: '#/components/schemas/GraderScoreModel' + - $ref: '#/components/schemas/GraderMulti' + VectorStoreExpirationAfter: + type: object + title: Vector store expiration policy + description: The expiration policy for a vector store. + properties: + anchor: + description: >- + Anchor timestamp after which the expiration policy applies. + Supported anchors: `last_active_at`. + type: string + enum: + - last_active_at + x-stainless-const: true + days: + description: >- + The number of days after the anchor time that the vector store will + expire. + type: integer + minimum: 1 + maximum: 365 + required: + - anchor + - days + VectorStoreFileAttributes: + anyOf: + - type: object + description: > + Set of 16 key-value pairs that can be attached to an object. This + can be + + useful for storing additional information about the object in a + structured + + format, and querying for objects via API or the dashboard. Keys are + strings + + with a maximum length of 64 characters. Values are strings with a + maximum + + length of 512 characters, booleans, or numbers. + maxProperties: 16 + propertyNames: + type: string + maxLength: 64 + additionalProperties: + oneOf: + - type: string + maxLength: 512 + - type: number + - type: boolean + x-oaiTypeLabel: map + - type: 'null' + VectorStoreFileBatchObject: + type: object + title: Vector store file batch + description: A batch of files attached to a vector store. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `vector_store.file_batch`. + type: string + enum: + - vector_store.files_batch + x-stainless-const: true + created_at: + description: >- + The Unix timestamp (in seconds) for when the vector store files + batch was created. + type: integer + vector_store_id: + description: >- + The ID of the [vector + store](/docs/api-reference/vector-stores/object) that the + [File](/docs/api-reference/files) is attached to. + type: string + status: + description: >- + The status of the vector store files batch, which can be either + `in_progress`, `completed`, `cancelled` or `failed`. + type: string + enum: + - in_progress + - completed + - cancelled + - failed + file_counts: + type: object + properties: + in_progress: + description: The number of files that are currently being processed. + type: integer + completed: + description: The number of files that have been processed. + type: integer + failed: + description: The number of files that have failed to process. + type: integer + cancelled: + description: The number of files that where cancelled. + type: integer + total: + description: The total number of files. + type: integer + required: + - in_progress + - completed + - cancelled + - failed + - total + required: + - id + - object + - created_at + - vector_store_id + - status + - file_counts + x-oaiMeta: + name: The vector store files batch object + beta: true + example: | + { + "id": "vsfb_123", + "object": "vector_store.files_batch", + "created_at": 1698107661, + "vector_store_id": "vs_abc123", + "status": "completed", + "file_counts": { + "in_progress": 0, + "completed": 100, + "failed": 0, + "cancelled": 0, + "total": 100 + } + } + VectorStoreFileContentResponse: + type: object + description: Represents the parsed content of a vector store file. + properties: + object: + type: string + enum: + - vector_store.file_content.page + description: The object type, which is always `vector_store.file_content.page` + x-stainless-const: true + data: + type: array + description: Parsed content of the file. + items: + type: object + properties: + type: + type: string + description: The content type (currently only `"text"`) + text: + type: string + description: The text content + has_more: + type: boolean + description: Indicates if there are more content pages to fetch. + next_page: + anyOf: + - type: string + description: The token for the next page, if any. + - type: 'null' + required: + - object + - data + - has_more + - next_page + VectorStoreFileObject: + type: object + title: Vector store files + description: A list of files attached to a vector store. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `vector_store.file`. + type: string + enum: + - vector_store.file + x-stainless-const: true + usage_bytes: + description: >- + The total vector store usage in bytes. Note that this may be + different from the original file size. + type: integer + created_at: + description: >- + The Unix timestamp (in seconds) for when the vector store file was + created. + type: integer + vector_store_id: + description: >- + The ID of the [vector + store](/docs/api-reference/vector-stores/object) that the + [File](/docs/api-reference/files) is attached to. + type: string + status: + description: >- + The status of the vector store file, which can be either + `in_progress`, `completed`, `cancelled`, or `failed`. The status + `completed` indicates that the vector store file is ready for use. + type: string + enum: + - in_progress + - completed + - cancelled + - failed + last_error: + anyOf: + - type: object + description: >- + The last error associated with this vector store file. Will be + `null` if there are no errors. + properties: + code: + type: string + description: >- + One of `server_error`, `unsupported_file`, or + `invalid_file`. + enum: + - server_error + - unsupported_file + - invalid_file + message: + type: string + description: A human-readable description of the error. + required: + - code + - message + - type: 'null' + chunking_strategy: + type: object + description: The strategy used to chunk the file. + oneOf: + - $ref: '#/components/schemas/StaticChunkingStrategyResponseParam' + - $ref: '#/components/schemas/OtherChunkingStrategyResponseParam' + attributes: + $ref: '#/components/schemas/VectorStoreFileAttributes' + required: + - id + - object + - usage_bytes + - created_at + - vector_store_id + - status + - last_error + x-oaiMeta: + name: The vector store file object + beta: true + example: | + { + "id": "file-abc123", + "object": "vector_store.file", + "usage_bytes": 1234, + "created_at": 1698107661, + "vector_store_id": "vs_abc123", + "status": "completed", + "last_error": null, + "chunking_strategy": { + "type": "static", + "static": { + "max_chunk_size_tokens": 800, + "chunk_overlap_tokens": 400 + } + } + } + VectorStoreObject: + type: object + title: Vector store + description: >- + A vector store is a collection of processed files can be used by the + `file_search` tool. + properties: + id: + description: The identifier, which can be referenced in API endpoints. + type: string + object: + description: The object type, which is always `vector_store`. + type: string + enum: + - vector_store + x-stainless-const: true + created_at: + description: >- + The Unix timestamp (in seconds) for when the vector store was + created. + type: integer + name: + description: The name of the vector store. + type: string + usage_bytes: + description: The total number of bytes used by the files in the vector store. + type: integer + file_counts: + type: object + properties: + in_progress: + description: The number of files that are currently being processed. + type: integer + completed: + description: The number of files that have been successfully processed. + type: integer + failed: + description: The number of files that have failed to process. + type: integer + cancelled: + description: The number of files that were cancelled. + type: integer + total: + description: The total number of files. + type: integer + required: + - in_progress + - completed + - failed + - cancelled + - total + status: + description: >- + The status of the vector store, which can be either `expired`, + `in_progress`, or `completed`. A status of `completed` indicates + that the vector store is ready for use. + type: string + enum: + - expired + - in_progress + - completed + expires_after: + $ref: '#/components/schemas/VectorStoreExpirationAfter' + expires_at: + anyOf: + - description: >- + The Unix timestamp (in seconds) for when the vector store will + expire. + type: integer + - type: 'null' + last_active_at: + anyOf: + - description: >- + The Unix timestamp (in seconds) for when the vector store was + last active. + type: integer + - type: 'null' + metadata: + $ref: '#/components/schemas/Metadata' + required: + - id + - object + - usage_bytes + - created_at + - status + - last_active_at + - name + - file_counts + - metadata + x-oaiMeta: + name: The vector store object + example: | + { + "id": "vs_123", + "object": "vector_store", + "created_at": 1698107661, + "usage_bytes": 123456, + "last_active_at": 1698107661, + "name": "my_vector_store", + "status": "completed", + "file_counts": { + "in_progress": 0, + "completed": 100, + "cancelled": 0, + "failed": 0, + "total": 100 + }, + "last_used_at": 1698107661 + } + VectorStoreSearchRequest: + type: object + additionalProperties: false + properties: + query: + description: A query string for a search + oneOf: + - type: string + - type: array + items: + type: string + description: A list of queries to search for. + minItems: 1 + rewrite_query: + description: Whether to rewrite the natural language query for vector search. + type: boolean + default: false + max_num_results: + description: >- + The maximum number of results to return. This number should be + between 1 and 50 inclusive. + type: integer + default: 10 + minimum: 1 + maximum: 50 + filters: + description: A filter to apply based on file attributes. + oneOf: + - $ref: '#/components/schemas/ComparisonFilter' + - $ref: '#/components/schemas/CompoundFilter' + ranking_options: + description: Ranking options for search. + type: object + additionalProperties: false + properties: + ranker: + description: >- + Enable re-ranking; set to `none` to disable, which can help + reduce latency. + type: string + enum: + - none + - auto + - default-2024-11-15 + default: auto + score_threshold: + type: number + minimum: 0 + maximum: 1 + default: 0 + required: + - query + x-oaiMeta: + name: Vector store search request + VectorStoreSearchResultContentObject: + type: object + additionalProperties: false + properties: + type: + description: The type of content. + type: string + enum: + - text + text: + description: The text content returned from search. + type: string + required: + - type + - text + x-oaiMeta: + name: Vector store search result content object + VectorStoreSearchResultItem: + type: object + additionalProperties: false + properties: + file_id: + type: string + description: The ID of the vector store file. + filename: + type: string + description: The name of the vector store file. + score: + type: number + description: The similarity score for the result. + minimum: 0 + maximum: 1 + attributes: + $ref: '#/components/schemas/VectorStoreFileAttributes' + content: + type: array + description: Content chunks from the file. + items: + $ref: '#/components/schemas/VectorStoreSearchResultContentObject' + required: + - file_id + - filename + - score + - attributes + - content + x-oaiMeta: + name: Vector store search result item + VectorStoreSearchResultsPage: + type: object + additionalProperties: false + properties: + object: + type: string + enum: + - vector_store.search_results.page + description: The object type, which is always `vector_store.search_results.page` + x-stainless-const: true + search_query: + type: array + items: + type: string + description: The query used for this search. + minItems: 1 + data: + type: array + description: The list of search result items. + items: + $ref: '#/components/schemas/VectorStoreSearchResultItem' + has_more: + type: boolean + description: Indicates if there are more results to fetch. + next_page: + anyOf: + - type: string + description: The token for the next page, if any. + - type: 'null' + required: + - object + - search_query + - data + - has_more + - next_page + x-oaiMeta: + name: Vector store search results page + Verbosity: + anyOf: + - type: string + enum: + - low + - medium + - high + default: medium + description: > + Constrains the verbosity of the model's response. Lower values will + result in + + more concise responses, while higher values will result in more + verbose responses. + + Currently supported values are `low`, `medium`, and `high`. + - type: 'null' + VoiceConsentDeletedResource: + type: object + additionalProperties: false + properties: + id: + type: string + description: The consent recording identifier. + example: cons_1234 + object: + type: string + enum: + - audio.voice_consent + x-stainless-const: true + deleted: + type: boolean + required: + - id + - object + - deleted + x-oaiMeta: + name: The voice consent deletion object + example: | + { + "object": "audio.voice_consent", + "id": "cons_1234", + "deleted": true + } + VoiceConsentListResource: + type: object + additionalProperties: false + properties: + object: + type: string + enum: + - list + x-stainless-const: true + data: + type: array + items: + $ref: '#/components/schemas/VoiceConsentResource' + first_id: + anyOf: + - type: string + - type: 'null' + last_id: + anyOf: + - type: string + - type: 'null' + has_more: + type: boolean + required: + - object + - data + - has_more + x-oaiMeta: + name: The voice consent list object + example: | + { + "object": "list", + "data": [ + { + "object": "audio.voice_consent", + "id": "cons_1234", + "name": "John Doe", + "language": "en-US", + "created_at": 1734220800 + } + ], + "first_id": "cons_1234", + "last_id": "cons_1234", + "has_more": false + } + VoiceConsentResource: + type: object + title: Voice consent + description: A consent recording used to authorize creation of a custom voice. + additionalProperties: false + properties: + object: + type: string + description: The object type, which is always `audio.voice_consent`. + enum: + - audio.voice_consent + x-stainless-const: true + id: + type: string + description: The consent recording identifier. + example: cons_1234 + name: + type: string + description: The label provided when the consent recording was uploaded. + language: + type: string + description: >- + The BCP 47 language tag for the consent phrase (for example, + `en-US`). + created_at: + type: integer + description: >- + The Unix timestamp (in seconds) for when the consent recording was + created. + required: + - object + - id + - name + - language + - created_at + x-oaiMeta: + name: The voice consent object + example: | + { + "object": "audio.voice_consent", + "id": "cons_1234", + "name": "John Doe", + "language": "en-US", + "created_at": 1734220800 + } + VoiceIdsOrCustomVoice: + title: Voice + description: | + A built-in voice name or a custom voice reference. + anyOf: + - $ref: '#/components/schemas/VoiceIdsShared' + - type: object + description: Custom voice reference. + additionalProperties: false + required: + - id + properties: + id: + type: string + description: The custom voice ID, e.g. `voice_1234`. + example: voice_1234 + VoiceIdsShared: + example: ash + anyOf: + - type: string + - type: string + enum: + - alloy + - ash + - ballad + - coral + - echo + - sage + - shimmer + - verse + - marin + - cedar + VoiceResource: + type: object + title: Voice + description: A custom voice that can be used for audio output. + additionalProperties: false + properties: + object: + type: string + description: The object type, which is always `audio.voice`. + enum: + - audio.voice + x-stainless-const: true + id: + type: string + description: The voice identifier, which can be referenced in API endpoints. + name: + type: string + description: The name of the voice. + created_at: + type: integer + description: The Unix timestamp (in seconds) for when the voice was created. + required: + - object + - id + - name + - created_at + x-oaiMeta: + name: The voice object + example: | + { + "object": "audio.voice", + "id": "voice_123abc", + "name": "My new voice", + "created_at": 1734220800 + } + WebSearchActionFind: + type: object + title: Find action + description: | + Action type "find_in_page": Searches for a pattern within a loaded page. + properties: + type: + type: string + enum: + - find_in_page + description: | + The action type. + x-stainless-const: true + url: + type: string + format: uri + description: | + The URL of the page searched for the pattern. + pattern: + type: string + description: | + The pattern or text to search for within the page. + required: + - type + - url + - pattern + WebSearchActionOpenPage: + type: object + title: Open page action + description: | + Action type "open_page" - Opens a specific URL from search results. + properties: + type: + type: string + enum: + - open_page + description: | + The action type. + x-stainless-const: true + url: + description: | + The URL opened by the model. + anyOf: + - type: string + format: uri + - type: 'null' + required: + - type + WebSearchActionSearch: + type: object + title: Search action + description: | + Action type "search" - Performs a web search query. + properties: + type: + type: string + enum: + - search + description: | + The action type. + x-stainless-const: true + query: + type: string + description: | + [DEPRECATED] The search query. + queries: + type: array + title: Search queries + description: | + The search queries. + items: + type: string + description: | + A search query. + sources: + type: array + title: Web search sources + description: | + The sources used in the search. + items: + type: object + title: Web search source + description: | + A source used in the search. + properties: + type: + type: string + enum: + - url + description: | + The type of source. Always `url`. + x-stainless-const: true + url: + type: string + description: | + The URL of the source. + required: + - type + - url + required: + - type + - query + WebSearchApproximateLocation: + anyOf: + - type: object + title: Web search approximate location + description: | + The approximate location of the user. + properties: + type: + type: string + enum: + - approximate + description: The type of location approximation. Always `approximate`. + default: approximate + x-stainless-const: true + country: + anyOf: + - type: string + description: >- + The two-letter [ISO country + code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, + e.g. `US`. + - type: 'null' + region: + anyOf: + - type: string + description: >- + Free text input for the region of the user, e.g. + `California`. + - type: 'null' + city: + anyOf: + - type: string + description: >- + Free text input for the city of the user, e.g. `San + Francisco`. + - type: 'null' + timezone: + anyOf: + - type: string + description: >- + The [IANA + timezone](https://timeapi.io/documentation/iana-timezones) + of the user, e.g. `America/Los_Angeles`. + - type: 'null' + - type: 'null' + WebSearchContextSize: + type: string + description: > + High level guidance for the amount of context window space to use for + the + + search. One of `low`, `medium`, or `high`. `medium` is the default. + enum: + - low + - medium + - high + default: medium + WebSearchLocation: + type: object + title: Web search location + description: Approximate location parameters for the search. + properties: + country: + type: string + description: > + The two-letter + + [ISO country code](https://en.wikipedia.org/wiki/ISO_3166-1) of the + user, + + e.g. `US`. + region: + type: string + description: | + Free text input for the region of the user, e.g. `California`. + city: + type: string + description: | + Free text input for the city of the user, e.g. `San Francisco`. + timezone: + type: string + description: > + The [IANA + timezone](https://timeapi.io/documentation/iana-timezones) + + of the user, e.g. `America/Los_Angeles`. + WebSearchTool: + type: object + title: Web search + description: > + Search the Internet for sources related to the prompt. Learn more about + the + + [web search tool](/docs/guides/tools-web-search). + properties: + type: + type: string + enum: + - web_search + - web_search_2025_08_26 + description: >- + The type of the web search tool. One of `web_search` or + `web_search_2025_08_26`. + default: web_search + filters: + anyOf: + - type: object + description: | + Filters for the search. + properties: + allowed_domains: + anyOf: + - type: array + title: Allowed domains for the search. + description: > + 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"]` + items: + type: string + description: Allowed domain for the search. + default: [] + - type: 'null' + - type: 'null' + user_location: + $ref: '#/components/schemas/WebSearchApproximateLocation' + search_context_size: + type: string + enum: + - low + - medium + - high + default: medium + description: >- + High level guidance for the amount of context window space to use + for the search. One of `low`, `medium`, or `high`. `medium` is the + default. + required: + - type + WebSearchToolCall: + type: object + title: Web search tool call + description: | + The results of a web search tool call. See the + [web search guide](/docs/guides/tools-web-search) for more information. + properties: + id: + type: string + description: | + The unique ID of the web search tool call. + type: + type: string + enum: + - web_search_call + description: | + The type of the web search tool call. Always `web_search_call`. + x-stainless-const: true + status: + type: string + description: | + The status of the web search tool call. + enum: + - in_progress + - searching + - completed + - failed + action: + type: object + description: > + An object describing the specific action taken in this web search + call. + + Includes details on how the model used the web (search, open_page, + find_in_page). + oneOf: + - $ref: '#/components/schemas/WebSearchActionSearch' + - $ref: '#/components/schemas/WebSearchActionOpenPage' + - $ref: '#/components/schemas/WebSearchActionFind' + discriminator: + propertyName: type + required: + - id + - type + - status + - action + WebhookBatchCancelled: + type: object + title: batch.cancelled + description: | + Sent when a batch API request has been cancelled. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the batch API request was + cancelled. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the batch API request. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `batch.cancelled`. + enum: + - batch.cancelled + x-stainless-const: true + x-oaiMeta: + name: batch.cancelled + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "batch.cancelled", + "created_at": 1719168000, + "data": { + "id": "batch_abc123" + } + } + WebhookBatchCompleted: + type: object + title: batch.completed + description: | + Sent when a batch API request has been completed. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the batch API request was + completed. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the batch API request. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `batch.completed`. + enum: + - batch.completed + x-stainless-const: true + x-oaiMeta: + name: batch.completed + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "batch.completed", + "created_at": 1719168000, + "data": { + "id": "batch_abc123" + } + } + WebhookBatchExpired: + type: object + title: batch.expired + description: | + Sent when a batch API request has expired. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the batch API request + expired. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the batch API request. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `batch.expired`. + enum: + - batch.expired + x-stainless-const: true + x-oaiMeta: + name: batch.expired + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "batch.expired", + "created_at": 1719168000, + "data": { + "id": "batch_abc123" + } + } + WebhookBatchFailed: + type: object + title: batch.failed + description: | + Sent when a batch API request has failed. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the batch API request + failed. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the batch API request. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `batch.failed`. + enum: + - batch.failed + x-stainless-const: true + x-oaiMeta: + name: batch.failed + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "batch.failed", + "created_at": 1719168000, + "data": { + "id": "batch_abc123" + } + } + WebhookEvalRunCanceled: + type: object + title: eval.run.canceled + description: | + Sent when an eval run has been canceled. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: | + The Unix timestamp (in seconds) of when the eval run was canceled. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the eval run. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `eval.run.canceled`. + enum: + - eval.run.canceled + x-stainless-const: true + x-oaiMeta: + name: eval.run.canceled + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "eval.run.canceled", + "created_at": 1719168000, + "data": { + "id": "evalrun_abc123" + } + } + WebhookEvalRunFailed: + type: object + title: eval.run.failed + description: | + Sent when an eval run has failed. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: | + The Unix timestamp (in seconds) of when the eval run failed. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the eval run. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `eval.run.failed`. + enum: + - eval.run.failed + x-stainless-const: true + x-oaiMeta: + name: eval.run.failed + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "eval.run.failed", + "created_at": 1719168000, + "data": { + "id": "evalrun_abc123" + } + } + WebhookEvalRunSucceeded: + type: object + title: eval.run.succeeded + description: | + Sent when an eval run has succeeded. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: | + The Unix timestamp (in seconds) of when the eval run succeeded. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the eval run. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `eval.run.succeeded`. + enum: + - eval.run.succeeded + x-stainless-const: true + x-oaiMeta: + name: eval.run.succeeded + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "eval.run.succeeded", + "created_at": 1719168000, + "data": { + "id": "evalrun_abc123" + } + } + WebhookFineTuningJobCancelled: + type: object + title: fine_tuning.job.cancelled + description: | + Sent when a fine-tuning job has been cancelled. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the fine-tuning job was + cancelled. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the fine-tuning job. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `fine_tuning.job.cancelled`. + enum: + - fine_tuning.job.cancelled + x-stainless-const: true + x-oaiMeta: + name: fine_tuning.job.cancelled + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "fine_tuning.job.cancelled", + "created_at": 1719168000, + "data": { + "id": "ftjob_abc123" + } + } + WebhookFineTuningJobFailed: + type: object + title: fine_tuning.job.failed + description: | + Sent when a fine-tuning job has failed. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: | + The Unix timestamp (in seconds) of when the fine-tuning job failed. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the fine-tuning job. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `fine_tuning.job.failed`. + enum: + - fine_tuning.job.failed + x-stainless-const: true + x-oaiMeta: + name: fine_tuning.job.failed + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "fine_tuning.job.failed", + "created_at": 1719168000, + "data": { + "id": "ftjob_abc123" + } + } + WebhookFineTuningJobSucceeded: + type: object + title: fine_tuning.job.succeeded + description: | + Sent when a fine-tuning job has succeeded. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the fine-tuning job + succeeded. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the fine-tuning job. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `fine_tuning.job.succeeded`. + enum: + - fine_tuning.job.succeeded + x-stainless-const: true + x-oaiMeta: + name: fine_tuning.job.succeeded + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "fine_tuning.job.succeeded", + "created_at": 1719168000, + "data": { + "id": "ftjob_abc123" + } + } + WebhookRealtimeCallIncoming: + type: object + title: realtime.call.incoming + description: | + Sent when Realtime API Receives a incoming SIP call. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the model response was + completed. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - call_id + - sip_headers + properties: + call_id: + type: string + description: | + The unique ID of this call. + sip_headers: + type: array + description: | + Headers from the SIP Invite. + items: + type: object + description: | + A header from the SIP Invite. + required: + - name + - value + properties: + name: + type: string + description: | + Name of the SIP Header. + value: + type: string + description: | + Value of the SIP Header. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `realtime.call.incoming`. + enum: + - realtime.call.incoming + x-stainless-const: true + x-oaiMeta: + name: realtime.call.incoming + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "realtime.call.incoming", + "created_at": 1719168000, + "data": { + "call_id": "rtc_479a275623b54bdb9b6fbae2f7cbd408", + "sip_headers": [ + {"name": "Max-Forwards", "value": "63"}, + {"name": "CSeq", "value": "851287 INVITE"}, + {"name": "Content-Type", "value": "application/sdp"}, + ] + } + } + WebhookResponseCancelled: + type: object + title: response.cancelled + description: | + Sent when a background response has been cancelled. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the model response was + cancelled. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the model response. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `response.cancelled`. + enum: + - response.cancelled + x-stainless-const: true + x-oaiMeta: + name: response.cancelled + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "response.cancelled", + "created_at": 1719168000, + "data": { + "id": "resp_abc123" + } + } + WebhookResponseCompleted: + type: object + title: response.completed + description: | + Sent when a background response has been completed. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the model response was + completed. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the model response. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `response.completed`. + enum: + - response.completed + x-stainless-const: true + x-oaiMeta: + name: response.completed + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "response.completed", + "created_at": 1719168000, + "data": { + "id": "resp_abc123" + } + } + WebhookResponseFailed: + type: object + title: response.failed + description: | + Sent when a background response has failed. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: | + The Unix timestamp (in seconds) of when the model response failed. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the model response. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `response.failed`. + enum: + - response.failed + x-stainless-const: true + x-oaiMeta: + name: response.failed + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "response.failed", + "created_at": 1719168000, + "data": { + "id": "resp_abc123" + } + } + WebhookResponseIncomplete: + type: object + title: response.incomplete + description: | + Sent when a background response has been interrupted. + required: + - created_at + - id + - data + - type + properties: + created_at: + type: integer + description: > + The Unix timestamp (in seconds) of when the model response was + interrupted. + id: + type: string + description: | + The unique ID of the event. + data: + type: object + description: | + Event data payload. + required: + - id + properties: + id: + type: string + description: | + The unique ID of the model response. + object: + type: string + description: | + The object of the event. Always `event`. + enum: + - event + x-stainless-const: true + type: + type: string + description: | + The type of the event. Always `response.incomplete`. + enum: + - response.incomplete + x-stainless-const: true + x-oaiMeta: + name: response.incomplete + group: webhook-events + example: | + { + "id": "evt_abc123", + "type": "response.incomplete", + "created_at": 1719168000, + "data": { + "id": "resp_abc123" + } + } + SkillReferenceParam: + properties: + type: + type: string + enum: + - skill_reference + description: References a skill created with the /v1/skills endpoint. + default: skill_reference + x-stainless-const: true + skill_id: + type: string + maxLength: 64 + minLength: 1 + description: The ID of the referenced skill. + version: + type: string + description: >- + Optional skill version. Use a positive integer or 'latest'. Omit for + default. + type: object + required: + - type + - skill_id + InlineSkillSourceParam: + properties: + type: + type: string + enum: + - base64 + description: The type of the inline skill source. Must be `base64`. + default: base64 + x-stainless-const: true + media_type: + type: string + enum: + - application/zip + description: >- + The media type of the inline skill payload. Must be + `application/zip`. + default: application/zip + x-stainless-const: true + data: + type: string + maxLength: 70254592 + minLength: 1 + description: Base64-encoded skill zip bundle. + type: object + required: + - type + - media_type + - data + description: Inline skill payload + InlineSkillParam: + properties: + type: + type: string + enum: + - inline + description: Defines an inline skill for this request. + default: inline + x-stainless-const: true + name: + type: string + description: The name of the skill. + description: + type: string + description: The description of the skill. + source: + $ref: '#/components/schemas/InlineSkillSourceParam' + description: Inline skill payload + type: object + required: + - type + - name + - description + - source + ContainerNetworkPolicyDisabledParam: + properties: + type: + type: string + enum: + - disabled + description: Disable outbound network access. Always `disabled`. + default: disabled + x-stainless-const: true + type: object + required: + - type + ContainerNetworkPolicyDomainSecretParam: + properties: + domain: + type: string + minLength: 1 + description: The domain associated with the secret. + name: + type: string + minLength: 1 + description: The name of the secret to inject for the domain. + value: + type: string + maxLength: 10485760 + minLength: 1 + description: The secret value to inject for the domain. + type: object + required: + - domain + - name + - value + ContainerNetworkPolicyAllowlistParam: + properties: + type: + type: string + enum: + - allowlist + description: >- + Allow outbound network access only to specified domains. Always + `allowlist`. + default: allowlist + x-stainless-const: true + allowed_domains: + items: + type: string + type: array + minItems: 1 + description: A list of allowed domains when type is `allowlist`. + domain_secrets: + items: + $ref: '#/components/schemas/ContainerNetworkPolicyDomainSecretParam' + type: array + minItems: 1 + description: Optional domain-scoped secrets for allowlisted domains. + type: object + required: + - type + - allowed_domains + IncludeEnum: + type: string + enum: + - file_search_call.results + - web_search_call.results + - web_search_call.action.sources + - message.input_image.image_url + - computer_call_output.output.image_url + - code_interpreter_call.outputs + - reasoning.encrypted_content + - message.output_text.logprobs + description: >- + 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). + MessageStatus: + type: string + enum: + - in_progress + - completed + - incomplete + MessageRole: + type: string + enum: + - unknown + - user + - assistant + - system + - critic + - discriminator + - developer + - tool + InputTextContent: + properties: + type: + type: string + enum: + - input_text + description: The type of the input item. Always `input_text`. + default: input_text + x-stainless-const: true + text: + type: string + description: The text input to the model. + type: object + required: + - type + - text + title: Input text + description: A text input to the model. + FileCitationBody: + properties: + type: + type: string + enum: + - file_citation + description: The type of the file citation. Always `file_citation`. + default: file_citation + x-stainless-const: true + file_id: + type: string + description: The ID of the file. + index: + type: integer + description: The index of the file in the list of files. + filename: + type: string + description: The filename of the file cited. + type: object + required: + - type + - file_id + - index + - filename + title: File citation + description: A citation to a file. + UrlCitationBody: + properties: + type: + type: string + enum: + - url_citation + description: The type of the URL citation. Always `url_citation`. + default: url_citation + x-stainless-const: true + url: + type: string + description: The URL of the web resource. + start_index: + type: integer + description: The index of the first character of the URL citation in the message. + end_index: + type: integer + description: The index of the last character of the URL citation in the message. + title: + type: string + description: The title of the web resource. + type: object + required: + - type + - url + - start_index + - end_index + - title + title: URL citation + description: A citation for a web resource used to generate a model response. + ContainerFileCitationBody: + properties: + type: + type: string + enum: + - container_file_citation + description: >- + The type of the container file citation. Always + `container_file_citation`. + default: container_file_citation + x-stainless-const: true + container_id: + type: string + description: The ID of the container file. + file_id: + type: string + description: The ID of the file. + start_index: + type: integer + description: >- + The index of the first character of the container file citation in + the message. + end_index: + type: integer + description: >- + The index of the last character of the container file citation in + the message. + filename: + type: string + description: The filename of the container file cited. + type: object + required: + - type + - container_id + - file_id + - start_index + - end_index + - filename + title: Container file citation + description: A citation for a container file used to generate a model response. + Annotation: + oneOf: + - $ref: '#/components/schemas/FileCitationBody' + - $ref: '#/components/schemas/UrlCitationBody' + - $ref: '#/components/schemas/ContainerFileCitationBody' + - $ref: '#/components/schemas/FilePath' + description: An annotation that applies to a span of output text. + discriminator: + propertyName: type + TopLogProb: + properties: + token: + type: string + logprob: + type: number + bytes: + items: + type: integer + type: array + type: object + required: + - token + - logprob + - bytes + title: Top log probability + description: The top log probability of a token. + LogProb: + properties: + token: + type: string + logprob: + type: number + bytes: + items: + type: integer + type: array + top_logprobs: + items: + $ref: '#/components/schemas/TopLogProb' + type: array + type: object + required: + - token + - logprob + - bytes + - top_logprobs + title: Log probability + description: The log probability of a token. + OutputTextContent: + properties: + type: + type: string + enum: + - output_text + description: The type of the output text. Always `output_text`. + default: output_text + x-stainless-const: true + text: + type: string + description: The text output from the model. + annotations: + items: + $ref: '#/components/schemas/Annotation' + type: array + description: The annotations of the text output. + logprobs: + items: + $ref: '#/components/schemas/LogProb' + type: array + type: object + required: + - type + - text + - annotations + - logprobs + title: Output text + description: A text output from the model. + TextContent: + properties: + type: + type: string + enum: + - text + default: text + x-stainless-const: true + text: + type: string + type: object + required: + - type + - text + title: Text Content + description: A text content. + SummaryTextContent: + properties: + type: + type: string + enum: + - summary_text + description: The type of the object. Always `summary_text`. + default: summary_text + x-stainless-const: true + text: + type: string + description: A summary of the reasoning output from the model so far. + type: object + required: + - type + - text + title: Summary text + description: A summary text from the model. + ReasoningTextContent: + properties: + type: + type: string + enum: + - reasoning_text + description: The type of the reasoning text. Always `reasoning_text`. + default: reasoning_text + x-stainless-const: true + text: + type: string + description: The reasoning text from the model. + type: object + required: + - type + - text + title: Reasoning text + description: Reasoning text from the model. + RefusalContent: + properties: + type: + type: string + enum: + - refusal + description: The type of the refusal. Always `refusal`. + default: refusal + x-stainless-const: true + refusal: + type: string + description: The refusal explanation from the model. + type: object + required: + - type + - refusal + title: Refusal + description: A refusal from the model. + ImageDetail: + type: string + enum: + - low + - high + - auto + - original + InputImageContent: + properties: + type: + type: string + enum: + - input_image + description: The type of the input item. Always `input_image`. + default: input_image + x-stainless-const: true + image_url: + anyOf: + - type: string + description: >- + The URL of the image to be sent to the model. A fully qualified + URL or base64 encoded image in a data URL. + - type: 'null' + file_id: + anyOf: + - type: string + description: The ID of the file to be sent to the model. + - type: 'null' + detail: + $ref: '#/components/schemas/ImageDetail' + description: >- + The detail level of the image to be sent to the model. One of + `high`, `low`, `auto`, or `original`. Defaults to `auto`. + type: object + required: + - type + - detail + title: Input image + description: >- + An image input to the model. Learn about [image + inputs](/docs/guides/vision). + ComputerScreenshotContent: + properties: + type: + type: string + enum: + - computer_screenshot + description: >- + Specifies the event type. For a computer screenshot, this property + is always set to `computer_screenshot`. + default: computer_screenshot + x-stainless-const: true + image_url: + anyOf: + - type: string + description: The URL of the screenshot image. + - type: 'null' + file_id: + anyOf: + - type: string + description: The identifier of an uploaded file that contains the screenshot. + - type: 'null' + detail: + $ref: '#/components/schemas/ImageDetail' + description: >- + The detail level of the screenshot image to be sent to the model. + One of `high`, `low`, `auto`, or `original`. Defaults to `auto`. + type: object + required: + - type + - image_url + - file_id + - detail + title: Computer screenshot + description: A screenshot of a computer. + FileInputDetail: + type: string + enum: + - low + - high + InputFileContent: + properties: + type: + type: string + enum: + - input_file + description: The type of the input item. Always `input_file`. + default: input_file + x-stainless-const: true + file_id: + anyOf: + - type: string + description: The ID of the file to be sent to the model. + - type: 'null' + filename: + type: string + description: The name of the file to be sent to the model. + file_data: + type: string + description: | + The content of the file to be sent to the model. + file_url: + type: string + description: The URL of the file to be sent to the model. + detail: + $ref: '#/components/schemas/FileInputDetail' + description: >- + The detail level of the file to be sent to the model. Use `low` for + the default rendering behavior, or `high` to render the file at + higher quality. Defaults to `low`. + type: object + required: &ref_0 + - type + title: Input file + description: A file input to the model. + MessagePhase-2: + type: string + enum: + - commentary + - final_answer + Message: + properties: + type: + type: string + enum: + - message + description: The type of the message. Always set to `message`. + default: message + x-stainless-const: true + id: + type: string + description: The unique ID of the message. + status: + $ref: '#/components/schemas/MessageStatus' + description: >- + The status of item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + role: + $ref: '#/components/schemas/MessageRole' + description: >- + The role of the message. One of `unknown`, `user`, `assistant`, + `system`, `critic`, `discriminator`, `developer`, or `tool`. + content: + items: + oneOf: + - $ref: '#/components/schemas/InputTextContent' + - $ref: '#/components/schemas/OutputTextContent' + - $ref: '#/components/schemas/TextContent' + - $ref: '#/components/schemas/SummaryTextContent' + - $ref: '#/components/schemas/ReasoningTextContent' + - $ref: '#/components/schemas/RefusalContent' + - $ref: '#/components/schemas/InputImageContent' + - $ref: '#/components/schemas/ComputerScreenshotContent' + - $ref: '#/components/schemas/InputFileContent' + description: A content part that makes up an input or output item. + discriminator: + propertyName: type + type: array + description: The content of the message + phase: + anyOf: + - $ref: '#/components/schemas/MessagePhase-2' + description: >- + Labels an `assistant` message as intermediate commentary + (`commentary`) or the final answer (`final_answer`). For models + like `gpt-5.3-codex` and beyond, when sending follow-up + requests, preserve and resend phase on all assistant messages — + dropping it can degrade performance. Not used for user messages. + - type: 'null' + type: object + required: + - type + - id + - status + - role + - content + title: Message + description: A message to or from the model. + FunctionCallStatus: + type: string + enum: + - in_progress + - completed + - incomplete + FunctionCallOutputStatusEnum: + type: string + enum: + - in_progress + - completed + - incomplete + ClickButtonType: + type: string + enum: + - left + - right + - wheel + - back + - forward + ClickParam: + properties: + type: + type: string + enum: + - click + description: >- + Specifies the event type. For a click action, this property is + always `click`. + default: click + x-stainless-const: true + button: + $ref: '#/components/schemas/ClickButtonType' + description: >- + Indicates which mouse button was pressed during the click. One of + `left`, `right`, `wheel`, `back`, or `forward`. + x: + type: integer + description: The x-coordinate where the click occurred. + 'y': + type: integer + description: The y-coordinate where the click occurred. + keys: + anyOf: + - items: + type: string + type: array + description: The keys being held while clicking. + - type: 'null' + type: object + required: + - type + - button + - x + - 'y' + title: Click + description: A click action. + DoubleClickAction: + properties: + type: + type: string + enum: + - double_click + description: >- + Specifies the event type. For a double click action, this property + is always set to `double_click`. + default: double_click + x-stainless-const: true + x: + type: integer + description: The x-coordinate where the double click occurred. + 'y': + type: integer + description: The y-coordinate where the double click occurred. + keys: + anyOf: + - items: + type: string + type: array + description: The keys being held while double-clicking. + - type: 'null' + type: object + required: + - type + - x + - 'y' + - keys + title: DoubleClick + description: A double click action. + CoordParam: + properties: + x: + type: integer + description: The x-coordinate. + 'y': + type: integer + description: The y-coordinate. + type: object + required: + - x + - 'y' + title: Coordinate + description: 'An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`.' + DragParam: + properties: + type: + type: string + enum: + - drag + description: >- + Specifies the event type. For a drag action, this property is always + set to `drag`. + default: drag + x-stainless-const: true + path: + items: + $ref: '#/components/schemas/CoordParam' + type: array + description: >- + An array of coordinates representing the path of the drag action. + Coordinates will appear as an array of objects, eg + + ``` + + [ + { x: 100, y: 200 }, + { x: 200, y: 300 } + ] + + ``` + keys: + anyOf: + - items: + type: string + type: array + description: The keys being held while dragging the mouse. + - type: 'null' + type: object + required: + - type + - path + title: Drag + description: A drag action. + KeyPressAction: + properties: + type: + type: string + enum: + - keypress + description: >- + Specifies the event type. For a keypress action, this property is + always set to `keypress`. + default: keypress + x-stainless-const: true + keys: + items: + type: string + description: One of the keys the model is requesting to be pressed. + type: array + description: >- + The combination of keys the model is requesting to be pressed. This + is an array of strings, each representing a key. + type: object + required: + - type + - keys + title: KeyPress + description: A collection of keypresses the model would like to perform. + MoveParam: + properties: + type: + type: string + enum: + - move + description: >- + Specifies the event type. For a move action, this property is always + set to `move`. + default: move + x-stainless-const: true + x: + type: integer + description: The x-coordinate to move to. + 'y': + type: integer + description: The y-coordinate to move to. + keys: + anyOf: + - items: + type: string + type: array + description: The keys being held while moving the mouse. + - type: 'null' + type: object + required: + - type + - x + - 'y' + title: Move + description: A mouse move action. + ScreenshotParam: + properties: + type: + type: string + enum: + - screenshot + description: >- + Specifies the event type. For a screenshot action, this property is + always set to `screenshot`. + default: screenshot + x-stainless-const: true + type: object + required: + - type + title: Screenshot + description: A screenshot action. + ScrollParam: + properties: + type: + type: string + enum: + - scroll + description: >- + Specifies the event type. For a scroll action, this property is + always set to `scroll`. + default: scroll + x-stainless-const: true + x: + type: integer + description: The x-coordinate where the scroll occurred. + 'y': + type: integer + description: The y-coordinate where the scroll occurred. + scroll_x: + type: integer + description: The horizontal scroll distance. + scroll_y: + type: integer + description: The vertical scroll distance. + keys: + anyOf: + - items: + type: string + type: array + description: The keys being held while scrolling. + - type: 'null' + type: object + required: + - type + - x + - 'y' + - scroll_x + - scroll_y + title: Scroll + description: A scroll action. + TypeParam: + properties: + type: + type: string + enum: + - type + description: >- + Specifies the event type. For a type action, this property is always + set to `type`. + default: type + x-stainless-const: true + text: + type: string + description: The text to type. + type: object + required: + - type + - text + title: Type + description: An action to type in text. + WaitParam: + properties: + type: + type: string + enum: + - wait + description: >- + Specifies the event type. For a wait action, this property is always + set to `wait`. + default: wait + x-stainless-const: true + type: object + required: + - type + title: Wait + description: A wait action. + ComputerCallSafetyCheckParam: + properties: + id: + type: string + description: The ID of the pending safety check. + code: + anyOf: + - type: string + description: The type of the pending safety check. + - type: 'null' + message: + anyOf: + - type: string + description: Details about the pending safety check. + - type: 'null' + type: object + required: + - id + description: A pending safety check for the computer call. + ComputerCallOutputStatus: + type: string + enum: + - completed + - incomplete + - failed + ToolSearchExecutionType: + type: string + enum: + - server + - client + ToolSearchCall: + properties: + type: + type: string + enum: + - tool_search_call + description: The type of the item. Always `tool_search_call`. + default: tool_search_call + x-stainless-const: true + id: + type: string + description: The unique ID of the tool search call item. + call_id: + anyOf: + - type: string + description: The unique ID of the tool search call generated by the model. + - type: 'null' + execution: + $ref: '#/components/schemas/ToolSearchExecutionType' + description: Whether tool search was executed by the server or by the client. + arguments: + description: Arguments used for the tool search call. + status: + $ref: '#/components/schemas/FunctionCallStatus' + description: The status of the tool search call item that was recorded. + created_by: + type: string + description: The identifier of the actor that created the item. + type: object + required: + - type + - id + - call_id + - execution + - arguments + - status + FunctionTool: + properties: + type: + type: string + enum: + - function + description: The type of the function tool. Always `function`. + default: function + x-stainless-const: true + name: + type: string + description: The name of the function to call. + description: + anyOf: + - type: string + description: >- + A description of the function. Used by the model to determine + whether or not to call the function. + - type: 'null' + parameters: + anyOf: + - additionalProperties: {} + type: object + description: A JSON schema object describing the parameters of the function. + x-oaiTypeLabel: map + - type: 'null' + strict: + anyOf: + - type: boolean + description: Whether to enforce strict parameter validation. Default `true`. + - type: 'null' + defer_loading: + type: boolean + description: Whether this function is deferred and loaded via tool search. + type: object + required: + - type + - name + - strict + - parameters + title: Function + description: >- + Defines a function in your own code the model can choose to call. Learn + more about [function + calling](https://platform.openai.com/docs/guides/function-calling). + RankerVersionType: + type: string + enum: + - auto + - default-2024-11-15 + HybridSearchOptions: + properties: + embedding_weight: + type: number + description: The weight of the embedding in the reciprocal ranking fusion. + text_weight: + type: number + description: The weight of the text in the reciprocal ranking fusion. + type: object + required: + - embedding_weight + - text_weight + RankingOptions: + properties: + ranker: + $ref: '#/components/schemas/RankerVersionType' + description: The ranker to use for the file search. + score_threshold: + type: number + description: >- + The score threshold for the file search, a number between 0 and 1. + Numbers closer to 1 will attempt to return only the most relevant + results, but may return fewer results. + hybrid_search: + $ref: '#/components/schemas/HybridSearchOptions' + description: >- + Weights that control how reciprocal rank fusion balances semantic + embedding matches versus sparse keyword matches when hybrid search + is enabled. + type: object + required: [] + Filters: + anyOf: + - $ref: '#/components/schemas/ComparisonFilter' + - $ref: '#/components/schemas/CompoundFilter' + FileSearchTool: + properties: + type: + type: string + enum: + - file_search + description: The type of the file search tool. Always `file_search`. + default: file_search + x-stainless-const: true + vector_store_ids: + items: + type: string + type: array + description: The IDs of the vector stores to search. + max_num_results: + type: integer + description: >- + The maximum number of results to return. This number should be + between 1 and 50 inclusive. + ranking_options: + $ref: '#/components/schemas/RankingOptions' + description: Ranking options for search. + filters: + anyOf: + - $ref: '#/components/schemas/Filters' + description: A filter to apply. + - type: 'null' + type: object + required: + - type + - vector_store_ids + title: File search + description: >- + A tool that searches for relevant content from uploaded files. Learn + more about the [file search + tool](https://platform.openai.com/docs/guides/tools-file-search). + ComputerTool: + properties: + type: + type: string + enum: + - computer + description: The type of the computer tool. Always `computer`. + default: computer + x-stainless-const: true + type: object + required: + - type + title: Computer + description: >- + A tool that controls a virtual computer. Learn more about the [computer + tool](https://platform.openai.com/docs/guides/tools-computer-use). + ComputerEnvironment: + type: string + enum: + - windows + - mac + - linux + - ubuntu + - browser + ComputerUsePreviewTool: + properties: + type: + type: string + enum: + - computer_use_preview + description: The type of the computer use tool. Always `computer_use_preview`. + default: computer_use_preview + x-stainless-const: true + environment: + $ref: '#/components/schemas/ComputerEnvironment' + description: The type of computer environment to control. + display_width: + type: integer + description: The width of the computer display. + display_height: + type: integer + description: The height of the computer display. + type: object + required: + - type + - environment + - display_width + - display_height + title: Computer use preview + description: >- + A tool that controls a virtual computer. Learn more about the [computer + tool](https://platform.openai.com/docs/guides/tools-computer-use). + ContainerMemoryLimit: + type: string + enum: + - 1g + - 4g + - 16g + - 64g + AutoCodeInterpreterToolParam: + properties: + type: + type: string + enum: + - auto + description: Always `auto`. + default: auto + x-stainless-const: true + file_ids: + items: + type: string + example: file-123 + type: array + maxItems: 50 + description: An optional list of uploaded files to make available to your code. + memory_limit: + anyOf: + - $ref: '#/components/schemas/ContainerMemoryLimit' + description: The memory limit for the code interpreter container. + - type: 'null' + network_policy: + oneOf: + - $ref: '#/components/schemas/ContainerNetworkPolicyDisabledParam' + - $ref: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' + description: Network access policy for the container. + discriminator: + propertyName: type + type: object + required: + - type + title: CodeInterpreterToolAuto + description: >- + Configuration for a code interpreter container. Optionally specify the + IDs of the files to run the code on. + InputFidelity: + type: string + enum: + - high + - low + description: >- + Control how much effort the model will exert to match the style and + features, especially facial features, of input images. This parameter is + only supported for `gpt-image-1` and `gpt-image-1.5` and later models, + unsupported for `gpt-image-1-mini`. Supports `high` and `low`. Defaults + to `low`. + ImageGenActionEnum: + type: string + enum: + - generate + - edit + - auto + LocalShellToolParam: + properties: + type: + type: string + enum: + - local_shell + description: The type of the local shell tool. Always `local_shell`. + default: local_shell + x-stainless-const: true + type: object + required: + - type + title: Local shell tool + description: >- + A tool that allows the model to execute shell commands in a local + environment. + ContainerAutoParam: + properties: + type: + type: string + enum: + - container_auto + description: Automatically creates a container for this request + default: container_auto + x-stainless-const: true + file_ids: + items: + type: string + example: file-123 + type: array + maxItems: 50 + description: An optional list of uploaded files to make available to your code. + memory_limit: + anyOf: + - $ref: '#/components/schemas/ContainerMemoryLimit' + description: The memory limit for the container. + - type: 'null' + network_policy: + oneOf: + - $ref: '#/components/schemas/ContainerNetworkPolicyDisabledParam' + - $ref: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' + description: Network access policy for the container. + discriminator: + propertyName: type + skills: + items: + oneOf: + - $ref: '#/components/schemas/SkillReferenceParam' + - $ref: '#/components/schemas/InlineSkillParam' + discriminator: + propertyName: type + type: array + maxItems: 200 + description: An optional list of skills referenced by id or inline data. + type: object + required: + - type + LocalSkillParam: + properties: + name: + type: string + description: The name of the skill. + description: + type: string + description: The description of the skill. + path: + type: string + description: The path to the directory containing the skill. + type: object + required: + - name + - description + - path + LocalEnvironmentParam: + properties: + type: + type: string + enum: + - local + description: Use a local computer environment. + default: local + x-stainless-const: true + skills: + items: + $ref: '#/components/schemas/LocalSkillParam' + type: array + maxItems: 200 + description: An optional list of skills. + type: object + required: + - type + ContainerReferenceParam: + properties: + type: + type: string + enum: + - container_reference + description: References a container created with the /v1/containers endpoint + default: container_reference + x-stainless-const: true + container_id: + type: string + description: The ID of the referenced container. + example: cntr_123 + type: object + required: + - type + - container_id + FunctionShellToolParam: + properties: + type: + type: string + enum: + - shell + description: The type of the shell tool. Always `shell`. + default: shell + x-stainless-const: true + environment: + anyOf: + - oneOf: + - $ref: '#/components/schemas/ContainerAutoParam' + - $ref: '#/components/schemas/LocalEnvironmentParam' + - $ref: '#/components/schemas/ContainerReferenceParam' + discriminator: + propertyName: type + - type: 'null' + type: object + required: + - type + title: Shell tool + description: A tool that allows the model to execute shell commands. + CustomTextFormatParam: + properties: + type: + type: string + enum: + - text + description: Unconstrained text format. Always `text`. + default: text + x-stainless-const: true + type: object + required: + - type + title: Text format + description: Unconstrained free-form text. + GrammarSyntax1: + type: string + enum: + - lark + - regex + CustomGrammarFormatParam: + properties: + type: + type: string + enum: + - grammar + description: Grammar format. Always `grammar`. + default: grammar + x-stainless-const: true + syntax: + $ref: '#/components/schemas/GrammarSyntax1' + description: The syntax of the grammar definition. One of `lark` or `regex`. + definition: + type: string + description: The grammar definition. + type: object + required: + - type + - syntax + - definition + title: Grammar format + description: A grammar defined by the user. + CustomToolParam: + properties: + type: + type: string + enum: + - custom + description: The type of the custom tool. Always `custom`. + default: custom + x-stainless-const: true + name: + type: string + description: The name of the custom tool, used to identify it in tool calls. + description: + type: string + description: >- + Optional description of the custom tool, used to provide more + context. + format: + oneOf: + - $ref: '#/components/schemas/CustomTextFormatParam' + - $ref: '#/components/schemas/CustomGrammarFormatParam' + description: The input format for the custom tool. Default is unconstrained text. + discriminator: + propertyName: type + defer_loading: + type: boolean + description: Whether this tool should be deferred and discovered via tool search. + type: object + required: + - type + - name + title: Custom tool + description: >- + A custom tool that processes input using a specified format. Learn more + about [custom tools](/docs/guides/function-calling#custom-tools) + EmptyModelParam: + properties: {} + type: object + required: [] + FunctionToolParam: + properties: + name: + type: string + maxLength: 128 + minLength: 1 + pattern: ^[a-zA-Z0-9_-]+$ + description: + anyOf: + - type: string + - type: 'null' + parameters: + anyOf: + - $ref: '#/components/schemas/EmptyModelParam' + - type: 'null' + strict: + anyOf: + - type: boolean + - type: 'null' + type: + type: string + enum: + - function + default: function + x-stainless-const: true + defer_loading: + type: boolean + description: >- + Whether this function should be deferred and discovered via tool + search. + type: object + required: + - name + - type + NamespaceToolParam: + properties: + type: + type: string + enum: + - namespace + description: The type of the tool. Always `namespace`. + default: namespace + x-stainless-const: true + name: + type: string + minLength: 1 + description: The namespace name used in tool calls (for example, `crm`). + description: + type: string + minLength: 1 + description: A description of the namespace shown to the model. + tools: + items: + oneOf: + - $ref: '#/components/schemas/FunctionToolParam' + - $ref: '#/components/schemas/CustomToolParam' + description: A function or custom tool that belongs to a namespace. + discriminator: + propertyName: type + type: array + minItems: 1 + description: The function/custom tools available inside this namespace. + type: object + required: + - type + - name + - description + - tools + title: Namespace + description: Groups function/custom tools under a shared namespace. + ToolSearchToolParam: + properties: + type: + type: string + enum: + - tool_search + description: The type of the tool. Always `tool_search`. + default: tool_search + x-stainless-const: true + execution: + $ref: '#/components/schemas/ToolSearchExecutionType' + description: Whether tool search is executed by the server or by the client. + description: + anyOf: + - type: string + description: >- + Description shown to the model for a client-executed tool search + tool. + - type: 'null' + parameters: + anyOf: + - $ref: '#/components/schemas/EmptyModelParam' + description: Parameter schema for a client-executed tool search tool. + - type: 'null' + type: object + required: + - type + title: Tool search tool + description: Hosted or BYOT tool search configuration for deferred tools. + ApproximateLocation: + properties: + type: + type: string + enum: + - approximate + description: The type of location approximation. Always `approximate`. + default: approximate + x-stainless-const: true + country: + anyOf: + - type: string + description: >- + The two-letter [ISO country + code](https://en.wikipedia.org/wiki/ISO_3166-1) of the user, + e.g. `US`. + - type: 'null' + region: + anyOf: + - type: string + description: Free text input for the region of the user, e.g. `California`. + - type: 'null' + city: + anyOf: + - type: string + description: Free text input for the city of the user, e.g. `San Francisco`. + - type: 'null' + timezone: + anyOf: + - type: string + description: >- + The [IANA + timezone](https://timeapi.io/documentation/iana-timezones) of + the user, e.g. `America/Los_Angeles`. + - type: 'null' + type: object + required: *ref_0 + SearchContextSize: + type: string + enum: + - low + - medium + - high + SearchContentType: + type: string + enum: + - text + - image + WebSearchPreviewTool: + properties: + type: + type: string + enum: + - web_search_preview + - web_search_preview_2025_03_11 + description: >- + The type of the web search tool. One of `web_search_preview` or + `web_search_preview_2025_03_11`. + default: web_search_preview + x-stainless-const: true + user_location: + anyOf: + - $ref: '#/components/schemas/ApproximateLocation' + description: The user's location. + - type: 'null' + search_context_size: + $ref: '#/components/schemas/SearchContextSize' + description: >- + High level guidance for the amount of context window space to use + for the search. One of `low`, `medium`, or `high`. `medium` is the + default. + search_content_types: + items: + $ref: '#/components/schemas/SearchContentType' + type: array + type: object + required: *ref_0 + title: Web search preview + description: >- + This tool searches the web for relevant results to use in a response. + Learn more about the [web search + tool](https://platform.openai.com/docs/guides/tools-web-search). + ApplyPatchToolParam: + properties: + type: + type: string + enum: + - apply_patch + description: The type of the tool. Always `apply_patch`. + default: apply_patch + x-stainless-const: true + type: object + required: + - type + title: Apply patch tool + description: >- + Allows the assistant to create, delete, or update files using unified + diffs. + ToolSearchOutput: + properties: + type: + type: string + enum: + - tool_search_output + description: The type of the item. Always `tool_search_output`. + default: tool_search_output + x-stainless-const: true + id: + type: string + description: The unique ID of the tool search output item. + call_id: + anyOf: + - type: string + description: The unique ID of the tool search call generated by the model. + - type: 'null' + execution: + $ref: '#/components/schemas/ToolSearchExecutionType' + description: Whether tool search was executed by the server or by the client. + tools: + items: + $ref: '#/components/schemas/Tool' + type: array + description: The loaded tool definitions returned by tool search. + status: + $ref: '#/components/schemas/FunctionCallOutputStatusEnum' + description: The status of the tool search output item that was recorded. + created_by: + type: string + description: The identifier of the actor that created the item. + type: object + required: + - type + - id + - call_id + - execution + - tools + - status + CompactionBody: + properties: + type: + type: string + enum: + - compaction + description: The type of the item. Always `compaction`. + default: compaction + x-stainless-const: true + id: + type: string + description: The unique ID of the compaction item. + encrypted_content: + type: string + description: The encrypted content that was produced by compaction. + created_by: + type: string + description: The identifier of the actor that created the item. + type: object + required: + - type + - id + - encrypted_content + title: Compaction item + description: >- + A compaction item generated by the [`v1/responses/compact` + API](/docs/api-reference/responses/compact). + CodeInterpreterOutputLogs: + properties: + type: + type: string + enum: + - logs + description: The type of the output. Always `logs`. + default: logs + x-stainless-const: true + logs: + type: string + description: The logs output from the code interpreter. + type: object + required: + - type + - logs + title: Code interpreter output logs + description: The logs output from the code interpreter. + CodeInterpreterOutputImage: + properties: + type: + type: string + enum: + - image + description: The type of the output. Always `image`. + default: image + x-stainless-const: true + url: + type: string + description: The URL of the image output from the code interpreter. + type: object + required: + - type + - url + title: Code interpreter output image + description: The image output from the code interpreter. + LocalShellExecAction: + properties: + type: + type: string + enum: + - exec + description: The type of the local shell action. Always `exec`. + default: exec + x-stainless-const: true + command: + items: + type: string + type: array + description: The command to run. + timeout_ms: + anyOf: + - type: integer + description: Optional timeout in milliseconds for the command. + - type: 'null' + working_directory: + anyOf: + - type: string + description: Optional working directory to run the command in. + - type: 'null' + env: + additionalProperties: + type: string + type: object + description: Environment variables to set for the command. + x-oaiTypeLabel: map + user: + anyOf: + - type: string + description: Optional user to run the command as. + - type: 'null' + type: object + required: + - type + - command + - env + title: Local shell exec action + description: Execute a shell command on the server. + FunctionShellAction: + properties: + commands: + items: + type: string + description: A list of commands to run. + type: array + timeout_ms: + anyOf: + - type: integer + description: Optional timeout in milliseconds for the commands. + - type: 'null' + max_output_length: + anyOf: + - type: integer + description: >- + Optional maximum number of characters to return from each + command. + - type: 'null' + type: object + required: + - commands + - timeout_ms + - max_output_length + title: Shell exec action + description: Execute a shell command. + LocalShellCallStatus: + type: string + enum: + - in_progress + - completed + - incomplete + LocalEnvironmentResource: + properties: + type: + type: string + enum: + - local + description: The environment type. Always `local`. + default: local + x-stainless-const: true + type: object + required: + - type + title: Local Environment + description: Represents the use of a local environment to perform shell actions. + ContainerReferenceResource: + properties: + type: + type: string + enum: + - container_reference + description: The environment type. Always `container_reference`. + default: container_reference + x-stainless-const: true + container_id: + type: string + type: object + required: + - type + - container_id + title: Container Reference + description: Represents a container created with /v1/containers. + FunctionShellCall: + properties: + type: + type: string + enum: + - shell_call + description: The type of the item. Always `shell_call`. + default: shell_call + x-stainless-const: true + id: + type: string + description: >- + The unique ID of the shell tool call. Populated when this item is + returned via API. + call_id: + type: string + description: The unique ID of the shell tool call generated by the model. + action: + $ref: '#/components/schemas/FunctionShellAction' + description: >- + The shell commands and limits that describe how to run the tool + call. + status: + $ref: '#/components/schemas/LocalShellCallStatus' + description: >- + The status of the shell call. One of `in_progress`, `completed`, or + `incomplete`. + environment: + anyOf: + - oneOf: + - $ref: '#/components/schemas/LocalEnvironmentResource' + - $ref: '#/components/schemas/ContainerReferenceResource' + discriminator: + propertyName: type + - type: 'null' + created_by: + type: string + description: The ID of the entity that created this tool call. + type: object + required: + - type + - id + - call_id + - action + - status + - environment + title: Shell tool call + description: >- + A tool call that executes one or more shell commands in a managed + environment. + LocalShellCallOutputStatusEnum: + type: string + enum: + - in_progress + - completed + - incomplete + FunctionShellCallOutputTimeoutOutcome: + properties: + type: + type: string + enum: + - timeout + description: The outcome type. Always `timeout`. + default: timeout + x-stainless-const: true + type: object + required: + - type + title: Shell call timeout outcome + description: Indicates that the shell call exceeded its configured time limit. + FunctionShellCallOutputExitOutcome: + properties: + type: + type: string + enum: + - exit + description: The outcome type. Always `exit`. + default: exit + x-stainless-const: true + exit_code: + type: integer + description: Exit code from the shell process. + type: object + required: + - type + - exit_code + title: Shell call exit outcome + description: Indicates that the shell commands finished and returned an exit code. + FunctionShellCallOutputContent: + properties: + stdout: + type: string + description: The standard output that was captured. + stderr: + type: string + description: The standard error output that was captured. + outcome: + oneOf: + - $ref: '#/components/schemas/FunctionShellCallOutputTimeoutOutcome' + - $ref: '#/components/schemas/FunctionShellCallOutputExitOutcome' + title: Shell call outcome + description: >- + Represents either an exit outcome (with an exit code) or a timeout + outcome for a shell call output chunk. + discriminator: + propertyName: type + created_by: + type: string + description: The identifier of the actor that created the item. + type: object + required: + - stdout + - stderr + - outcome + title: Shell call output content + description: The content of a shell tool call output that was emitted. + FunctionShellCallOutput: + properties: + type: + type: string + enum: + - shell_call_output + description: The type of the shell call output. Always `shell_call_output`. + default: shell_call_output + x-stainless-const: true + id: + type: string + description: >- + The unique ID of the shell call output. Populated when this item is + returned via API. + call_id: + type: string + description: The unique ID of the shell tool call generated by the model. + status: + $ref: '#/components/schemas/LocalShellCallOutputStatusEnum' + description: >- + The status of the shell call output. One of `in_progress`, + `completed`, or `incomplete`. + output: + items: + $ref: '#/components/schemas/FunctionShellCallOutputContent' + type: array + description: An array of shell call output contents + max_output_length: + anyOf: + - type: integer + description: >- + The maximum length of the shell command output. This is + generated by the model and should be passed back with the raw + output. + - type: 'null' + created_by: + type: string + description: The identifier of the actor that created the item. + type: object + required: + - type + - id + - call_id + - status + - output + - max_output_length + title: Shell call output + description: The output of a shell tool call that was emitted. + ApplyPatchCallStatus: + type: string + enum: + - in_progress + - completed + ApplyPatchCreateFileOperation: + properties: + type: + type: string + enum: + - create_file + description: Create a new file with the provided diff. + default: create_file + x-stainless-const: true + path: + type: string + description: Path of the file to create. + diff: + type: string + description: Diff to apply. + type: object + required: + - type + - path + - diff + title: Apply patch create file operation + description: Instruction describing how to create a file via the apply_patch tool. + ApplyPatchDeleteFileOperation: + properties: + type: + type: string + enum: + - delete_file + description: Delete the specified file. + default: delete_file + x-stainless-const: true + path: + type: string + description: Path of the file to delete. + type: object + required: + - type + - path + title: Apply patch delete file operation + description: Instruction describing how to delete a file via the apply_patch tool. + ApplyPatchUpdateFileOperation: + properties: + type: + type: string + enum: + - update_file + description: Update an existing file with the provided diff. + default: update_file + x-stainless-const: true + path: + type: string + description: Path of the file to update. + diff: + type: string + description: Diff to apply. + type: object + required: + - type + - path + - diff + title: Apply patch update file operation + description: Instruction describing how to update a file via the apply_patch tool. + ApplyPatchToolCall: + properties: + type: + type: string + enum: + - apply_patch_call + description: The type of the item. Always `apply_patch_call`. + default: apply_patch_call + x-stainless-const: true + id: + type: string + description: >- + The unique ID of the apply patch tool call. Populated when this item + is returned via API. + call_id: + type: string + description: The unique ID of the apply patch tool call generated by the model. + status: + $ref: '#/components/schemas/ApplyPatchCallStatus' + description: >- + The status of the apply patch tool call. One of `in_progress` or + `completed`. + operation: + oneOf: + - $ref: '#/components/schemas/ApplyPatchCreateFileOperation' + - $ref: '#/components/schemas/ApplyPatchDeleteFileOperation' + - $ref: '#/components/schemas/ApplyPatchUpdateFileOperation' + title: Apply patch operation + description: >- + One of the create_file, delete_file, or update_file operations + applied via apply_patch. + discriminator: + propertyName: type + created_by: + type: string + description: The ID of the entity that created this tool call. + type: object + required: + - type + - id + - call_id + - status + - operation + title: Apply patch tool call + description: >- + A tool call that applies file diffs by creating, deleting, or updating + files. + ApplyPatchCallOutputStatus: + type: string + enum: + - completed + - failed + ApplyPatchToolCallOutput: + properties: + type: + type: string + enum: + - apply_patch_call_output + description: The type of the item. Always `apply_patch_call_output`. + default: apply_patch_call_output + x-stainless-const: true + id: + type: string + description: >- + The unique ID of the apply patch tool call output. Populated when + this item is returned via API. + call_id: + type: string + description: The unique ID of the apply patch tool call generated by the model. + status: + $ref: '#/components/schemas/ApplyPatchCallOutputStatus' + description: >- + The status of the apply patch tool call output. One of `completed` + or `failed`. + output: + anyOf: + - type: string + description: Optional textual output returned by the apply patch tool. + - type: 'null' + created_by: + type: string + description: The ID of the entity that created this tool call output. + type: object + required: + - type + - id + - call_id + - status + title: Apply patch tool call output + description: The output emitted by an apply patch tool call. + MCPToolCallStatus: + type: string + enum: + - in_progress + - completed + - incomplete + - calling + - failed + DetailEnum: + type: string + enum: + - low + - high + - auto + - original + FunctionCallItemStatus: + type: string + enum: + - in_progress + - completed + - incomplete + ComputerCallOutputItemParam: + properties: + id: + anyOf: + - type: string + description: The ID of the computer tool call output. + example: cuo_123 + - type: 'null' + call_id: + type: string + maxLength: 64 + minLength: 1 + description: The ID of the computer tool call that produced the output. + type: + type: string + enum: + - computer_call_output + description: >- + The type of the computer tool call output. Always + `computer_call_output`. + default: computer_call_output + x-stainless-const: true + output: + $ref: '#/components/schemas/ComputerScreenshotImage' + acknowledged_safety_checks: + anyOf: + - items: + $ref: '#/components/schemas/ComputerCallSafetyCheckParam' + type: array + description: >- + The safety checks reported by the API that have been + acknowledged by the developer. + - type: 'null' + status: + anyOf: + - $ref: '#/components/schemas/FunctionCallItemStatus' + description: >- + The status of the message input. One of `in_progress`, + `completed`, or `incomplete`. Populated when input items are + returned via API. + - type: 'null' + type: object + required: + - call_id + - type + - output + title: Computer tool call output + description: The output of a computer tool call. + InputTextContentParam: + properties: + type: + type: string + enum: + - input_text + description: The type of the input item. Always `input_text`. + default: input_text + x-stainless-const: true + text: + type: string + maxLength: 10485760 + description: The text input to the model. + type: object + required: + - type + - text + title: Input text + description: A text input to the model. + InputImageContentParamAutoParam: + properties: + type: + type: string + enum: + - input_image + description: The type of the input item. Always `input_image`. + default: input_image + x-stainless-const: true + image_url: + anyOf: + - type: string + maxLength: 20971520 + description: >- + The URL of the image to be sent to the model. A fully qualified + URL or base64 encoded image in a data URL. + - type: 'null' + file_id: + anyOf: + - type: string + description: The ID of the file to be sent to the model. + example: file-123 + - type: 'null' + detail: + anyOf: + - $ref: '#/components/schemas/DetailEnum' + description: >- + The detail level of the image to be sent to the model. One of + `high`, `low`, `auto`, or `original`. Defaults to `auto`. + - type: 'null' + type: object + required: + - type + title: Input image + description: >- + An image input to the model. Learn about [image + inputs](/docs/guides/vision) + FileDetailEnum: + type: string + enum: + - low + - high + InputFileContentParam: + properties: + type: + type: string + enum: + - input_file + description: The type of the input item. Always `input_file`. + default: input_file + x-stainless-const: true + file_id: + anyOf: + - type: string + description: The ID of the file to be sent to the model. + example: file-123 + - type: 'null' + filename: + anyOf: + - type: string + description: The name of the file to be sent to the model. + - type: 'null' + file_data: + anyOf: + - type: string + maxLength: 73400320 + description: The base64-encoded data of the file to be sent to the model. + - type: 'null' + file_url: + anyOf: + - type: string + description: The URL of the file to be sent to the model. + - type: 'null' + detail: + $ref: '#/components/schemas/FileDetailEnum' + description: >- + The detail level of the file to be sent to the model. Use `low` for + the default rendering behavior, or `high` to render the file at + higher quality. Defaults to `low`. + type: object + required: + - type + title: Input file + description: A file input to the model. + FunctionCallOutputItemParam: + properties: + id: + anyOf: + - type: string + description: >- + The unique ID of the function tool call output. Populated when + this item is returned via API. + example: fc_123 + - type: 'null' + call_id: + type: string + maxLength: 64 + minLength: 1 + description: The unique ID of the function tool call generated by the model. + type: + type: string + enum: + - function_call_output + description: >- + The type of the function tool call output. Always + `function_call_output`. + default: function_call_output + x-stainless-const: true + output: + oneOf: + - type: string + maxLength: 10485760 + description: A JSON string of the output of the function tool call. + - items: + oneOf: + - $ref: '#/components/schemas/InputTextContentParam' + - $ref: '#/components/schemas/InputImageContentParamAutoParam' + - $ref: '#/components/schemas/InputFileContentParam' + description: A piece of message content, such as text, an image, or a file. + discriminator: + propertyName: type + type: array + description: >- + An array of content outputs (text, image, file) for the function + tool call. + description: Text, image, or file output of the function tool call. + status: + anyOf: + - $ref: '#/components/schemas/FunctionCallItemStatus' + description: >- + The status of the item. One of `in_progress`, `completed`, or + `incomplete`. Populated when items are returned via API. + - type: 'null' + type: object + required: + - call_id + - type + - output + title: Function tool call output + description: The output of a function tool call. + ToolSearchCallItemParam: + properties: + id: + anyOf: + - type: string + description: The unique ID of this tool search call. + example: tsc_123 + - type: 'null' + call_id: + anyOf: + - type: string + maxLength: 64 + minLength: 1 + description: The unique ID of the tool search call generated by the model. + - type: 'null' + type: + type: string + enum: + - tool_search_call + description: The item type. Always `tool_search_call`. + default: tool_search_call + x-stainless-const: true + execution: + $ref: '#/components/schemas/ToolSearchExecutionType' + description: Whether tool search was executed by the server or by the client. + arguments: + $ref: '#/components/schemas/EmptyModelParam' + description: The arguments supplied to the tool search call. + status: + anyOf: + - $ref: '#/components/schemas/FunctionCallItemStatus' + description: The status of the tool search call. + - type: 'null' + type: object + required: + - type + - arguments + ToolSearchOutputItemParam: + properties: + id: + anyOf: + - type: string + description: The unique ID of this tool search output. + example: tso_123 + - type: 'null' + call_id: + anyOf: + - type: string + maxLength: 64 + minLength: 1 + description: The unique ID of the tool search call generated by the model. + - type: 'null' + type: + type: string + enum: + - tool_search_output + description: The item type. Always `tool_search_output`. + default: tool_search_output + x-stainless-const: true + execution: + $ref: '#/components/schemas/ToolSearchExecutionType' + description: Whether tool search was executed by the server or by the client. + tools: + items: + $ref: '#/components/schemas/Tool' + type: array + description: The loaded tool definitions returned by the tool search output. + status: + anyOf: + - $ref: '#/components/schemas/FunctionCallItemStatus' + description: The status of the tool search output. + - type: 'null' + type: object + required: + - type + - tools + CompactionSummaryItemParam: + properties: + id: + anyOf: + - type: string + description: The ID of the compaction item. + example: cmp_123 + - type: 'null' + type: + type: string + enum: + - compaction + description: The type of the item. Always `compaction`. + default: compaction + x-stainless-const: true + encrypted_content: + type: string + maxLength: 10485760 + description: The encrypted content of the compaction summary. + type: object + required: + - type + - encrypted_content + title: Compaction item + description: >- + A compaction item generated by the [`v1/responses/compact` + API](/docs/api-reference/responses/compact). + FunctionShellActionParam: + properties: + commands: + items: + type: string + type: array + description: Ordered shell commands for the execution environment to run. + timeout_ms: + anyOf: + - type: integer + description: >- + Maximum wall-clock time in milliseconds to allow the shell + commands to run. + - type: 'null' + max_output_length: + anyOf: + - type: integer + description: >- + Maximum number of UTF-8 characters to capture from combined + stdout and stderr output. + - type: 'null' + type: object + required: + - commands + title: Shell action + description: Commands and limits describing how to run the shell tool call. + FunctionShellCallItemStatus: + type: string + enum: + - in_progress + - completed + - incomplete + title: Shell call status + description: Status values reported for shell tool calls. + FunctionShellCallItemParam: + properties: + id: + anyOf: + - type: string + description: >- + The unique ID of the shell tool call. Populated when this item + is returned via API. + example: sh_123 + - type: 'null' + call_id: + type: string + maxLength: 64 + minLength: 1 + description: The unique ID of the shell tool call generated by the model. + type: + type: string + enum: + - shell_call + description: The type of the item. Always `shell_call`. + default: shell_call + x-stainless-const: true + action: + $ref: '#/components/schemas/FunctionShellActionParam' + description: >- + The shell commands and limits that describe how to run the tool + call. + status: + anyOf: + - $ref: '#/components/schemas/FunctionShellCallItemStatus' + description: >- + The status of the shell call. One of `in_progress`, `completed`, + or `incomplete`. + - type: 'null' + environment: + anyOf: + - oneOf: + - $ref: '#/components/schemas/LocalEnvironmentParam' + - $ref: '#/components/schemas/ContainerReferenceParam' + description: The environment to execute the shell commands in. + discriminator: + propertyName: type + - type: 'null' + type: object + required: + - call_id + - type + - action + title: Shell tool call + description: A tool representing a request to execute one or more shell commands. + FunctionShellCallOutputTimeoutOutcomeParam: + properties: + type: + type: string + enum: + - timeout + description: The outcome type. Always `timeout`. + default: timeout + x-stainless-const: true + type: object + required: + - type + title: Shell call timeout outcome + description: Indicates that the shell call exceeded its configured time limit. + FunctionShellCallOutputExitOutcomeParam: + properties: + type: + type: string + enum: + - exit + description: The outcome type. Always `exit`. + default: exit + x-stainless-const: true + exit_code: + type: integer + description: The exit code returned by the shell process. + type: object + required: + - type + - exit_code + title: Shell call exit outcome + description: Indicates that the shell commands finished and returned an exit code. + FunctionShellCallOutputOutcomeParam: + oneOf: + - $ref: '#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam' + - $ref: '#/components/schemas/FunctionShellCallOutputExitOutcomeParam' + title: Shell call outcome + description: The exit or timeout outcome associated with this shell call. + discriminator: + propertyName: type + FunctionShellCallOutputContentParam: + properties: + stdout: + type: string + maxLength: 10485760 + description: Captured stdout output for the shell call. + stderr: + type: string + maxLength: 10485760 + description: Captured stderr output for the shell call. + outcome: + $ref: '#/components/schemas/FunctionShellCallOutputOutcomeParam' + description: The exit or timeout outcome associated with this shell call. + type: object + required: + - stdout + - stderr + - outcome + title: Shell output content + description: Captured stdout and stderr for a portion of a shell tool call output. + FunctionShellCallOutputItemParam: + properties: + id: + anyOf: + - type: string + description: >- + The unique ID of the shell tool call output. Populated when this + item is returned via API. + example: sho_123 + - type: 'null' + call_id: + type: string + maxLength: 64 + minLength: 1 + description: The unique ID of the shell tool call generated by the model. + type: + type: string + enum: + - shell_call_output + description: The type of the item. Always `shell_call_output`. + default: shell_call_output + x-stainless-const: true + output: + items: + $ref: '#/components/schemas/FunctionShellCallOutputContentParam' + type: array + description: >- + Captured chunks of stdout and stderr output, along with their + associated outcomes. + status: + anyOf: + - $ref: '#/components/schemas/FunctionShellCallItemStatus' + description: The status of the shell call output. + - type: 'null' + max_output_length: + anyOf: + - type: integer + description: >- + The maximum number of UTF-8 characters captured for this shell + call's combined output. + - type: 'null' + type: object + required: + - call_id + - type + - output + title: Shell tool call output + description: The streamed output items emitted by a shell tool call. + ApplyPatchCallStatusParam: + type: string + enum: + - in_progress + - completed + title: Apply patch call status + description: Status values reported for apply_patch tool calls. + ApplyPatchCreateFileOperationParam: + properties: + type: + type: string + enum: + - create_file + description: The operation type. Always `create_file`. + default: create_file + x-stainless-const: true + path: + type: string + minLength: 1 + description: Path of the file to create relative to the workspace root. + diff: + type: string + maxLength: 10485760 + description: Unified diff content to apply when creating the file. + type: object + required: + - type + - path + - diff + title: Apply patch create file operation + description: Instruction for creating a new file via the apply_patch tool. + ApplyPatchDeleteFileOperationParam: + properties: + type: + type: string + enum: + - delete_file + description: The operation type. Always `delete_file`. + default: delete_file + x-stainless-const: true + path: + type: string + minLength: 1 + description: Path of the file to delete relative to the workspace root. + type: object + required: + - type + - path + title: Apply patch delete file operation + description: Instruction for deleting an existing file via the apply_patch tool. + ApplyPatchUpdateFileOperationParam: + properties: + type: + type: string + enum: + - update_file + description: The operation type. Always `update_file`. + default: update_file + x-stainless-const: true + path: + type: string + minLength: 1 + description: Path of the file to update relative to the workspace root. + diff: + type: string + maxLength: 10485760 + description: Unified diff content to apply to the existing file. + type: object + required: + - type + - path + - diff + title: Apply patch update file operation + description: Instruction for updating an existing file via the apply_patch tool. + ApplyPatchOperationParam: + oneOf: + - $ref: '#/components/schemas/ApplyPatchCreateFileOperationParam' + - $ref: '#/components/schemas/ApplyPatchDeleteFileOperationParam' + - $ref: '#/components/schemas/ApplyPatchUpdateFileOperationParam' + title: Apply patch operation + description: >- + One of the create_file, delete_file, or update_file operations supplied + to the apply_patch tool. + discriminator: + propertyName: type + ApplyPatchToolCallItemParam: + properties: + type: + type: string + enum: + - apply_patch_call + description: The type of the item. Always `apply_patch_call`. + default: apply_patch_call + x-stainless-const: true + id: + anyOf: + - type: string + description: >- + The unique ID of the apply patch tool call. Populated when this + item is returned via API. + example: apc_123 + - type: 'null' + call_id: + type: string + maxLength: 64 + minLength: 1 + description: The unique ID of the apply patch tool call generated by the model. + status: + $ref: '#/components/schemas/ApplyPatchCallStatusParam' + description: >- + The status of the apply patch tool call. One of `in_progress` or + `completed`. + operation: + $ref: '#/components/schemas/ApplyPatchOperationParam' + description: >- + The specific create, delete, or update instruction for the + apply_patch tool call. + type: object + required: + - type + - call_id + - status + - operation + title: Apply patch tool call + description: >- + A tool call representing a request to create, delete, or update files + using diff patches. + ApplyPatchCallOutputStatusParam: + type: string + enum: + - completed + - failed + title: Apply patch call output status + description: Outcome values reported for apply_patch tool call outputs. + ApplyPatchToolCallOutputItemParam: + properties: + type: + type: string + enum: + - apply_patch_call_output + description: The type of the item. Always `apply_patch_call_output`. + default: apply_patch_call_output + x-stainless-const: true + id: + anyOf: + - type: string + description: >- + The unique ID of the apply patch tool call output. Populated + when this item is returned via API. + example: apco_123 + - type: 'null' + call_id: + type: string + maxLength: 64 + minLength: 1 + description: The unique ID of the apply patch tool call generated by the model. + status: + $ref: '#/components/schemas/ApplyPatchCallOutputStatusParam' + description: >- + The status of the apply patch tool call output. One of `completed` + or `failed`. + output: + anyOf: + - type: string + maxLength: 10485760 + description: >- + Optional human-readable log text from the apply patch tool + (e.g., patch results or errors). + - type: 'null' + type: object + required: + - type + - call_id + - status + title: Apply patch tool call output + description: The streamed output emitted by an apply patch tool call. + ItemReferenceParam: + properties: + type: + anyOf: + - type: string + enum: + - item_reference + description: The type of item to reference. Always `item_reference`. + default: item_reference + x-stainless-const: true + - type: 'null' + id: + type: string + description: The ID of the item to reference. + type: object + required: + - id + title: Item reference + description: An internal identifier for an item to reference. + ConversationResource: + properties: + id: + type: string + description: The unique ID of the conversation. + object: + type: string + enum: + - conversation + description: The object type, which is always `conversation`. + default: conversation + x-stainless-const: true + metadata: + description: >- + Set of 16 key-value pairs that can be attached to an object. This + can be useful for storing additional information about the + object in a structured format, and querying for objects via + API or the dashboard. + Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. + created_at: + type: integer + description: >- + The time at which the conversation was created, measured in seconds + since the Unix epoch. + type: object + required: + - id + - object + - metadata + - created_at + ImageGenOutputTokensDetails: + properties: + image_tokens: + type: integer + description: The number of image output tokens generated by the model. + text_tokens: + type: integer + description: The number of text output tokens generated by the model. + type: object + required: + - image_tokens + - text_tokens + title: Image generation output token details + description: The output token details for the image generation. + ImageGenInputUsageDetails: + properties: + text_tokens: + type: integer + description: The number of text tokens in the input prompt. + image_tokens: + type: integer + description: The number of image tokens in the input prompt. + type: object + required: + - text_tokens + - image_tokens + title: Input usage details + description: The input tokens detailed information for the image generation. + ImageGenUsage: + properties: + input_tokens: + type: integer + description: The number of tokens (images and text) in the input prompt. + total_tokens: + type: integer + description: >- + The total number of tokens (images and text) used for the image + generation. + output_tokens: + type: integer + description: The number of output tokens generated by the model. + output_tokens_details: + $ref: '#/components/schemas/ImageGenOutputTokensDetails' + input_tokens_details: + $ref: '#/components/schemas/ImageGenInputUsageDetails' + type: object + required: + - input_tokens + - total_tokens + - output_tokens + - input_tokens_details + title: Image generation usage + description: >- + For `gpt-image-1` only, the token usage information for the image + generation. + SpecificApplyPatchParam: + properties: + type: + type: string + enum: + - apply_patch + description: The tool to call. Always `apply_patch`. + default: apply_patch + x-stainless-const: true + type: object + required: + - type + title: Specific apply patch tool choice + description: >- + Forces the model to call the apply_patch tool when executing a tool + call. + SpecificFunctionShellParam: + properties: + type: + type: string + enum: + - shell + description: The tool to call. Always `shell`. + default: shell + x-stainless-const: true + type: object + required: + - type + title: Specific shell tool choice + description: Forces the model to call the shell tool when a tool call is required. + ConversationParam-2: + properties: + id: + type: string + description: The unique ID of the conversation. + example: conv_123 + type: object + required: + - id + title: Conversation object + description: The conversation that this response belongs to. + ContextManagementParam: + properties: + type: + type: string + description: >- + The context management entry type. Currently only 'compaction' is + supported. + compact_threshold: + anyOf: + - type: integer + minimum: 1000 + description: >- + Token threshold at which compaction should be triggered for this + entry. + - type: 'null' + type: object + required: + - type + Conversation-2: + properties: + id: + type: string + description: >- + The unique ID of the conversation that this response was associated + with. + type: object + required: + - id + title: Conversation + description: >- + The conversation that this response belonged to. Input items and output + items from this response were automatically added to this conversation. + CreateConversationBody: + properties: + metadata: + anyOf: + - $ref: '#/components/schemas/Metadata' + description: >- + Set of 16 key-value pairs that can be attached to an object. + This can be useful for storing additional information + about the object in a structured format, and querying + for objects via API or the dashboard. + Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. + - type: 'null' + items: + anyOf: + - items: + $ref: '#/components/schemas/InputItem' + type: array + maxItems: 20 + description: >- + Initial items to include in the conversation context. You may + add up to 20 items at a time. + - type: 'null' + type: object + required: [] + UpdateConversationBody: + properties: + metadata: + $ref: '#/components/schemas/Metadata' + description: >- + Set of 16 key-value pairs that can be attached to an object. This + can be useful for storing additional information about the + object in a structured format, and querying for objects via + API or the dashboard. + Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. + type: object + required: + - metadata + DeletedConversationResource: + properties: + object: + type: string + enum: + - conversation.deleted + default: conversation.deleted + x-stainless-const: true + deleted: + type: boolean + id: + type: string + type: object + required: + - object + - deleted + - id + OrderEnum: + type: string + enum: + - asc + - desc + VideoModel: + anyOf: + - type: string + - type: string + enum: + - sora-2 + - sora-2-pro + - sora-2-2025-10-06 + - sora-2-pro-2025-10-06 + - sora-2-2025-12-08 + VideoStatus: + type: string + enum: + - queued + - in_progress + - completed + - failed + VideoSize: + type: string + enum: + - 720x1280 + - 1280x720 + - 1024x1792 + - 1792x1024 + Error-2: + properties: + code: + type: string + description: A machine-readable error code that was returned. + message: + type: string + description: A human-readable description of the error that was returned. + type: object + required: + - code + - message + title: Error + description: An error that occurred while generating the response. + VideoResource: + properties: + id: + type: string + description: Unique identifier for the video job. + object: + type: string + enum: + - video + description: The object type, which is always `video`. + default: video + x-stainless-const: true + model: + $ref: '#/components/schemas/VideoModel' + description: The video generation model that produced the job. + status: + $ref: '#/components/schemas/VideoStatus' + description: Current lifecycle status of the video job. + progress: + type: integer + description: Approximate completion percentage for the generation task. + created_at: + type: integer + description: Unix timestamp (seconds) for when the job was created. + completed_at: + anyOf: + - type: integer + description: >- + Unix timestamp (seconds) for when the job completed, if + finished. + - type: 'null' + expires_at: + anyOf: + - type: integer + description: >- + Unix timestamp (seconds) for when the downloadable assets + expire, if set. + - type: 'null' + prompt: + anyOf: + - type: string + description: The prompt that was used to generate the video. + - type: 'null' + size: + $ref: '#/components/schemas/VideoSize' + description: The resolution of the generated video. + seconds: + type: string + description: >- + Duration of the generated clip in seconds. For extensions, this is + the stitched total duration. + remixed_from_video_id: + anyOf: + - type: string + description: Identifier of the source video if this video is a remix. + - type: 'null' + error: + anyOf: + - $ref: '#/components/schemas/Error-2' + description: >- + Error payload that explains why generation failed, if + applicable. + - type: 'null' + type: object + required: + - id + - object + - model + - status + - progress + - created_at + - completed_at + - expires_at + - prompt + - size + - seconds + - remixed_from_video_id + - error + title: Video job + description: Structured information describing a generated video job. + VideoListResource: + properties: + object: + type: string + enum: + - list + description: The type of object returned, must be `list`. + default: list + x-stainless-const: true + data: + items: + $ref: '#/components/schemas/VideoResource' + type: array + description: A list of items + first_id: + anyOf: + - type: string + description: The ID of the first item in the list. + - type: 'null' + last_id: + anyOf: + - type: string + description: The ID of the last item in the list. + - type: 'null' + has_more: + type: boolean + description: Whether there are more items available. + type: object + required: + - object + - data + - first_id + - last_id + - has_more + ImageRefParam-2: + properties: + image_url: + type: string + maxLength: 20971520 + description: A fully qualified URL or base64-encoded data URL. + file_id: + type: string + example: file-123 + type: object + required: [] + VideoSeconds: + type: string + enum: + - '4' + - '8' + - '12' + CreateVideoMultipartBody: + properties: + model: + $ref: '#/components/schemas/VideoModel' + description: >- + The video generation model to use (allowed values: sora-2, + sora-2-pro). Defaults to `sora-2`. + prompt: + type: string + maxLength: 32000 + minLength: 1 + description: Text prompt that describes the video to generate. + input_reference: + oneOf: + - type: string + format: binary + description: >- + Optional reference asset upload or reference object that guides + generation. + - $ref: '#/components/schemas/ImageRefParam-2' + seconds: + $ref: '#/components/schemas/VideoSeconds' + description: >- + Clip duration in seconds (allowed values: 4, 8, 12). Defaults to 4 + seconds. + size: + $ref: '#/components/schemas/VideoSize' + description: >- + Output resolution formatted as width x height (allowed values: + 720x1280, 1280x720, 1024x1792, 1792x1024). Defaults to 720x1280. + type: object + required: + - prompt + title: Create video multipart request + description: Multipart parameters for creating a new video generation job. + CreateVideoJsonBody: + properties: + model: + $ref: '#/components/schemas/VideoModel' + description: >- + The video generation model to use (allowed values: sora-2, + sora-2-pro). Defaults to `sora-2`. + prompt: + type: string + maxLength: 32000 + minLength: 1 + description: Text prompt that describes the video to generate. + input_reference: + $ref: '#/components/schemas/ImageRefParam-2' + description: >- + Optional reference object that guides generation. Provide exactly + one of `image_url` or `file_id`. + seconds: + $ref: '#/components/schemas/VideoSeconds' + description: >- + Clip duration in seconds (allowed values: 4, 8, 12). Defaults to 4 + seconds. + size: + $ref: '#/components/schemas/VideoSize' + description: >- + Output resolution formatted as width x height (allowed values: + 720x1280, 1280x720, 1024x1792, 1792x1024). Defaults to 720x1280. + type: object + required: + - prompt + title: Create video JSON request + description: JSON parameters for creating a new video generation job. + CreateVideoCharacterBody: + properties: + video: + type: string + format: binary + description: Video file used to create a character. + name: + type: string + maxLength: 80 + minLength: 1 + description: Display name for this API character. + type: object + required: + - video + - name + title: Create character request + description: Parameters for creating a character from an uploaded video. + VideoCharacterResource: + properties: + id: + anyOf: + - type: string + description: Identifier for the character creation cameo. + - type: 'null' + name: + anyOf: + - type: string + description: Display name for the character. + - type: 'null' + created_at: + type: integer + description: Unix timestamp (in seconds) when the character was created. + type: object + required: + - id + - name + - created_at + VideoReferenceInputParam: + properties: + id: + type: string + description: The identifier of the completed video. + example: video_123 + type: object + required: + - id + description: Reference to the completed video. + CreateVideoEditMultipartBody: + properties: + video: + oneOf: + - type: string + format: binary + description: Reference to the completed video to edit. + - $ref: '#/components/schemas/VideoReferenceInputParam' + prompt: + type: string + maxLength: 32000 + minLength: 1 + description: Text prompt that describes how to edit the source video. + type: object + required: + - video + - prompt + title: Create video edit multipart request + description: Parameters for editing an existing generated video. + CreateVideoEditJsonBody: + properties: + video: + $ref: '#/components/schemas/VideoReferenceInputParam' + description: Reference to the completed video to edit. + prompt: + type: string + maxLength: 32000 + minLength: 1 + description: Text prompt that describes how to edit the source video. + type: object + required: + - video + - prompt + title: Create video edit JSON request + description: JSON parameters for editing an existing generated video. + CreateVideoExtendMultipartBody: + properties: + video: + oneOf: + - $ref: '#/components/schemas/VideoReferenceInputParam' + - type: string + format: binary + description: Reference to the completed video to extend. + prompt: + type: string + maxLength: 32000 + minLength: 1 + description: Updated text prompt that directs the extension generation. + seconds: + $ref: '#/components/schemas/VideoSeconds' + description: >- + Length of the newly generated extension segment in seconds (allowed + values: 4, 8, 12, 16, 20). + type: object + required: + - video + - prompt + - seconds + title: Create video extension multipart request + description: Multipart parameters for extending an existing generated video. + CreateVideoExtendJsonBody: + properties: + video: + $ref: '#/components/schemas/VideoReferenceInputParam' + description: Reference to the completed video to extend. + prompt: + type: string + maxLength: 32000 + minLength: 1 + description: Updated text prompt that directs the extension generation. + seconds: + $ref: '#/components/schemas/VideoSeconds' + description: >- + Length of the newly generated extension segment in seconds (allowed + values: 4, 8, 12, 16, 20). + type: object + required: + - video + - prompt + - seconds + title: Create video extension JSON request + description: JSON parameters for extending an existing generated video. + DeletedVideoResource: + properties: + object: + type: string + enum: + - video.deleted + description: The object type that signals the deletion response. + default: video.deleted + x-stainless-const: true + deleted: + type: boolean + description: Indicates that the video resource was deleted. + id: + type: string + description: Identifier of the deleted video. + type: object + required: + - object + - deleted + - id + title: Deleted video response + description: Confirmation payload returned after deleting a video. + VideoContentVariant: + type: string + enum: + - video + - thumbnail + - spritesheet + CreateVideoRemixBody: + properties: + prompt: + type: string + maxLength: 32000 + minLength: 1 + description: Updated text prompt that directs the remix generation. + type: object + required: + - prompt + title: Create video remix request + description: Parameters for remixing an existing generated video. + TruncationEnum: + type: string + enum: + - auto + - disabled + TokenCountsBody: + properties: + model: + anyOf: + - type: string + description: >- + Model ID used to generate the response, like `gpt-4o` or `o3`. + OpenAI offers a wide range of models with different + capabilities, performance characteristics, and price points. + Refer to the [model guide](/docs/models) to browse and compare + available models. + - type: 'null' + input: + anyOf: + - oneOf: + - type: string + maxLength: 10485760 + description: >- + A text input to the model, equivalent to a text input with + the `user` role. + - items: + $ref: '#/components/schemas/InputItem' + type: array + description: >- + A list of one or many input items to the model, containing + different content types. + description: >- + Text, image, or file inputs to the model, used to generate a + response + - type: 'null' + previous_response_id: + anyOf: + - type: string + description: >- + The unique ID of the previous response to the model. Use this to + create multi-turn conversations. Learn more about [conversation + state](/docs/guides/conversation-state). Cannot be used in + conjunction with `conversation`. + example: resp_123 + - type: 'null' + tools: + anyOf: + - items: + $ref: '#/components/schemas/Tool' + type: array + description: >- + An array of tools the model may call while generating a + response. You can specify which tool to use by setting the + `tool_choice` parameter. + - type: 'null' + text: + anyOf: + - $ref: '#/components/schemas/ResponseTextParam' + - type: 'null' + reasoning: + anyOf: + - $ref: '#/components/schemas/Reasoning' + description: >- + **gpt-5 and o-series models only** Configuration options for + [reasoning + models](https://platform.openai.com/docs/guides/reasoning). + - type: 'null' + truncation: + $ref: '#/components/schemas/TruncationEnum' + description: >- + The truncation strategy to use for the model response. - `auto`: If + the input to this Response exceeds the model's context window size, + the model will truncate the response to fit the context window by + dropping items from the beginning of the conversation. - `disabled` + (default): If the input size will exceed the context window size for + a model, the request will fail with a 400 error. + instructions: + anyOf: + - type: string + description: >- + A system (or developer) message inserted into the model's + context. + + When used along with `previous_response_id`, the instructions + from a previous response will not be carried over to the next + response. This makes it simple to swap out system (or developer) + messages in new responses. + - type: 'null' + conversation: + anyOf: + - $ref: '#/components/schemas/ConversationParam' + - type: 'null' + tool_choice: + anyOf: + - $ref: '#/components/schemas/ToolChoiceParam' + description: Controls which tool the model should use, if any. + - type: 'null' + parallel_tool_calls: + anyOf: + - type: boolean + description: Whether to allow the model to run tool calls in parallel. + - type: 'null' + type: object + required: [] + TokenCountsResource: + properties: + object: + type: string + enum: + - response.input_tokens + default: response.input_tokens + x-stainless-const: true + input_tokens: + type: integer + type: object + required: + - object + - input_tokens + title: Token counts + example: + object: response.input_tokens + input_tokens: 123 + PromptCacheRetentionEnum: + type: string + enum: + - in_memory + - 24h + CompactResponseMethodPublicBody: + properties: + model: + $ref: '#/components/schemas/ModelIdsCompaction' + input: + anyOf: + - oneOf: + - type: string + maxLength: 10485760 + description: >- + A text input to the model, equivalent to a text input with + the `user` role. + - items: + $ref: '#/components/schemas/InputItem' + type: array + description: >- + A list of one or many input items to the model, containing + different content types. + description: >- + Text, image, or file inputs to the model, used to generate a + response + - type: 'null' + previous_response_id: + anyOf: + - type: string + description: >- + The unique ID of the previous response to the model. Use this to + create multi-turn conversations. Learn more about [conversation + state](/docs/guides/conversation-state). Cannot be used in + conjunction with `conversation`. + example: resp_123 + - type: 'null' + instructions: + anyOf: + - type: string + description: >- + A system (or developer) message inserted into the model's + context. + + When used along with `previous_response_id`, the instructions + from a previous response will not be carried over to the next + response. This makes it simple to swap out system (or developer) + messages in new responses. + - type: 'null' + prompt_cache_key: + anyOf: + - type: string + maxLength: 64 + description: A key to use when reading from or writing to the prompt cache. + - type: 'null' + prompt_cache_retention: + anyOf: + - $ref: '#/components/schemas/PromptCacheRetentionEnum' + description: How long to retain a prompt cache entry created by this request. + - type: 'null' + type: object + required: + - model + ItemField: + oneOf: + - $ref: '#/components/schemas/Message' + - $ref: '#/components/schemas/FunctionToolCall' + - $ref: '#/components/schemas/ToolSearchCall' + - $ref: '#/components/schemas/ToolSearchOutput' + - $ref: '#/components/schemas/FunctionToolCallOutput' + - $ref: '#/components/schemas/FileSearchToolCall' + - $ref: '#/components/schemas/WebSearchToolCall' + - $ref: '#/components/schemas/ImageGenToolCall' + - $ref: '#/components/schemas/ComputerToolCall' + - $ref: '#/components/schemas/ComputerToolCallOutputResource' + - $ref: '#/components/schemas/ReasoningItem' + - $ref: '#/components/schemas/CompactionBody' + - $ref: '#/components/schemas/CodeInterpreterToolCall' + - $ref: '#/components/schemas/LocalShellToolCall' + - $ref: '#/components/schemas/LocalShellToolCallOutput' + - $ref: '#/components/schemas/FunctionShellCall' + - $ref: '#/components/schemas/FunctionShellCallOutput' + - $ref: '#/components/schemas/ApplyPatchToolCall' + - $ref: '#/components/schemas/ApplyPatchToolCallOutput' + - $ref: '#/components/schemas/MCPListTools' + - $ref: '#/components/schemas/MCPApprovalRequest' + - $ref: '#/components/schemas/MCPApprovalResponseResource' + - $ref: '#/components/schemas/MCPToolCall' + - $ref: '#/components/schemas/CustomToolCall' + - $ref: '#/components/schemas/CustomToolCallOutput' + description: >- + An item representing a message, tool call, tool output, reasoning, or + other response element. + discriminator: + propertyName: type + CompactResource: + properties: + id: + type: string + description: The unique identifier for the compacted response. + object: + type: string + enum: + - response.compaction + description: The object type. Always `response.compaction`. + default: response.compaction + x-stainless-const: true + output: + items: + $ref: '#/components/schemas/ItemField' + type: array + description: The compacted list of output items. + created_at: + type: integer + description: >- + Unix timestamp (in seconds) when the compacted conversation was + created. + usage: + $ref: '#/components/schemas/ResponseUsage' + description: >- + Token accounting for the compaction pass, including cached, + reasoning, and total tokens. + type: object + required: + - id + - object + - output + - created_at + - usage + title: The compacted response object + example: + id: resp_001 + object: response.compaction + output: + - type: message + role: user + content: + - type: input_text + text: Summarize our launch checklist from last week. + - type: message + role: user + content: + - type: input_text + text: You are performing a CONTEXT CHECKPOINT COMPACTION... + - type: compaction + id: cmp_001 + encrypted_content: encrypted-summary + created_at: 1731459200 + usage: + input_tokens: 42897 + output_tokens: 12000 + total_tokens: 54912 + SkillResource: + properties: + id: + type: string + description: Unique identifier for the skill. + object: + type: string + enum: + - skill + description: The object type, which is `skill`. + default: skill + x-stainless-const: true + name: + type: string + description: Name of the skill. + description: + type: string + description: Description of the skill. + created_at: + type: integer + description: Unix timestamp (seconds) for when the skill was created. + default_version: + type: string + description: Default version for the skill. + latest_version: + type: string + description: Latest version for the skill. + type: object + required: + - id + - object + - name + - description + - created_at + - default_version + - latest_version + SkillListResource: + properties: + object: + type: string + enum: + - list + description: The type of object returned, must be `list`. + default: list + x-stainless-const: true + data: + items: + $ref: '#/components/schemas/SkillResource' + type: array + description: A list of items + first_id: + anyOf: + - type: string + description: The ID of the first item in the list. + - type: 'null' + last_id: + anyOf: + - type: string + description: The ID of the last item in the list. + - type: 'null' + has_more: + type: boolean + description: Whether there are more items available. + type: object + required: + - object + - data + - first_id + - last_id + - has_more + CreateSkillBody: + properties: + files: + oneOf: + - items: + type: string + format: binary + type: array + maxItems: 500 + description: Skill files to upload (directory upload) or a single zip file. + - type: string + format: binary + description: Skill zip file to upload. + type: object + required: + - files + title: Create skill request + description: >- + Uploads a skill either as a directory (multipart `files[]`) or as a + single zip file. + SetDefaultSkillVersionBody: + properties: + default_version: + type: string + description: The skill version number to set as default. + type: object + required: + - default_version + title: Update skill request + description: Updates the default version pointer for a skill. + DeletedSkillResource: + properties: + object: + type: string + enum: + - skill.deleted + default: skill.deleted + x-stainless-const: true + deleted: + type: boolean + id: + type: string + type: object + required: + - object + - deleted + - id + SkillVersionResource: + properties: + object: + type: string + enum: + - skill.version + description: The object type, which is `skill.version`. + default: skill.version + x-stainless-const: true + id: + type: string + description: Unique identifier for the skill version. + skill_id: + type: string + description: Identifier of the skill for this version. + version: + type: string + description: Version number for this skill. + created_at: + type: integer + description: Unix timestamp (seconds) for when the version was created. + name: + type: string + description: Name of the skill version. + description: + type: string + description: Description of the skill version. + type: object + required: + - object + - id + - skill_id + - version + - created_at + - name + - description + SkillVersionListResource: + properties: + object: + type: string + enum: + - list + description: The type of object returned, must be `list`. + default: list + x-stainless-const: true + data: + items: + $ref: '#/components/schemas/SkillVersionResource' + type: array + description: A list of items + first_id: + anyOf: + - type: string + description: The ID of the first item in the list. + - type: 'null' + last_id: + anyOf: + - type: string + description: The ID of the last item in the list. + - type: 'null' + has_more: + type: boolean + description: Whether there are more items available. + type: object + required: + - object + - data + - first_id + - last_id + - has_more + CreateSkillVersionBody: + properties: + files: + oneOf: + - items: + type: string + format: binary + type: array + maxItems: 500 + description: Skill files to upload (directory upload) or a single zip file. + - type: string + format: binary + description: Skill zip file to upload. + default: + type: boolean + description: Whether to set this version as the default. + type: object + required: + - files + title: Create skill version request + description: Uploads a new immutable version of a skill. + DeletedSkillVersionResource: + properties: + object: + type: string + enum: + - skill.version.deleted + default: skill.version.deleted + x-stainless-const: true + deleted: + type: boolean + id: + type: string + version: + type: string + description: The deleted skill version. + type: object + required: + - object + - deleted + - id + - version + ChatkitWorkflowTracing: + properties: + enabled: + type: boolean + description: Indicates whether tracing is enabled. + type: object + required: + - enabled + title: Tracing Configuration + description: Controls diagnostic tracing during the session. + ChatkitWorkflow: + properties: + id: + type: string + description: Identifier of the workflow backing the session. + version: + anyOf: + - type: string + description: >- + Specific workflow version used for the session. Defaults to null + when using the latest deployment. + - type: 'null' + state_variables: + anyOf: + - additionalProperties: + oneOf: + - type: string + - type: integer + - type: boolean + - type: number + type: object + description: >- + State variable key-value pairs applied when invoking the + workflow. Defaults to null when no overrides were provided. + x-oaiTypeLabel: map + - type: 'null' + tracing: + $ref: '#/components/schemas/ChatkitWorkflowTracing' + description: Tracing settings applied to the workflow. + type: object + required: + - id + - version + - state_variables + - tracing + title: Workflow + description: Workflow metadata and state returned for the session. + ChatSessionRateLimits: + properties: + max_requests_per_1_minute: + type: integer + description: Maximum allowed requests per one-minute window. + type: object + required: + - max_requests_per_1_minute + title: Rate limits + description: Active per-minute request limit for the session. + ChatSessionStatus: + type: string + enum: + - active + - expired + - cancelled + ChatSessionAutomaticThreadTitling: + properties: + enabled: + type: boolean + description: Whether automatic thread titling is enabled. + type: object + required: + - enabled + title: Automatic thread titling + description: Automatic thread title preferences for the session. + ChatSessionFileUpload: + properties: + enabled: + type: boolean + description: Indicates if uploads are enabled for the session. + max_file_size: + anyOf: + - type: integer + description: Maximum upload size in megabytes. + - type: 'null' + max_files: + anyOf: + - type: integer + description: Maximum number of uploads allowed during the session. + - type: 'null' + type: object + required: + - enabled + - max_file_size + - max_files + title: File upload settings + description: Upload permissions and limits applied to the session. + ChatSessionHistory: + properties: + enabled: + type: boolean + description: Indicates if chat history is persisted for the session. + recent_threads: + anyOf: + - type: integer + description: >- + Number of prior threads surfaced in history views. Defaults to + null when all history is retained. + - type: 'null' + type: object + required: + - enabled + - recent_threads + title: History settings + description: History retention preferences returned for the session. + ChatSessionChatkitConfiguration: + properties: + automatic_thread_titling: + $ref: '#/components/schemas/ChatSessionAutomaticThreadTitling' + description: Automatic thread titling preferences. + file_upload: + $ref: '#/components/schemas/ChatSessionFileUpload' + description: Upload settings for the session. + history: + $ref: '#/components/schemas/ChatSessionHistory' + description: History retention configuration. + type: object + required: + - automatic_thread_titling + - file_upload + - history + title: ChatKit configuration + description: ChatKit configuration for the session. + ChatSessionResource: + properties: + id: + type: string + description: Identifier for the ChatKit session. + object: + type: string + enum: + - chatkit.session + description: Type discriminator that is always `chatkit.session`. + default: chatkit.session + x-stainless-const: true + expires_at: + type: integer + description: Unix timestamp (in seconds) for when the session expires. + client_secret: + type: string + description: Ephemeral client secret that authenticates session requests. + workflow: + $ref: '#/components/schemas/ChatkitWorkflow' + description: Workflow metadata for the session. + user: + type: string + description: User identifier associated with the session. + rate_limits: + $ref: '#/components/schemas/ChatSessionRateLimits' + description: Resolved rate limit values. + max_requests_per_1_minute: + type: integer + description: Convenience copy of the per-minute request limit. + status: + $ref: '#/components/schemas/ChatSessionStatus' + description: Current lifecycle state of the session. + chatkit_configuration: + $ref: '#/components/schemas/ChatSessionChatkitConfiguration' + description: Resolved ChatKit feature configuration for the session. + type: object + required: + - id + - object + - expires_at + - client_secret + - workflow + - user + - rate_limits + - max_requests_per_1_minute + - status + - chatkit_configuration + title: The chat session object + description: Represents a ChatKit session and its resolved configuration. + example: + id: cksess_123 + object: chatkit.session + client_secret: ek_token_123 + expires_at: 1712349876 + workflow: + id: workflow_alpha + version: 2024-10-01T00:00:00.000Z + user: user_789 + rate_limits: + max_requests_per_1_minute: 60 + max_requests_per_1_minute: 60 + status: cancelled + chatkit_configuration: + automatic_thread_titling: + enabled: true + file_upload: + enabled: true + max_file_size: 16 + max_files: 20 + history: + enabled: true + recent_threads: 10 + WorkflowTracingParam: + properties: + enabled: + type: boolean + description: Whether tracing is enabled during the session. Defaults to true. + type: object + required: [] + title: Tracing Configuration + description: Controls diagnostic tracing during the session. + WorkflowParam: + properties: + id: + type: string + description: Identifier for the workflow invoked by the session. + version: + type: string + description: >- + Specific workflow version to run. Defaults to the latest deployed + version. + state_variables: + additionalProperties: + oneOf: + - type: string + maxLength: 10485760 + - type: integer + - type: boolean + - type: number + type: object + maxProperties: 64 + description: >- + State variables forwarded to the workflow. Keys may be up to 64 + characters, values must be primitive types, and the map defaults to + an empty object. + x-oaiTypeLabel: map + tracing: + $ref: '#/components/schemas/WorkflowTracingParam' + description: >- + Optional tracing overrides for the workflow invocation. When + omitted, tracing is enabled by default. + type: object + required: + - id + title: Workflow settings + description: Workflow reference and overrides applied to the chat session. + ExpiresAfterParam: + properties: + anchor: + type: string + enum: + - created_at + description: >- + Base timestamp used to calculate expiration. Currently fixed to + `created_at`. + default: created_at + x-stainless-const: true + seconds: + type: integer + maximum: 600 + minimum: 1 + description: Number of seconds after the anchor when the session expires. + type: object + required: + - anchor + - seconds + title: Expiration overrides + description: Controls when the session expires relative to an anchor timestamp. + RateLimitsParam: + properties: + max_requests_per_1_minute: + type: integer + minimum: 1 + description: >- + Maximum number of requests allowed per minute for the session. + Defaults to 10. + type: object + required: [] + title: Rate limit overrides + description: Controls request rate limits for the session. + AutomaticThreadTitlingParam: + properties: + enabled: + type: boolean + description: Enable automatic thread title generation. Defaults to true. + type: object + required: [] + title: Automatic thread titling configuration + description: Controls whether ChatKit automatically generates thread titles. + FileUploadParam: + properties: + enabled: + type: boolean + description: Enable uploads for this session. Defaults to false. + max_file_size: + type: integer + maximum: 512 + minimum: 1 + description: >- + Maximum size in megabytes for each uploaded file. Defaults to 512 + MB, which is the maximum allowable size. + max_files: + type: integer + minimum: 1 + description: >- + Maximum number of files that can be uploaded to the session. + Defaults to 10. + type: object + required: [] + title: File upload configuration + description: Controls whether users can upload files. + HistoryParam: + properties: + enabled: + type: boolean + description: >- + Enables chat users to access previous ChatKit threads. Defaults to + true. + recent_threads: + type: integer + minimum: 1 + description: >- + Number of recent ChatKit threads users have access to. Defaults to + unlimited when unset. + type: object + required: [] + title: Chat history configuration + description: Controls how much historical context is retained for the session. + ChatkitConfigurationParam: + properties: + automatic_thread_titling: + $ref: '#/components/schemas/AutomaticThreadTitlingParam' + description: >- + Configuration for automatic thread titling. When omitted, automatic + thread titling is enabled by default. + file_upload: + $ref: '#/components/schemas/FileUploadParam' + description: >- + Configuration for upload enablement and limits. When omitted, + uploads are disabled by default (max_files 10, max_file_size 512 + MB). + history: + $ref: '#/components/schemas/HistoryParam' + description: >- + Configuration for chat history retention. When omitted, history is + enabled by default with no limit on recent_threads (null). + type: object + required: [] + title: ChatKit configuration overrides + description: Optional per-session configuration settings for ChatKit behavior. + CreateChatSessionBody: + properties: + workflow: + $ref: '#/components/schemas/WorkflowParam' + description: Workflow that powers the session. + user: + type: string + minLength: 1 + description: >- + A free-form string that identifies your end user; ensures this + Session can access other objects that have the same `user` scope. + expires_after: + $ref: '#/components/schemas/ExpiresAfterParam' + description: >- + Optional override for session expiration timing in seconds from + creation. Defaults to 10 minutes. + rate_limits: + $ref: '#/components/schemas/RateLimitsParam' + description: >- + Optional override for per-minute request limits. When omitted, + defaults to 10. + chatkit_configuration: + $ref: '#/components/schemas/ChatkitConfigurationParam' + description: Optional overrides for ChatKit runtime configuration features + type: object + required: + - workflow + - user + title: Create chat session request + description: Parameters for provisioning a new ChatKit session. + UserMessageInputText: + properties: + type: + type: string + enum: + - input_text + description: Type discriminator that is always `input_text`. + default: input_text + x-stainless-const: true + text: + type: string + description: Plain-text content supplied by the user. + type: object + required: + - type + - text + title: User message input + description: Text block that a user contributed to the thread. + UserMessageQuotedText: + properties: + type: + type: string + enum: + - quoted_text + description: Type discriminator that is always `quoted_text`. + default: quoted_text + x-stainless-const: true + text: + type: string + description: Quoted text content. + type: object + required: + - type + - text + title: User message quoted text + description: Quoted snippet that the user referenced in their message. + AttachmentType: + type: string + enum: + - image + - file + Attachment: + properties: + type: + $ref: '#/components/schemas/AttachmentType' + description: Attachment discriminator. + id: + type: string + description: Identifier for the attachment. + name: + type: string + description: Original display name for the attachment. + mime_type: + type: string + description: MIME type of the attachment. + preview_url: + anyOf: + - type: string + description: Preview URL for rendering the attachment inline. + - type: 'null' + type: object + required: + - type + - id + - name + - mime_type + - preview_url + title: Attachment + description: Attachment metadata included on thread items. + ToolChoice: + properties: + id: + type: string + description: Identifier of the requested tool. + type: object + required: + - id + title: Tool choice + description: Tool selection that the assistant should honor when executing the item. + InferenceOptions: + properties: + tool_choice: + anyOf: + - $ref: '#/components/schemas/ToolChoice' + description: >- + Preferred tool to invoke. Defaults to null when ChatKit should + auto-select. + - type: 'null' + model: + anyOf: + - type: string + description: >- + Model name that generated the response. Defaults to null when + using the session default. + - type: 'null' + type: object + required: + - tool_choice + - model + title: Inference options + description: Model and tool overrides applied when generating the assistant response. + UserMessageItem: + properties: + id: + type: string + description: Identifier of the thread item. + object: + type: string + enum: + - chatkit.thread_item + description: Type discriminator that is always `chatkit.thread_item`. + default: chatkit.thread_item + x-stainless-const: true + created_at: + type: integer + description: Unix timestamp (in seconds) for when the item was created. + thread_id: + type: string + description: Identifier of the parent thread. + type: + type: string + enum: + - chatkit.user_message + default: chatkit.user_message + x-stainless-const: true + content: + items: + oneOf: + - $ref: '#/components/schemas/UserMessageInputText' + - $ref: '#/components/schemas/UserMessageQuotedText' + description: Content blocks that comprise a user message. + discriminator: + propertyName: type + type: array + description: Ordered content elements supplied by the user. + attachments: + items: + $ref: '#/components/schemas/Attachment' + type: array + description: >- + Attachments associated with the user message. Defaults to an empty + list. + inference_options: + anyOf: + - $ref: '#/components/schemas/InferenceOptions' + description: >- + Inference overrides applied to the message. Defaults to null + when unset. + - type: 'null' + type: object + required: + - id + - object + - created_at + - thread_id + - type + - content + - attachments + - inference_options + title: User Message Item + description: User-authored messages within a thread. + FileAnnotationSource: + properties: + type: + type: string + enum: + - file + description: Type discriminator that is always `file`. + default: file + x-stainless-const: true + filename: + type: string + description: Filename referenced by the annotation. + type: object + required: + - type + - filename + title: File annotation source + description: Attachment source referenced by an annotation. + FileAnnotation: + properties: + type: + type: string + enum: + - file + description: Type discriminator that is always `file` for this annotation. + default: file + x-stainless-const: true + source: + $ref: '#/components/schemas/FileAnnotationSource' + description: File attachment referenced by the annotation. + type: object + required: + - type + - source + title: File annotation + description: Annotation that references an uploaded file. + UrlAnnotationSource: + properties: + type: + type: string + enum: + - url + description: Type discriminator that is always `url`. + default: url + x-stainless-const: true + url: + type: string + description: URL referenced by the annotation. + type: object + required: + - type + - url + title: URL annotation source + description: URL backing an annotation entry. + UrlAnnotation: + properties: + type: + type: string + enum: + - url + description: Type discriminator that is always `url` for this annotation. + default: url + x-stainless-const: true + source: + $ref: '#/components/schemas/UrlAnnotationSource' + description: URL referenced by the annotation. + type: object + required: + - type + - source + title: URL annotation + description: Annotation that references a URL. + ResponseOutputText: + properties: + type: + type: string + enum: + - output_text + description: Type discriminator that is always `output_text`. + default: output_text + x-stainless-const: true + text: + type: string + description: Assistant generated text. + annotations: + items: + oneOf: + - $ref: '#/components/schemas/FileAnnotation' + - $ref: '#/components/schemas/UrlAnnotation' + description: Annotation object describing a cited source. + discriminator: + propertyName: type + type: array + description: Ordered list of annotations attached to the response text. + type: object + required: + - type + - text + - annotations + title: Assistant message content + description: Assistant response text accompanied by optional annotations. + AssistantMessageItem: + properties: + id: + type: string + description: Identifier of the thread item. + object: + type: string + enum: + - chatkit.thread_item + description: Type discriminator that is always `chatkit.thread_item`. + default: chatkit.thread_item + x-stainless-const: true + created_at: + type: integer + description: Unix timestamp (in seconds) for when the item was created. + thread_id: + type: string + description: Identifier of the parent thread. + type: + type: string + enum: + - chatkit.assistant_message + description: Type discriminator that is always `chatkit.assistant_message`. + default: chatkit.assistant_message + x-stainless-const: true + content: + items: + $ref: '#/components/schemas/ResponseOutputText' + type: array + description: Ordered assistant response segments. + type: object + required: + - id + - object + - created_at + - thread_id + - type + - content + title: Assistant message + description: Assistant-authored message within a thread. + WidgetMessageItem: + properties: + id: + type: string + description: Identifier of the thread item. + object: + type: string + enum: + - chatkit.thread_item + description: Type discriminator that is always `chatkit.thread_item`. + default: chatkit.thread_item + x-stainless-const: true + created_at: + type: integer + description: Unix timestamp (in seconds) for when the item was created. + thread_id: + type: string + description: Identifier of the parent thread. + type: + type: string + enum: + - chatkit.widget + description: Type discriminator that is always `chatkit.widget`. + default: chatkit.widget + x-stainless-const: true + widget: + type: string + description: Serialized widget payload rendered in the UI. + type: object + required: + - id + - object + - created_at + - thread_id + - type + - widget + title: Widget message + description: Thread item that renders a widget payload. + ClientToolCallStatus: + type: string + enum: + - in_progress + - completed + ClientToolCallItem: + properties: + id: + type: string + description: Identifier of the thread item. + object: + type: string + enum: + - chatkit.thread_item + description: Type discriminator that is always `chatkit.thread_item`. + default: chatkit.thread_item + x-stainless-const: true + created_at: + type: integer + description: Unix timestamp (in seconds) for when the item was created. + thread_id: + type: string + description: Identifier of the parent thread. + type: + type: string + enum: + - chatkit.client_tool_call + description: Type discriminator that is always `chatkit.client_tool_call`. + default: chatkit.client_tool_call + x-stainless-const: true + status: + $ref: '#/components/schemas/ClientToolCallStatus' + description: Execution status for the tool call. + call_id: + type: string + description: Identifier for the client tool call. + name: + type: string + description: Tool name that was invoked. + arguments: + type: string + description: JSON-encoded arguments that were sent to the tool. + output: + anyOf: + - type: string + description: >- + JSON-encoded output captured from the tool. Defaults to null + while execution is in progress. + - type: 'null' + type: object + required: + - id + - object + - created_at + - thread_id + - type + - status + - call_id + - name + - arguments + - output + title: Client tool call + description: Record of a client side tool invocation initiated by the assistant. + TaskType: + type: string + enum: + - custom + - thought + TaskItem: + properties: + id: + type: string + description: Identifier of the thread item. + object: + type: string + enum: + - chatkit.thread_item + description: Type discriminator that is always `chatkit.thread_item`. + default: chatkit.thread_item + x-stainless-const: true + created_at: + type: integer + description: Unix timestamp (in seconds) for when the item was created. + thread_id: + type: string + description: Identifier of the parent thread. + type: + type: string + enum: + - chatkit.task + description: Type discriminator that is always `chatkit.task`. + default: chatkit.task + x-stainless-const: true + task_type: + $ref: '#/components/schemas/TaskType' + description: Subtype for the task. + heading: + anyOf: + - type: string + description: >- + Optional heading for the task. Defaults to null when not + provided. + - type: 'null' + summary: + anyOf: + - type: string + description: >- + Optional summary that describes the task. Defaults to null when + omitted. + - type: 'null' + type: object + required: + - id + - object + - created_at + - thread_id + - type + - task_type + - heading + - summary + title: Task item + description: Task emitted by the workflow to show progress and status updates. + TaskGroupTask: + properties: + type: + $ref: '#/components/schemas/TaskType' + description: Subtype for the grouped task. + heading: + anyOf: + - type: string + description: >- + Optional heading for the grouped task. Defaults to null when not + provided. + - type: 'null' + summary: + anyOf: + - type: string + description: >- + Optional summary that describes the grouped task. Defaults to + null when omitted. + - type: 'null' + type: object + required: + - type + - heading + - summary + title: Task group task + description: Task entry that appears within a TaskGroup. + TaskGroupItem: + properties: + id: + type: string + description: Identifier of the thread item. + object: + type: string + enum: + - chatkit.thread_item + description: Type discriminator that is always `chatkit.thread_item`. + default: chatkit.thread_item + x-stainless-const: true + created_at: + type: integer + description: Unix timestamp (in seconds) for when the item was created. + thread_id: + type: string + description: Identifier of the parent thread. + type: + type: string + enum: + - chatkit.task_group + description: Type discriminator that is always `chatkit.task_group`. + default: chatkit.task_group + x-stainless-const: true + tasks: + items: + $ref: '#/components/schemas/TaskGroupTask' + type: array + description: Tasks included in the group. + type: object + required: + - id + - object + - created_at + - thread_id + - type + - tasks + title: Task group + description: Collection of workflow tasks grouped together in the thread. + ThreadItem: + oneOf: + - $ref: '#/components/schemas/UserMessageItem' + - $ref: '#/components/schemas/AssistantMessageItem' + - $ref: '#/components/schemas/WidgetMessageItem' + - $ref: '#/components/schemas/ClientToolCallItem' + - $ref: '#/components/schemas/TaskItem' + - $ref: '#/components/schemas/TaskGroupItem' + title: The thread item + discriminator: + propertyName: type + ThreadItemListResource: + properties: + object: + type: string + enum: + - list + description: The type of object returned, must be `list`. + default: list + x-stainless-const: true + data: + items: + $ref: '#/components/schemas/ThreadItem' + type: array + description: A list of items + first_id: + anyOf: + - type: string + description: The ID of the first item in the list. + - type: 'null' + last_id: + anyOf: + - type: string + description: The ID of the last item in the list. + - type: 'null' + has_more: + type: boolean + description: Whether there are more items available. + type: object + required: + - object + - data + - first_id + - last_id + - has_more + title: Thread Items + description: A paginated list of thread items rendered for the ChatKit API. + ActiveStatus: + properties: + type: + type: string + enum: + - active + description: Status discriminator that is always `active`. + default: active + x-stainless-const: true + type: object + required: + - type + title: Active thread status + description: Indicates that a thread is active. + LockedStatus: + properties: + type: + type: string + enum: + - locked + description: Status discriminator that is always `locked`. + default: locked + x-stainless-const: true + reason: + anyOf: + - type: string + description: >- + Reason that the thread was locked. Defaults to null when no + reason is recorded. + - type: 'null' + type: object + required: + - type + - reason + title: Locked thread status + description: Indicates that a thread is locked and cannot accept new input. + ClosedStatus: + properties: + type: + type: string + enum: + - closed + description: Status discriminator that is always `closed`. + default: closed + x-stainless-const: true + reason: + anyOf: + - type: string + description: >- + Reason that the thread was closed. Defaults to null when no + reason is recorded. + - type: 'null' + type: object + required: + - type + - reason + title: Closed thread status + description: Indicates that a thread has been closed. + ThreadResource: + properties: + id: + type: string + description: Identifier of the thread. + object: + type: string + enum: + - chatkit.thread + description: Type discriminator that is always `chatkit.thread`. + default: chatkit.thread + x-stainless-const: true + created_at: + type: integer + description: Unix timestamp (in seconds) for when the thread was created. + title: + anyOf: + - type: string + description: >- + Optional human-readable title for the thread. Defaults to null + when no title has been generated. + - type: 'null' + status: + oneOf: + - $ref: '#/components/schemas/ActiveStatus' + - $ref: '#/components/schemas/LockedStatus' + - $ref: '#/components/schemas/ClosedStatus' + description: >- + Current status for the thread. Defaults to `active` for newly + created threads. + discriminator: + propertyName: type + user: + type: string + description: Free-form string that identifies your end user who owns the thread. + type: object + required: + - id + - object + - created_at + - title + - status + - user + title: The thread object + description: Represents a ChatKit thread and its current status. + example: + id: cthr_def456 + object: chatkit.thread + created_at: 1712345600 + title: Demo feedback + status: + type: active + user: user_456 + DeletedThreadResource: + properties: + id: + type: string + description: Identifier of the deleted thread. + object: + type: string + enum: + - chatkit.thread.deleted + description: Type discriminator that is always `chatkit.thread.deleted`. + default: chatkit.thread.deleted + x-stainless-const: true + deleted: + type: boolean + description: Indicates that the thread has been deleted. + type: object + required: + - id + - object + - deleted + title: Deleted thread + description: Confirmation payload returned after deleting a thread. + ThreadListResource: + properties: + object: + type: string + enum: + - list + description: The type of object returned, must be `list`. + default: list + x-stainless-const: true + data: + items: + $ref: '#/components/schemas/ThreadResource' + type: array + description: A list of items + first_id: + anyOf: + - type: string + description: The ID of the first item in the list. + - type: 'null' + last_id: + anyOf: + - type: string + description: The ID of the last item in the list. + - type: 'null' + has_more: + type: boolean + description: Whether there are more items available. + type: object + required: + - object + - data + - first_id + - last_id + - has_more + title: Threads + description: A paginated list of ChatKit threads. + DragPoint: + properties: + x: + type: integer + description: The x-coordinate. + 'y': + type: integer + description: The y-coordinate. + type: object + required: + - x + - 'y' + title: Coordinate + description: 'An x/y coordinate pair, e.g. `{ x: 100, y: 200 }`.' + securitySchemes: + ApiKeyAuth: + type: http + scheme: bearer +x-oaiMeta: + navigationGroups: + - id: responses + title: Responses API + - id: webhooks + title: Webhooks + - id: endpoints + title: Platform APIs + - id: vector_stores + title: Vector stores + - id: chatkit + title: ChatKit + beta: true + - id: containers + title: Containers + - id: realtime + title: Realtime + - id: chat + title: Chat Completions + - id: assistants + title: Assistants + deprecated: true + - id: administration + title: Administration + - id: legacy + title: Legacy + groups: + - id: responses-streaming + title: Streaming events + description: > + When you [create a Response](/docs/api-reference/responses/create) with + + `stream` set to `true`, the server will emit server-sent events to the + + client as the Response is generated. This section contains the events + that + + are emitted by the server. + + + [Learn more about streaming + responses](/docs/guides/streaming-responses?api-mode=responses). + navigationGroup: responses + sections: + - type: object + key: ResponseCreatedEvent + path: + - type: object + key: ResponseInProgressEvent + path: + - type: object + key: ResponseCompletedEvent + path: + - type: object + key: ResponseFailedEvent + path: + - type: object + key: ResponseIncompleteEvent + path: + - type: object + key: ResponseOutputItemAddedEvent + path: + - type: object + key: ResponseOutputItemDoneEvent + path: + - type: object + key: ResponseContentPartAddedEvent + path: + - type: object + key: ResponseContentPartDoneEvent + path: + - type: object + key: ResponseTextDeltaEvent + path: response/output_text/delta + - type: object + key: ResponseTextDoneEvent + path: response/output_text/done + - type: object + key: ResponseRefusalDeltaEvent + path: + - type: object + key: ResponseRefusalDoneEvent + path: + - type: object + key: ResponseFunctionCallArgumentsDeltaEvent + path: + - type: object + key: ResponseFunctionCallArgumentsDoneEvent + path: + - type: object + key: ResponseFileSearchCallInProgressEvent + path: + - type: object + key: ResponseFileSearchCallSearchingEvent + path: + - type: object + key: ResponseFileSearchCallCompletedEvent + path: + - type: object + key: ResponseWebSearchCallInProgressEvent + path: + - type: object + key: ResponseWebSearchCallSearchingEvent + path: + - type: object + key: ResponseWebSearchCallCompletedEvent + path: + - type: object + key: ResponseReasoningSummaryPartAddedEvent + path: + - type: object + key: ResponseReasoningSummaryPartDoneEvent + path: + - type: object + key: ResponseReasoningSummaryTextDeltaEvent + path: + - type: object + key: ResponseReasoningSummaryTextDoneEvent + path: + - type: object + key: ResponseReasoningTextDeltaEvent + path: + - type: object + key: ResponseReasoningTextDoneEvent + path: + - type: object + key: ResponseImageGenCallCompletedEvent + path: + - type: object + key: ResponseImageGenCallGeneratingEvent + path: + - type: object + key: ResponseImageGenCallInProgressEvent + path: + - type: object + key: ResponseImageGenCallPartialImageEvent + path: + - type: object + key: ResponseMCPCallArgumentsDeltaEvent + path: + - type: object + key: ResponseMCPCallArgumentsDoneEvent + path: + - type: object + key: ResponseMCPCallCompletedEvent + path: + - type: object + key: ResponseMCPCallFailedEvent + path: + - type: object + key: ResponseMCPCallInProgressEvent + path: + - type: object + key: ResponseMCPListToolsCompletedEvent + path: + - type: object + key: ResponseMCPListToolsFailedEvent + path: + - type: object + key: ResponseMCPListToolsInProgressEvent + path: + - type: object + key: ResponseCodeInterpreterCallInProgressEvent + path: + - type: object + key: ResponseCodeInterpreterCallInterpretingEvent + path: + - type: object + key: ResponseCodeInterpreterCallCompletedEvent + path: + - type: object + key: ResponseCodeInterpreterCallCodeDeltaEvent + path: + - type: object + key: ResponseCodeInterpreterCallCodeDoneEvent + path: + - type: object + key: ResponseOutputTextAnnotationAddedEvent + path: + - type: object + key: ResponseQueuedEvent + path: + - type: object + key: ResponseCustomToolCallInputDeltaEvent + path: + - type: object + key: ResponseCustomToolCallInputDoneEvent + path: + - type: object + key: ResponseErrorEvent + path: + - id: webhook-events + title: Webhook Events + description: > + Webhooks are HTTP requests sent by OpenAI to a URL you specify when + certain + + events happen during the course of API usage. + + + [Learn more about webhooks](/docs/guides/webhooks). + navigationGroup: webhooks + sections: + - type: object + key: WebhookResponseCompleted + path: + - type: object + key: WebhookResponseCancelled + path: + - type: object + key: WebhookResponseFailed + path: + - type: object + key: WebhookResponseIncomplete + path: + - type: object + key: WebhookBatchCompleted + path: + - type: object + key: WebhookBatchCancelled + path: + - type: object + key: WebhookBatchExpired + path: + - type: object + key: WebhookBatchFailed + path: + - type: object + key: WebhookFineTuningJobSucceeded + path: + - type: object + key: WebhookFineTuningJobFailed + path: + - type: object + key: WebhookFineTuningJobCancelled + path: + - type: object + key: WebhookEvalRunSucceeded + path: + - type: object + key: WebhookEvalRunFailed + path: + - type: object + key: WebhookEvalRunCanceled + path: + - type: object + key: WebhookRealtimeCallIncoming + path: + - id: images-streaming + title: Image Streaming + description: > + Stream image generation and editing in real time with server-sent + events. + + [Learn more about image streaming](/docs/guides/image-generation). + navigationGroup: endpoints + sections: + - type: object + key: ImageGenPartialImageEvent + path: + - type: object + key: ImageGenCompletedEvent + path: + - type: object + key: ImageEditPartialImageEvent + path: + - type: object + key: ImageEditCompletedEvent + path: + - id: realtime-client-events + title: Client events + description: > + These are events that the OpenAI Realtime WebSocket server will accept + from the client. + navigationGroup: realtime + sections: + - type: object + key: RealtimeClientEventSessionUpdate + path: + - type: object + key: RealtimeClientEventInputAudioBufferAppend + path: + - type: object + key: RealtimeClientEventInputAudioBufferCommit + path: + - type: object + key: RealtimeClientEventInputAudioBufferClear + path: + - type: object + key: RealtimeClientEventConversationItemCreate + path: + - type: object + key: RealtimeClientEventConversationItemRetrieve + path: + - type: object + key: RealtimeClientEventConversationItemTruncate + path: + - type: object + key: RealtimeClientEventConversationItemDelete + path: + - type: object + key: RealtimeClientEventResponseCreate + path: + - type: object + key: RealtimeClientEventResponseCancel + path: + - type: object + key: RealtimeClientEventOutputAudioBufferClear + path: + - id: realtime-server-events + title: Server events + description: > + These are events emitted from the OpenAI Realtime WebSocket server to + the client. + navigationGroup: realtime + sections: + - type: object + key: RealtimeServerEventError + path: + - type: object + key: RealtimeServerEventSessionCreated + path: + - type: object + key: RealtimeServerEventSessionUpdated + path: + - type: object + key: RealtimeServerEventConversationItemAdded + path: + - type: object + key: RealtimeServerEventConversationItemDone + path: + - type: object + key: RealtimeServerEventConversationItemRetrieved + path: + - type: object + key: RealtimeServerEventConversationItemInputAudioTranscriptionCompleted + path: + - type: object + key: RealtimeServerEventConversationItemInputAudioTranscriptionDelta + path: + - type: object + key: RealtimeServerEventConversationItemInputAudioTranscriptionSegment + path: + - type: object + key: RealtimeServerEventConversationItemInputAudioTranscriptionFailed + path: + - type: object + key: RealtimeServerEventConversationItemTruncated + path: + - type: object + key: RealtimeServerEventConversationItemDeleted + path: + - type: object + key: RealtimeServerEventInputAudioBufferCommitted + path: + - type: object + key: RealtimeServerEventInputAudioBufferDtmfEventReceived + path: + - type: object + key: RealtimeServerEventInputAudioBufferCleared + path: + - type: object + key: RealtimeServerEventInputAudioBufferSpeechStarted + path: + - type: object + key: RealtimeServerEventInputAudioBufferSpeechStopped + path: + - type: object + key: RealtimeServerEventInputAudioBufferTimeoutTriggered + path: + - type: object + key: RealtimeServerEventOutputAudioBufferStarted + path: + - type: object + key: RealtimeServerEventOutputAudioBufferStopped + path: + - type: object + key: RealtimeServerEventOutputAudioBufferCleared + path: + - type: object + key: RealtimeServerEventResponseCreated + path: + - type: object + key: RealtimeServerEventResponseDone + path: + - type: object + key: RealtimeServerEventResponseOutputItemAdded + path: + - type: object + key: RealtimeServerEventResponseOutputItemDone + path: + - type: object + key: RealtimeServerEventResponseContentPartAdded + path: + - type: object + key: RealtimeServerEventResponseContentPartDone + path: + - type: object + key: RealtimeServerEventResponseTextDelta + path: + - type: object + key: RealtimeServerEventResponseTextDone + path: + - type: object + key: RealtimeServerEventResponseAudioTranscriptDelta + path: + - type: object + key: RealtimeServerEventResponseAudioTranscriptDone + path: + - type: object + key: RealtimeServerEventResponseAudioDelta + path: + - type: object + key: RealtimeServerEventResponseAudioDone + path: + - type: object + key: RealtimeServerEventResponseFunctionCallArgumentsDelta + path: + - type: object + key: RealtimeServerEventResponseFunctionCallArgumentsDone + path: + - type: object + key: RealtimeServerEventResponseMCPCallArgumentsDelta + path: + - type: object + key: RealtimeServerEventResponseMCPCallArgumentsDone + path: + - type: object + key: RealtimeServerEventResponseMCPCallInProgress + path: + - type: object + key: RealtimeServerEventResponseMCPCallCompleted + path: + - type: object + key: RealtimeServerEventResponseMCPCallFailed + path: + - type: object + key: RealtimeServerEventMCPListToolsInProgress + path: + - type: object + key: RealtimeServerEventMCPListToolsCompleted + path: + - type: object + key: RealtimeServerEventMCPListToolsFailed + path: + - type: object + key: RealtimeServerEventRateLimitsUpdated + path: + - id: chat-streaming + title: Streaming + description: | + Stream Chat Completions in real time. Receive chunks of completions + returned from the model using server-sent events. + [Learn more](/docs/guides/streaming-responses?api-mode=chat). + navigationGroup: chat + sections: + - type: object + key: CreateChatCompletionStreamResponse + path: streaming + - id: assistants-streaming + title: Streaming + beta: true + description: > + Stream the result of executing a Run or resuming a Run after submitting + tool outputs. + + You can stream events from the [Create Thread and + Run](/docs/api-reference/runs/createThreadAndRun), + + [Create Run](/docs/api-reference/runs/createRun), and [Submit Tool + Outputs](/docs/api-reference/runs/submitToolOutputs) + + endpoints by passing `"stream": true`. The response will be a + [Server-Sent + events](https://html.spec.whatwg.org/multipage/server-sent-events.html#server-sent-events) + stream. + + Our Node and Python SDKs provide helpful utilities to make streaming + easy. Reference the + + [Assistants API quickstart](/docs/assistants/overview) to learn more. + navigationGroup: assistants + sections: + - type: object + key: AssistantStreamEvent + path: events + - id: realtime-beta-client-events + title: Realtime Beta client events + description: > + These are events that the OpenAI Realtime WebSocket server will accept + from the client. + navigationGroup: legacy + sections: + - type: object + key: RealtimeBetaClientEventSessionUpdate + path: + - type: object + key: RealtimeBetaClientEventInputAudioBufferAppend + path: + - type: object + key: RealtimeBetaClientEventInputAudioBufferCommit + path: + - type: object + key: RealtimeBetaClientEventInputAudioBufferClear + path: + - type: object + key: RealtimeBetaClientEventConversationItemCreate + path: + - type: object + key: RealtimeBetaClientEventConversationItemRetrieve + path: + - type: object + key: RealtimeBetaClientEventConversationItemTruncate + path: + - type: object + key: RealtimeBetaClientEventConversationItemDelete + path: + - type: object + key: RealtimeBetaClientEventResponseCreate + path: + - type: object + key: RealtimeBetaClientEventResponseCancel + path: + - type: object + key: RealtimeBetaClientEventTranscriptionSessionUpdate + path: + - type: object + key: RealtimeBetaClientEventOutputAudioBufferClear + path: + - id: realtime-beta-server-events + title: Realtime Beta server events + description: > + These are events emitted from the OpenAI Realtime WebSocket server to + the client. + navigationGroup: legacy + sections: + - type: object + key: RealtimeBetaServerEventError + path: + - type: object + key: RealtimeBetaServerEventSessionCreated + path: + - type: object + key: RealtimeBetaServerEventSessionUpdated + path: + - type: object + key: RealtimeBetaServerEventTranscriptionSessionCreated + path: + - type: object + key: RealtimeBetaServerEventTranscriptionSessionUpdated + path: + - type: object + key: RealtimeBetaServerEventConversationItemCreated + path: + - type: object + key: RealtimeBetaServerEventConversationItemRetrieved + path: + - type: object + key: >- + RealtimeBetaServerEventConversationItemInputAudioTranscriptionCompleted + path: + - type: object + key: RealtimeBetaServerEventConversationItemInputAudioTranscriptionDelta + path: + - type: object + key: >- + RealtimeBetaServerEventConversationItemInputAudioTranscriptionSegment + path: + - type: object + key: RealtimeBetaServerEventConversationItemInputAudioTranscriptionFailed + path: + - type: object + key: RealtimeBetaServerEventConversationItemTruncated + path: + - type: object + key: RealtimeBetaServerEventConversationItemDeleted + path: + - type: object + key: RealtimeBetaServerEventInputAudioBufferCommitted + path: + - type: object + key: RealtimeBetaServerEventInputAudioBufferCleared + path: + - type: object + key: RealtimeBetaServerEventInputAudioBufferSpeechStarted + path: + - type: object + key: RealtimeBetaServerEventInputAudioBufferSpeechStopped + path: + - type: object + key: RealtimeServerEventInputAudioBufferTimeoutTriggered + path: + - type: object + key: RealtimeBetaServerEventResponseCreated + path: + - type: object + key: RealtimeBetaServerEventResponseDone + path: + - type: object + key: RealtimeBetaServerEventResponseOutputItemAdded + path: + - type: object + key: RealtimeBetaServerEventResponseOutputItemDone + path: + - type: object + key: RealtimeBetaServerEventResponseContentPartAdded + path: + - type: object + key: RealtimeBetaServerEventResponseContentPartDone + path: + - type: object + key: RealtimeBetaServerEventResponseTextDelta + path: + - type: object + key: RealtimeBetaServerEventResponseTextDone + path: + - type: object + key: RealtimeBetaServerEventResponseAudioTranscriptDelta + path: + - type: object + key: RealtimeBetaServerEventResponseAudioTranscriptDone + path: + - type: object + key: RealtimeBetaServerEventResponseAudioDelta + path: + - type: object + key: RealtimeBetaServerEventResponseAudioDone + path: + - type: object + key: RealtimeBetaServerEventResponseFunctionCallArgumentsDelta + path: + - type: object + key: RealtimeBetaServerEventResponseFunctionCallArgumentsDone + path: + - type: object + key: RealtimeBetaServerEventResponseMCPCallArgumentsDelta + path: + - type: object + key: RealtimeBetaServerEventResponseMCPCallArgumentsDone + path: + - type: object + key: RealtimeBetaServerEventResponseMCPCallInProgress + path: + - type: object + key: RealtimeBetaServerEventResponseMCPCallCompleted + path: + - type: object + key: RealtimeBetaServerEventResponseMCPCallFailed + path: + - type: object + key: RealtimeBetaServerEventMCPListToolsInProgress + path: + - type: object + key: RealtimeBetaServerEventMCPListToolsCompleted + path: + - type: object + key: RealtimeBetaServerEventMCPListToolsFailed + path: + - type: object + key: RealtimeBetaServerEventRateLimitsUpdated + path: From 8efc593922fdddf9784ee4f045ff7d54e3079b60 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Mon, 18 May 2026 16:28:59 +0300 Subject: [PATCH 14/31] Add discriminator mappings missing from OpenAPI spec All discriminator blocks in the spec used propertyName values (e.g. 'type') whose enum strings don't match schema names, making explicit mapping required. Without it, strict OpenAPI tooling cannot resolve the correct schema from a discriminator value. Co-Authored-By: Claude Sonnet 4.6 --- openapi.with-code-samples.yml | 431 ++++++++++++++++++++++++++++++++++ 1 file changed, 431 insertions(+) diff --git a/openapi.with-code-samples.yml b/openapi.with-code-samples.yml index b494033d..46e58f6b 100644 --- a/openapi.with-code-samples.yml +++ b/openapi.with-code-samples.yml @@ -1,3 +1,9 @@ +# NOTE: This file was downloaded from https://github.com/openai/openai-openapi and +# subsequently edited. The following changes were made locally: +# - Added 'mapping' entries to discriminator blocks that were missing them. +# Without explicit mappings, OpenAPI tooling cannot resolve discriminator values +# to schema references when the value strings don't match schema names exactly. + openapi: 3.1.0 info: title: OpenAI API @@ -34724,6 +34730,9 @@ components: - $ref: '#/components/schemas/ChatCompletionMessageCustomToolCall' discriminator: propertyName: type + mapping: + custom: '#/components/schemas/ChatCompletionMessageCustomToolCall' + function: '#/components/schemas/ChatCompletionMessageToolCall' ChatCompletionModalities: anyOf: - type: array @@ -34890,6 +34899,9 @@ components: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartRefusal' discriminator: propertyName: type + mapping: + refusal: '#/components/schemas/ChatCompletionRequestMessageContentPartRefusal' + text: '#/components/schemas/ChatCompletionRequestMessageContentPartText' ChatCompletionRequestDeveloperMessage: type: object title: Developer message @@ -34964,6 +34976,13 @@ components: - $ref: '#/components/schemas/ChatCompletionRequestFunctionMessage' discriminator: propertyName: role + mapping: + assistant: '#/components/schemas/ChatCompletionRequestAssistantMessage' + developer: '#/components/schemas/ChatCompletionRequestDeveloperMessage' + function: '#/components/schemas/ChatCompletionRequestFunctionMessage' + system: '#/components/schemas/ChatCompletionRequestSystemMessage' + tool: '#/components/schemas/ChatCompletionRequestToolMessage' + user: '#/components/schemas/ChatCompletionRequestUserMessage' ChatCompletionRequestMessageContentPartAudio: type: object title: Audio content part @@ -35586,6 +35605,9 @@ components: - $ref: '#/components/schemas/StaticChunkingStrategyRequestParam' discriminator: propertyName: type + mapping: + auto: '#/components/schemas/AutoChunkingStrategyRequestParam' + static: '#/components/schemas/StaticChunkingStrategyRequestParam' CodeInterpreterFileOutput: type: object title: Code interpreter file output @@ -35717,6 +35739,9 @@ components: - $ref: '#/components/schemas/CodeInterpreterOutputImage' discriminator: propertyName: type + mapping: + image: '#/components/schemas/CodeInterpreterOutputImage' + logs: '#/components/schemas/CodeInterpreterOutputLogs' discriminator: propertyName: type description: > @@ -35898,6 +35923,8 @@ components: - $recursiveRef: '#' discriminator: propertyName: type + mapping: + eq: '#/components/schemas/ComparisonFilter' required: - type - filters @@ -35916,6 +35943,16 @@ components: - $ref: '#/components/schemas/WaitParam' discriminator: propertyName: type + mapping: + click: '#/components/schemas/ClickParam' + double_click: '#/components/schemas/DoubleClickAction' + drag: '#/components/schemas/DragParam' + keypress: '#/components/schemas/KeyPressAction' + move: '#/components/schemas/MoveParam' + screenshot: '#/components/schemas/ScreenshotParam' + scroll: '#/components/schemas/ScrollParam' + type: '#/components/schemas/TypeParam' + wait: '#/components/schemas/WaitParam' ComputerActionList: title: Computer Action List type: array @@ -36303,6 +36340,32 @@ components: - $ref: '#/components/schemas/CustomToolCallOutput' discriminator: propertyName: type + mapping: + apply_patch_call: '#/components/schemas/ApplyPatchToolCall' + apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutput' + code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' + compaction: '#/components/schemas/CompactionBody' + computer_call: '#/components/schemas/ComputerToolCall' + computer_call_output: '#/components/schemas/ComputerToolCallOutputResource' + custom_tool_call: '#/components/schemas/CustomToolCall' + custom_tool_call_output: '#/components/schemas/CustomToolCallOutput' + file_search_call: '#/components/schemas/FileSearchToolCall' + function_call: '#/components/schemas/FunctionToolCallResource' + function_call_output: '#/components/schemas/FunctionToolCallOutputResource' + image_generation_call: '#/components/schemas/ImageGenToolCall' + local_shell_call: '#/components/schemas/LocalShellToolCall' + local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' + mcp_approval_request: '#/components/schemas/MCPApprovalRequest' + mcp_approval_response: '#/components/schemas/MCPApprovalResponseResource' + mcp_call: '#/components/schemas/MCPToolCall' + mcp_list_tools: '#/components/schemas/MCPListTools' + message: '#/components/schemas/Message' + reasoning: '#/components/schemas/ReasoningItem' + shell_call: '#/components/schemas/FunctionShellCall' + shell_call_output: '#/components/schemas/FunctionShellCallOutput' + tool_search_call: '#/components/schemas/ToolSearchCall' + tool_search_output: '#/components/schemas/ToolSearchOutput' + web_search_call: '#/components/schemas/WebSearchToolCall' ConversationItemList: type: object title: The conversation item list @@ -36762,6 +36825,10 @@ components: - $ref: '#/components/schemas/ResponseFormatJsonObject' discriminator: propertyName: type + mapping: + json_object: '#/components/schemas/ResponseFormatJsonObject' + json_schema: '#/components/schemas/ResponseFormatJsonSchema' + text: '#/components/schemas/ResponseFormatText' audio: type: object nullable: true @@ -37717,6 +37784,9 @@ components: - $ref: '#/components/schemas/InlineSkillParam' discriminator: propertyName: type + mapping: + inline: '#/components/schemas/InlineSkillParam' + skill_reference: '#/components/schemas/SkillReferenceParam' memory_limit: type: string enum: @@ -37732,6 +37802,9 @@ components: - $ref: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' discriminator: propertyName: type + mapping: + allowlist: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' + disabled: '#/components/schemas/ContainerNetworkPolicyDisabledParam' required: - name CreateContainerFileBody: @@ -40146,6 +40219,9 @@ components: - $ref: '#/components/schemas/SpeechAudioDoneEvent' discriminator: propertyName: type + mapping: + speech.audio.delta: '#/components/schemas/SpeechAudioDeltaEvent' + speech.audio.done: '#/components/schemas/SpeechAudioDoneEvent' CreateThreadAndRunRequest: type: object additionalProperties: false @@ -40667,6 +40743,9 @@ components: title: Duration Usage discriminator: propertyName: type + mapping: + duration: '#/components/schemas/TranscriptTextUsageDuration' + tokens: '#/components/schemas/TranscriptTextUsageTokens' required: - task - duration @@ -40768,6 +40847,10 @@ components: - $ref: '#/components/schemas/TranscriptTextDoneEvent' discriminator: propertyName: type + mapping: + transcript.text.delta: '#/components/schemas/TranscriptTextDeltaEvent' + transcript.text.done: '#/components/schemas/TranscriptTextDoneEvent' + transcript.text.segment: '#/components/schemas/TranscriptTextSegmentEvent' CreateTranscriptionResponseVerboseJson: type: object description: >- @@ -44158,6 +44241,10 @@ components: - $ref: '#/components/schemas/InputFileContent' discriminator: propertyName: type + mapping: + input_file: '#/components/schemas/InputFileContent' + input_image: '#/components/schemas/InputImageContent' + input_text: '#/components/schemas/InputTextContent' FunctionObject: type: object properties: @@ -45226,6 +45313,9 @@ components: - $ref: '#/components/schemas/ImageEditCompletedEvent' discriminator: propertyName: type + mapping: + image_edit.completed: '#/components/schemas/ImageEditCompletedEvent' + image_edit.partial_image: '#/components/schemas/ImageEditPartialImageEvent' ImageGenCompletedEvent: type: object description: > @@ -45403,6 +45493,9 @@ components: - $ref: '#/components/schemas/ImageGenCompletedEvent' discriminator: propertyName: type + mapping: + image_generation.completed: '#/components/schemas/ImageGenCompletedEvent' + image_generation.partial_image: '#/components/schemas/ImageGenPartialImageEvent' ImageGenTool: type: object title: Image generation tool @@ -45737,6 +45830,10 @@ components: - $ref: '#/components/schemas/InputFileContent' discriminator: propertyName: type + mapping: + input_file: '#/components/schemas/InputFileContent' + input_image: '#/components/schemas/InputImageContent' + input_text: '#/components/schemas/InputTextContent' InputItem: oneOf: - $ref: '#/components/schemas/EasyInputMessage' @@ -45750,6 +45847,8 @@ components: - $ref: '#/components/schemas/ItemReferenceParam' discriminator: propertyName: type + mapping: + message: '#/components/schemas/EasyInputMessage' InputMessage: type: object title: Input message @@ -46050,6 +46149,32 @@ components: - $ref: '#/components/schemas/CustomToolCall' discriminator: propertyName: type + mapping: + apply_patch_call: '#/components/schemas/ApplyPatchToolCallItemParam' + apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutputItemParam' + code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' + compaction: '#/components/schemas/CompactionSummaryItemParam' + computer_call: '#/components/schemas/ComputerToolCall' + computer_call_output: '#/components/schemas/ComputerCallOutputItemParam' + custom_tool_call: '#/components/schemas/CustomToolCall' + custom_tool_call_output: '#/components/schemas/CustomToolCallOutput' + file_search_call: '#/components/schemas/FileSearchToolCall' + function_call: '#/components/schemas/FunctionToolCall' + function_call_output: '#/components/schemas/FunctionCallOutputItemParam' + image_generation_call: '#/components/schemas/ImageGenToolCall' + local_shell_call: '#/components/schemas/LocalShellToolCall' + local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' + mcp_approval_request: '#/components/schemas/MCPApprovalRequest' + mcp_approval_response: '#/components/schemas/MCPApprovalResponse' + mcp_call: '#/components/schemas/MCPToolCall' + mcp_list_tools: '#/components/schemas/MCPListTools' + message: '#/components/schemas/OutputMessage' + reasoning: '#/components/schemas/ReasoningItem' + shell_call: '#/components/schemas/FunctionShellCallItemParam' + shell_call_output: '#/components/schemas/FunctionShellCallOutputItemParam' + tool_search_call: '#/components/schemas/ToolSearchCallItemParam' + tool_search_output: '#/components/schemas/ToolSearchOutputItemParam' + web_search_call: '#/components/schemas/WebSearchToolCall' ItemResource: description: | Content item used to generate a response. @@ -46082,6 +46207,32 @@ components: - $ref: '#/components/schemas/CustomToolCallOutputResource' discriminator: propertyName: type + mapping: + apply_patch_call: '#/components/schemas/ApplyPatchToolCall' + apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutput' + code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' + compaction: '#/components/schemas/CompactionBody' + computer_call: '#/components/schemas/ComputerToolCall' + computer_call_output: '#/components/schemas/ComputerToolCallOutputResource' + custom_tool_call: '#/components/schemas/CustomToolCallResource' + custom_tool_call_output: '#/components/schemas/CustomToolCallOutputResource' + file_search_call: '#/components/schemas/FileSearchToolCall' + function_call: '#/components/schemas/FunctionToolCallResource' + function_call_output: '#/components/schemas/FunctionToolCallOutputResource' + image_generation_call: '#/components/schemas/ImageGenToolCall' + local_shell_call: '#/components/schemas/LocalShellToolCall' + local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' + mcp_approval_request: '#/components/schemas/MCPApprovalRequest' + mcp_approval_response: '#/components/schemas/MCPApprovalResponseResource' + mcp_call: '#/components/schemas/MCPToolCall' + mcp_list_tools: '#/components/schemas/MCPListTools' + message: '#/components/schemas/OutputMessage' + reasoning: '#/components/schemas/ReasoningItem' + shell_call: '#/components/schemas/FunctionShellCall' + shell_call_output: '#/components/schemas/FunctionShellCallOutput' + tool_search_call: '#/components/schemas/ToolSearchCall' + tool_search_output: '#/components/schemas/ToolSearchOutput' + web_search_call: '#/components/schemas/WebSearchToolCall' ListAssistantsResponse: type: object properties: @@ -48311,6 +48462,10 @@ components: - $ref: '#/components/schemas/ReasoningTextContent' discriminator: propertyName: type + mapping: + output_text: '#/components/schemas/OutputTextContent' + reasoning_text: '#/components/schemas/ReasoningTextContent' + refusal: '#/components/schemas/RefusalContent' OutputItem: oneOf: - $ref: '#/components/schemas/OutputMessage' @@ -48340,6 +48495,32 @@ components: - $ref: '#/components/schemas/CustomToolCallOutputResource' discriminator: propertyName: type + mapping: + apply_patch_call: '#/components/schemas/ApplyPatchToolCall' + apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutput' + code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' + compaction: '#/components/schemas/CompactionBody' + computer_call: '#/components/schemas/ComputerToolCall' + computer_call_output: '#/components/schemas/ComputerToolCallOutputResource' + custom_tool_call: '#/components/schemas/CustomToolCall' + custom_tool_call_output: '#/components/schemas/CustomToolCallOutputResource' + file_search_call: '#/components/schemas/FileSearchToolCall' + function_call: '#/components/schemas/FunctionToolCall' + function_call_output: '#/components/schemas/FunctionToolCallOutputResource' + image_generation_call: '#/components/schemas/ImageGenToolCall' + local_shell_call: '#/components/schemas/LocalShellToolCall' + local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' + mcp_approval_request: '#/components/schemas/MCPApprovalRequest' + mcp_approval_response: '#/components/schemas/MCPApprovalResponseResource' + mcp_call: '#/components/schemas/MCPToolCall' + mcp_list_tools: '#/components/schemas/MCPListTools' + message: '#/components/schemas/OutputMessage' + reasoning: '#/components/schemas/ReasoningItem' + shell_call: '#/components/schemas/FunctionShellCall' + shell_call_output: '#/components/schemas/FunctionShellCallOutput' + tool_search_call: '#/components/schemas/ToolSearchCall' + tool_search_output: '#/components/schemas/ToolSearchOutput' + web_search_call: '#/components/schemas/WebSearchToolCall' OutputMessage: type: object title: Output message @@ -48397,6 +48578,9 @@ components: - $ref: '#/components/schemas/RefusalContent' discriminator: propertyName: type + mapping: + output_text: '#/components/schemas/OutputTextContent' + refusal: '#/components/schemas/RefusalContent' ParallelToolCalls: description: >- Whether to enable [parallel function @@ -52541,6 +52725,18 @@ components: RealtimeClientEvent: discriminator: propertyName: type + mapping: + conversation.item.create: '#/components/schemas/RealtimeClientEventConversationItemCreate' + conversation.item.delete: '#/components/schemas/RealtimeClientEventConversationItemDelete' + conversation.item.retrieve: '#/components/schemas/RealtimeClientEventConversationItemRetrieve' + conversation.item.truncate: '#/components/schemas/RealtimeClientEventConversationItemTruncate' + input_audio_buffer.append: '#/components/schemas/RealtimeClientEventInputAudioBufferAppend' + input_audio_buffer.clear: '#/components/schemas/RealtimeClientEventInputAudioBufferClear' + input_audio_buffer.commit: '#/components/schemas/RealtimeClientEventInputAudioBufferCommit' + output_audio_buffer.clear: '#/components/schemas/RealtimeClientEventOutputAudioBufferClear' + response.cancel: '#/components/schemas/RealtimeClientEventResponseCancel' + response.create: '#/components/schemas/RealtimeClientEventResponseCreate' + session.update: '#/components/schemas/RealtimeClientEventSessionUpdate' description: | A realtime client event. anyOf: @@ -53245,6 +53441,14 @@ components: - $ref: '#/components/schemas/RealtimeMCPApprovalRequest' discriminator: propertyName: type + mapping: + function_call: '#/components/schemas/RealtimeConversationItemFunctionCall' + function_call_output: '#/components/schemas/RealtimeConversationItemFunctionCallOutput' + mcp_approval_request: '#/components/schemas/RealtimeMCPApprovalRequest' + mcp_approval_response: '#/components/schemas/RealtimeMCPApprovalResponse' + mcp_call: '#/components/schemas/RealtimeMCPToolCall' + mcp_list_tools: '#/components/schemas/RealtimeMCPListTools' + message: '#/components/schemas/RealtimeConversationItemMessageAssistant' RealtimeConversationItemFunctionCall: type: object title: Realtime function call item @@ -53770,6 +53974,9 @@ components: #/components/schemas/RealtimeTranscriptionSessionCreateResponseGA discriminator: propertyName: type + mapping: + realtime: '#/components/schemas/RealtimeSessionCreateResponseGA' + transcription: '#/components/schemas/RealtimeTranscriptionSessionCreateResponseGA' required: - value - expires_at @@ -54408,6 +54615,53 @@ components: RealtimeServerEvent: discriminator: propertyName: type + mapping: + conversation.created: '#/components/schemas/RealtimeServerEventConversationCreated' + conversation.item.added: '#/components/schemas/RealtimeServerEventConversationItemAdded' + conversation.item.created: '#/components/schemas/RealtimeServerEventConversationItemCreated' + conversation.item.deleted: '#/components/schemas/RealtimeServerEventConversationItemDeleted' + conversation.item.done: '#/components/schemas/RealtimeServerEventConversationItemDone' + conversation.item.input_audio_transcription.completed: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionCompleted' + conversation.item.input_audio_transcription.delta: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionDelta' + conversation.item.input_audio_transcription.failed: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionFailed' + conversation.item.input_audio_transcription.segment: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionSegment' + conversation.item.retrieved: '#/components/schemas/RealtimeServerEventConversationItemRetrieved' + conversation.item.truncated: '#/components/schemas/RealtimeServerEventConversationItemTruncated' + error: '#/components/schemas/RealtimeServerEventError' + input_audio_buffer.cleared: '#/components/schemas/RealtimeServerEventInputAudioBufferCleared' + input_audio_buffer.committed: '#/components/schemas/RealtimeServerEventInputAudioBufferCommitted' + input_audio_buffer.dtmf_event_received: '#/components/schemas/RealtimeServerEventInputAudioBufferDtmfEventReceived' + input_audio_buffer.speech_started: '#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStarted' + input_audio_buffer.speech_stopped: '#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStopped' + input_audio_buffer.timeout_triggered: '#/components/schemas/RealtimeServerEventInputAudioBufferTimeoutTriggered' + mcp_list_tools.completed: '#/components/schemas/RealtimeServerEventMCPListToolsCompleted' + mcp_list_tools.failed: '#/components/schemas/RealtimeServerEventMCPListToolsFailed' + mcp_list_tools.in_progress: '#/components/schemas/RealtimeServerEventMCPListToolsInProgress' + output_audio_buffer.cleared: '#/components/schemas/RealtimeServerEventOutputAudioBufferCleared' + output_audio_buffer.started: '#/components/schemas/RealtimeServerEventOutputAudioBufferStarted' + output_audio_buffer.stopped: '#/components/schemas/RealtimeServerEventOutputAudioBufferStopped' + rate_limits.updated: '#/components/schemas/RealtimeServerEventRateLimitsUpdated' + response.content_part.added: '#/components/schemas/RealtimeServerEventResponseContentPartAdded' + response.content_part.done: '#/components/schemas/RealtimeServerEventResponseContentPartDone' + response.created: '#/components/schemas/RealtimeServerEventResponseCreated' + response.done: '#/components/schemas/RealtimeServerEventResponseDone' + response.function_call_arguments.delta: '#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDelta' + response.function_call_arguments.done: '#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDone' + response.mcp_call.completed: '#/components/schemas/RealtimeServerEventResponseMCPCallCompleted' + response.mcp_call.failed: '#/components/schemas/RealtimeServerEventResponseMCPCallFailed' + response.mcp_call.in_progress: '#/components/schemas/RealtimeServerEventResponseMCPCallInProgress' + response.mcp_call_arguments.delta: '#/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDelta' + response.mcp_call_arguments.done: '#/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDone' + response.output_audio.delta: '#/components/schemas/RealtimeServerEventResponseAudioDelta' + response.output_audio.done: '#/components/schemas/RealtimeServerEventResponseAudioDone' + response.output_audio_transcript.delta: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDelta' + response.output_audio_transcript.done: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDone' + response.output_item.added: '#/components/schemas/RealtimeServerEventResponseOutputItemAdded' + response.output_item.done: '#/components/schemas/RealtimeServerEventResponseOutputItemDone' + response.output_text.delta: '#/components/schemas/RealtimeServerEventResponseTextDelta' + response.output_text.done: '#/components/schemas/RealtimeServerEventResponseTextDone' + session.created: '#/components/schemas/RealtimeServerEventSessionCreated' + session.updated: '#/components/schemas/RealtimeServerEventSessionUpdated' description: | A realtime server event. anyOf: @@ -62019,6 +62273,60 @@ components: - $ref: '#/components/schemas/ResponseCustomToolCallInputDoneEvent' discriminator: propertyName: type + mapping: + error: '#/components/schemas/ResponseErrorEvent' + response.audio.delta: '#/components/schemas/ResponseAudioDeltaEvent' + response.audio.done: '#/components/schemas/ResponseAudioDoneEvent' + response.audio.transcript.delta: '#/components/schemas/ResponseAudioTranscriptDeltaEvent' + response.audio.transcript.done: '#/components/schemas/ResponseAudioTranscriptDoneEvent' + response.code_interpreter_call.completed: '#/components/schemas/ResponseCodeInterpreterCallCompletedEvent' + response.code_interpreter_call.in_progress: '#/components/schemas/ResponseCodeInterpreterCallInProgressEvent' + response.code_interpreter_call.interpreting: '#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent' + response.code_interpreter_call_code.delta: '#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent' + response.code_interpreter_call_code.done: '#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent' + response.completed: '#/components/schemas/ResponseCompletedEvent' + response.content_part.added: '#/components/schemas/ResponseContentPartAddedEvent' + response.content_part.done: '#/components/schemas/ResponseContentPartDoneEvent' + response.created: '#/components/schemas/ResponseCreatedEvent' + response.custom_tool_call_input.delta: '#/components/schemas/ResponseCustomToolCallInputDeltaEvent' + response.custom_tool_call_input.done: '#/components/schemas/ResponseCustomToolCallInputDoneEvent' + response.failed: '#/components/schemas/ResponseFailedEvent' + response.file_search_call.completed: '#/components/schemas/ResponseFileSearchCallCompletedEvent' + response.file_search_call.in_progress: '#/components/schemas/ResponseFileSearchCallInProgressEvent' + response.file_search_call.searching: '#/components/schemas/ResponseFileSearchCallSearchingEvent' + response.function_call_arguments.delta: '#/components/schemas/ResponseFunctionCallArgumentsDeltaEvent' + response.function_call_arguments.done: '#/components/schemas/ResponseFunctionCallArgumentsDoneEvent' + response.image_generation_call.completed: '#/components/schemas/ResponseImageGenCallCompletedEvent' + response.image_generation_call.generating: '#/components/schemas/ResponseImageGenCallGeneratingEvent' + response.image_generation_call.in_progress: '#/components/schemas/ResponseImageGenCallInProgressEvent' + response.image_generation_call.partial_image: '#/components/schemas/ResponseImageGenCallPartialImageEvent' + response.in_progress: '#/components/schemas/ResponseInProgressEvent' + response.incomplete: '#/components/schemas/ResponseIncompleteEvent' + response.mcp_call.completed: '#/components/schemas/ResponseMCPCallCompletedEvent' + response.mcp_call.failed: '#/components/schemas/ResponseMCPCallFailedEvent' + response.mcp_call.in_progress: '#/components/schemas/ResponseMCPCallInProgressEvent' + response.mcp_call_arguments.delta: '#/components/schemas/ResponseMCPCallArgumentsDeltaEvent' + response.mcp_call_arguments.done: '#/components/schemas/ResponseMCPCallArgumentsDoneEvent' + response.mcp_list_tools.completed: '#/components/schemas/ResponseMCPListToolsCompletedEvent' + response.mcp_list_tools.failed: '#/components/schemas/ResponseMCPListToolsFailedEvent' + response.mcp_list_tools.in_progress: '#/components/schemas/ResponseMCPListToolsInProgressEvent' + response.output_item.added: '#/components/schemas/ResponseOutputItemAddedEvent' + response.output_item.done: '#/components/schemas/ResponseOutputItemDoneEvent' + response.output_text.annotation.added: '#/components/schemas/ResponseOutputTextAnnotationAddedEvent' + response.output_text.delta: '#/components/schemas/ResponseTextDeltaEvent' + response.output_text.done: '#/components/schemas/ResponseTextDoneEvent' + response.queued: '#/components/schemas/ResponseQueuedEvent' + response.reasoning_summary_part.added: '#/components/schemas/ResponseReasoningSummaryPartAddedEvent' + response.reasoning_summary_part.done: '#/components/schemas/ResponseReasoningSummaryPartDoneEvent' + response.reasoning_summary_text.delta: '#/components/schemas/ResponseReasoningSummaryTextDeltaEvent' + response.reasoning_summary_text.done: '#/components/schemas/ResponseReasoningSummaryTextDoneEvent' + response.reasoning_text.delta: '#/components/schemas/ResponseReasoningTextDeltaEvent' + response.reasoning_text.done: '#/components/schemas/ResponseReasoningTextDoneEvent' + response.refusal.delta: '#/components/schemas/ResponseRefusalDeltaEvent' + response.refusal.done: '#/components/schemas/ResponseRefusalDoneEvent' + response.web_search_call.completed: '#/components/schemas/ResponseWebSearchCallCompletedEvent' + response.web_search_call.in_progress: '#/components/schemas/ResponseWebSearchCallInProgressEvent' + response.web_search_call.searching: '#/components/schemas/ResponseWebSearchCallSearchingEvent' ResponseStreamOptions: anyOf: - description: > @@ -62333,6 +62641,8 @@ components: ResponsesClientEvent: discriminator: propertyName: type + mapping: + response.create: '#/components/schemas/ResponsesClientEventResponseCreate' description: | Client events accepted by the Responses WebSocket server. anyOf: @@ -64327,6 +64637,22 @@ components: A tool that can be used to generate a response. discriminator: propertyName: type + mapping: + apply_patch: '#/components/schemas/ApplyPatchToolParam' + code_interpreter: '#/components/schemas/CodeInterpreterTool' + computer: '#/components/schemas/ComputerTool' + computer_use_preview: '#/components/schemas/ComputerUsePreviewTool' + custom: '#/components/schemas/CustomToolParam' + file_search: '#/components/schemas/FileSearchTool' + function: '#/components/schemas/FunctionTool' + image_generation: '#/components/schemas/ImageGenTool' + local_shell: '#/components/schemas/LocalShellToolParam' + mcp: '#/components/schemas/MCPTool' + namespace: '#/components/schemas/NamespaceToolParam' + shell: '#/components/schemas/FunctionShellToolParam' + tool_search: '#/components/schemas/ToolSearchToolParam' + web_search: '#/components/schemas/WebSearchTool' + web_search_preview: '#/components/schemas/WebSearchPreviewTool' oneOf: - $ref: '#/components/schemas/FunctionTool' - $ref: '#/components/schemas/FileSearchTool' @@ -66913,6 +67239,10 @@ components: - $ref: '#/components/schemas/WebSearchActionFind' discriminator: propertyName: type + mapping: + find_in_page: '#/components/schemas/WebSearchActionFind' + open_page: '#/components/schemas/WebSearchActionOpenPage' + search: '#/components/schemas/WebSearchActionSearch' required: - id - type @@ -68107,6 +68437,11 @@ components: description: An annotation that applies to a span of output text. discriminator: propertyName: type + mapping: + container_file_citation: '#/components/schemas/ContainerFileCitationBody' + file_citation: '#/components/schemas/FileCitationBody' + file_path: '#/components/schemas/FilePath' + url_citation: '#/components/schemas/UrlCitationBody' TopLogProb: properties: token: @@ -68402,6 +68737,16 @@ components: description: A content part that makes up an input or output item. discriminator: propertyName: type + mapping: + computer_screenshot: '#/components/schemas/ComputerScreenshotContent' + input_file: '#/components/schemas/InputFileContent' + input_image: '#/components/schemas/InputImageContent' + input_text: '#/components/schemas/InputTextContent' + output_text: '#/components/schemas/OutputTextContent' + reasoning_text: '#/components/schemas/ReasoningTextContent' + refusal: '#/components/schemas/RefusalContent' + summary_text: '#/components/schemas/SummaryTextContent' + text: '#/components/schemas/TextContent' type: array description: The content of the message phase: @@ -68987,6 +69332,9 @@ components: description: Network access policy for the container. discriminator: propertyName: type + mapping: + allowlist: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' + disabled: '#/components/schemas/ContainerNetworkPolicyDisabledParam' type: object required: - type @@ -69055,6 +69403,9 @@ components: description: Network access policy for the container. discriminator: propertyName: type + mapping: + allowlist: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' + disabled: '#/components/schemas/ContainerNetworkPolicyDisabledParam' skills: items: oneOf: @@ -69062,6 +69413,9 @@ components: - $ref: '#/components/schemas/InlineSkillParam' discriminator: propertyName: type + mapping: + inline: '#/components/schemas/InlineSkillParam' + skill_reference: '#/components/schemas/SkillReferenceParam' type: array maxItems: 200 description: An optional list of skills referenced by id or inline data. @@ -69136,6 +69490,10 @@ components: - $ref: '#/components/schemas/ContainerReferenceParam' discriminator: propertyName: type + mapping: + container_auto: '#/components/schemas/ContainerAutoParam' + container_reference: '#/components/schemas/ContainerReferenceParam' + local: '#/components/schemas/LocalEnvironmentParam' - type: 'null' type: object required: @@ -69207,6 +69565,9 @@ components: description: The input format for the custom tool. Default is unconstrained text. discriminator: propertyName: type + mapping: + grammar: '#/components/schemas/CustomGrammarFormatParam' + text: '#/components/schemas/CustomTextFormatParam' defer_loading: type: boolean description: Whether this tool should be deferred and discovered via tool search. @@ -69281,6 +69642,9 @@ components: description: A function or custom tool that belongs to a namespace. discriminator: propertyName: type + mapping: + custom: '#/components/schemas/CustomToolParam' + function: '#/components/schemas/FunctionToolParam' type: array minItems: 1 description: The function/custom tools available inside this namespace. @@ -69660,6 +70024,9 @@ components: - $ref: '#/components/schemas/ContainerReferenceResource' discriminator: propertyName: type + mapping: + container_reference: '#/components/schemas/ContainerReferenceResource' + local: '#/components/schemas/LocalEnvironmentResource' - type: 'null' created_by: type: string @@ -69732,6 +70099,9 @@ components: outcome for a shell call output chunk. discriminator: propertyName: type + mapping: + exit: '#/components/schemas/FunctionShellCallOutputExitOutcome' + timeout: '#/components/schemas/FunctionShellCallOutputTimeoutOutcome' created_by: type: string description: The identifier of the actor that created the item. @@ -69890,6 +70260,10 @@ components: applied via apply_patch. discriminator: propertyName: type + mapping: + create_file: '#/components/schemas/ApplyPatchCreateFileOperation' + delete_file: '#/components/schemas/ApplyPatchDeleteFileOperation' + update_file: '#/components/schemas/ApplyPatchUpdateFileOperation' created_by: type: string description: The ID of the entity that created this tool call. @@ -70156,6 +70530,10 @@ components: description: A piece of message content, such as text, an image, or a file. discriminator: propertyName: type + mapping: + input_file: '#/components/schemas/InputFileContentParam' + input_image: '#/components/schemas/InputImageContentParamAutoParam' + input_text: '#/components/schemas/InputTextContentParam' type: array description: >- An array of content outputs (text, image, file) for the function @@ -70354,6 +70732,9 @@ components: description: The environment to execute the shell commands in. discriminator: propertyName: type + mapping: + container_reference: '#/components/schemas/ContainerReferenceParam' + local: '#/components/schemas/LocalEnvironmentParam' - type: 'null' type: object required: @@ -70402,6 +70783,9 @@ components: description: The exit or timeout outcome associated with this shell call. discriminator: propertyName: type + mapping: + exit: '#/components/schemas/FunctionShellCallOutputExitOutcomeParam' + timeout: '#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam' FunctionShellCallOutputContentParam: properties: stdout: @@ -70555,6 +70939,10 @@ components: to the apply_patch tool. discriminator: propertyName: type + mapping: + create_file: '#/components/schemas/ApplyPatchCreateFileOperationParam' + delete_file: '#/components/schemas/ApplyPatchDeleteFileOperationParam' + update_file: '#/components/schemas/ApplyPatchUpdateFileOperationParam' ApplyPatchToolCallItemParam: properties: type: @@ -71504,6 +71892,32 @@ components: other response element. discriminator: propertyName: type + mapping: + apply_patch_call: '#/components/schemas/ApplyPatchToolCall' + apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutput' + code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' + compaction: '#/components/schemas/CompactionBody' + computer_call: '#/components/schemas/ComputerToolCall' + computer_call_output: '#/components/schemas/ComputerToolCallOutputResource' + custom_tool_call: '#/components/schemas/CustomToolCall' + custom_tool_call_output: '#/components/schemas/CustomToolCallOutput' + file_search_call: '#/components/schemas/FileSearchToolCall' + function_call: '#/components/schemas/FunctionToolCall' + function_call_output: '#/components/schemas/FunctionToolCallOutput' + image_generation_call: '#/components/schemas/ImageGenToolCall' + local_shell_call: '#/components/schemas/LocalShellToolCall' + local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' + mcp_approval_request: '#/components/schemas/MCPApprovalRequest' + mcp_approval_response: '#/components/schemas/MCPApprovalResponseResource' + mcp_call: '#/components/schemas/MCPToolCall' + mcp_list_tools: '#/components/schemas/MCPListTools' + message: '#/components/schemas/Message' + reasoning: '#/components/schemas/ReasoningItem' + shell_call: '#/components/schemas/FunctionShellCall' + shell_call_output: '#/components/schemas/FunctionShellCallOutput' + tool_search_call: '#/components/schemas/ToolSearchCall' + tool_search_output: '#/components/schemas/ToolSearchOutput' + web_search_call: '#/components/schemas/WebSearchToolCall' CompactResource: properties: id: @@ -72305,6 +72719,9 @@ components: description: Content blocks that comprise a user message. discriminator: propertyName: type + mapping: + input_text: '#/components/schemas/UserMessageInputText' + quoted_text: '#/components/schemas/UserMessageQuotedText' type: array description: Ordered content elements supplied by the user. attachments: @@ -72425,6 +72842,9 @@ components: description: Annotation object describing a cited source. discriminator: propertyName: type + mapping: + file: '#/components/schemas/FileAnnotation' + url: '#/components/schemas/UrlAnnotation' type: array description: Ordered list of annotations attached to the response text. type: object @@ -72711,6 +73131,13 @@ components: title: The thread item discriminator: propertyName: type + mapping: + chatkit.assistant_message: '#/components/schemas/AssistantMessageItem' + chatkit.client_tool_call: '#/components/schemas/ClientToolCallItem' + chatkit.task: '#/components/schemas/TaskItem' + chatkit.task_group: '#/components/schemas/TaskGroupItem' + chatkit.user_message: '#/components/schemas/UserMessageItem' + chatkit.widget: '#/components/schemas/WidgetMessageItem' ThreadItemListResource: properties: object: @@ -72837,6 +73264,10 @@ components: created threads. discriminator: propertyName: type + mapping: + active: '#/components/schemas/ActiveStatus' + closed: '#/components/schemas/ClosedStatus' + locked: '#/components/schemas/LockedStatus' user: type: string description: Free-form string that identifies your end user who owns the thread. From da7f88d00f64575e8a25ec73bc0b0ecd8e5e7a4e Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 22 May 2026 22:46:12 +0300 Subject: [PATCH 15/31] Revert "Add discriminator mappings missing from OpenAPI spec" This reverts commit 8efc593922fdddf9784ee4f045ff7d54e3079b60. --- openapi.with-code-samples.yml | 431 ---------------------------------- 1 file changed, 431 deletions(-) diff --git a/openapi.with-code-samples.yml b/openapi.with-code-samples.yml index 46e58f6b..b494033d 100644 --- a/openapi.with-code-samples.yml +++ b/openapi.with-code-samples.yml @@ -1,9 +1,3 @@ -# NOTE: This file was downloaded from https://github.com/openai/openai-openapi and -# subsequently edited. The following changes were made locally: -# - Added 'mapping' entries to discriminator blocks that were missing them. -# Without explicit mappings, OpenAPI tooling cannot resolve discriminator values -# to schema references when the value strings don't match schema names exactly. - openapi: 3.1.0 info: title: OpenAI API @@ -34730,9 +34724,6 @@ components: - $ref: '#/components/schemas/ChatCompletionMessageCustomToolCall' discriminator: propertyName: type - mapping: - custom: '#/components/schemas/ChatCompletionMessageCustomToolCall' - function: '#/components/schemas/ChatCompletionMessageToolCall' ChatCompletionModalities: anyOf: - type: array @@ -34899,9 +34890,6 @@ components: - $ref: '#/components/schemas/ChatCompletionRequestMessageContentPartRefusal' discriminator: propertyName: type - mapping: - refusal: '#/components/schemas/ChatCompletionRequestMessageContentPartRefusal' - text: '#/components/schemas/ChatCompletionRequestMessageContentPartText' ChatCompletionRequestDeveloperMessage: type: object title: Developer message @@ -34976,13 +34964,6 @@ components: - $ref: '#/components/schemas/ChatCompletionRequestFunctionMessage' discriminator: propertyName: role - mapping: - assistant: '#/components/schemas/ChatCompletionRequestAssistantMessage' - developer: '#/components/schemas/ChatCompletionRequestDeveloperMessage' - function: '#/components/schemas/ChatCompletionRequestFunctionMessage' - system: '#/components/schemas/ChatCompletionRequestSystemMessage' - tool: '#/components/schemas/ChatCompletionRequestToolMessage' - user: '#/components/schemas/ChatCompletionRequestUserMessage' ChatCompletionRequestMessageContentPartAudio: type: object title: Audio content part @@ -35605,9 +35586,6 @@ components: - $ref: '#/components/schemas/StaticChunkingStrategyRequestParam' discriminator: propertyName: type - mapping: - auto: '#/components/schemas/AutoChunkingStrategyRequestParam' - static: '#/components/schemas/StaticChunkingStrategyRequestParam' CodeInterpreterFileOutput: type: object title: Code interpreter file output @@ -35739,9 +35717,6 @@ components: - $ref: '#/components/schemas/CodeInterpreterOutputImage' discriminator: propertyName: type - mapping: - image: '#/components/schemas/CodeInterpreterOutputImage' - logs: '#/components/schemas/CodeInterpreterOutputLogs' discriminator: propertyName: type description: > @@ -35923,8 +35898,6 @@ components: - $recursiveRef: '#' discriminator: propertyName: type - mapping: - eq: '#/components/schemas/ComparisonFilter' required: - type - filters @@ -35943,16 +35916,6 @@ components: - $ref: '#/components/schemas/WaitParam' discriminator: propertyName: type - mapping: - click: '#/components/schemas/ClickParam' - double_click: '#/components/schemas/DoubleClickAction' - drag: '#/components/schemas/DragParam' - keypress: '#/components/schemas/KeyPressAction' - move: '#/components/schemas/MoveParam' - screenshot: '#/components/schemas/ScreenshotParam' - scroll: '#/components/schemas/ScrollParam' - type: '#/components/schemas/TypeParam' - wait: '#/components/schemas/WaitParam' ComputerActionList: title: Computer Action List type: array @@ -36340,32 +36303,6 @@ components: - $ref: '#/components/schemas/CustomToolCallOutput' discriminator: propertyName: type - mapping: - apply_patch_call: '#/components/schemas/ApplyPatchToolCall' - apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutput' - code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' - compaction: '#/components/schemas/CompactionBody' - computer_call: '#/components/schemas/ComputerToolCall' - computer_call_output: '#/components/schemas/ComputerToolCallOutputResource' - custom_tool_call: '#/components/schemas/CustomToolCall' - custom_tool_call_output: '#/components/schemas/CustomToolCallOutput' - file_search_call: '#/components/schemas/FileSearchToolCall' - function_call: '#/components/schemas/FunctionToolCallResource' - function_call_output: '#/components/schemas/FunctionToolCallOutputResource' - image_generation_call: '#/components/schemas/ImageGenToolCall' - local_shell_call: '#/components/schemas/LocalShellToolCall' - local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' - mcp_approval_request: '#/components/schemas/MCPApprovalRequest' - mcp_approval_response: '#/components/schemas/MCPApprovalResponseResource' - mcp_call: '#/components/schemas/MCPToolCall' - mcp_list_tools: '#/components/schemas/MCPListTools' - message: '#/components/schemas/Message' - reasoning: '#/components/schemas/ReasoningItem' - shell_call: '#/components/schemas/FunctionShellCall' - shell_call_output: '#/components/schemas/FunctionShellCallOutput' - tool_search_call: '#/components/schemas/ToolSearchCall' - tool_search_output: '#/components/schemas/ToolSearchOutput' - web_search_call: '#/components/schemas/WebSearchToolCall' ConversationItemList: type: object title: The conversation item list @@ -36825,10 +36762,6 @@ components: - $ref: '#/components/schemas/ResponseFormatJsonObject' discriminator: propertyName: type - mapping: - json_object: '#/components/schemas/ResponseFormatJsonObject' - json_schema: '#/components/schemas/ResponseFormatJsonSchema' - text: '#/components/schemas/ResponseFormatText' audio: type: object nullable: true @@ -37784,9 +37717,6 @@ components: - $ref: '#/components/schemas/InlineSkillParam' discriminator: propertyName: type - mapping: - inline: '#/components/schemas/InlineSkillParam' - skill_reference: '#/components/schemas/SkillReferenceParam' memory_limit: type: string enum: @@ -37802,9 +37732,6 @@ components: - $ref: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' discriminator: propertyName: type - mapping: - allowlist: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' - disabled: '#/components/schemas/ContainerNetworkPolicyDisabledParam' required: - name CreateContainerFileBody: @@ -40219,9 +40146,6 @@ components: - $ref: '#/components/schemas/SpeechAudioDoneEvent' discriminator: propertyName: type - mapping: - speech.audio.delta: '#/components/schemas/SpeechAudioDeltaEvent' - speech.audio.done: '#/components/schemas/SpeechAudioDoneEvent' CreateThreadAndRunRequest: type: object additionalProperties: false @@ -40743,9 +40667,6 @@ components: title: Duration Usage discriminator: propertyName: type - mapping: - duration: '#/components/schemas/TranscriptTextUsageDuration' - tokens: '#/components/schemas/TranscriptTextUsageTokens' required: - task - duration @@ -40847,10 +40768,6 @@ components: - $ref: '#/components/schemas/TranscriptTextDoneEvent' discriminator: propertyName: type - mapping: - transcript.text.delta: '#/components/schemas/TranscriptTextDeltaEvent' - transcript.text.done: '#/components/schemas/TranscriptTextDoneEvent' - transcript.text.segment: '#/components/schemas/TranscriptTextSegmentEvent' CreateTranscriptionResponseVerboseJson: type: object description: >- @@ -44241,10 +44158,6 @@ components: - $ref: '#/components/schemas/InputFileContent' discriminator: propertyName: type - mapping: - input_file: '#/components/schemas/InputFileContent' - input_image: '#/components/schemas/InputImageContent' - input_text: '#/components/schemas/InputTextContent' FunctionObject: type: object properties: @@ -45313,9 +45226,6 @@ components: - $ref: '#/components/schemas/ImageEditCompletedEvent' discriminator: propertyName: type - mapping: - image_edit.completed: '#/components/schemas/ImageEditCompletedEvent' - image_edit.partial_image: '#/components/schemas/ImageEditPartialImageEvent' ImageGenCompletedEvent: type: object description: > @@ -45493,9 +45403,6 @@ components: - $ref: '#/components/schemas/ImageGenCompletedEvent' discriminator: propertyName: type - mapping: - image_generation.completed: '#/components/schemas/ImageGenCompletedEvent' - image_generation.partial_image: '#/components/schemas/ImageGenPartialImageEvent' ImageGenTool: type: object title: Image generation tool @@ -45830,10 +45737,6 @@ components: - $ref: '#/components/schemas/InputFileContent' discriminator: propertyName: type - mapping: - input_file: '#/components/schemas/InputFileContent' - input_image: '#/components/schemas/InputImageContent' - input_text: '#/components/schemas/InputTextContent' InputItem: oneOf: - $ref: '#/components/schemas/EasyInputMessage' @@ -45847,8 +45750,6 @@ components: - $ref: '#/components/schemas/ItemReferenceParam' discriminator: propertyName: type - mapping: - message: '#/components/schemas/EasyInputMessage' InputMessage: type: object title: Input message @@ -46149,32 +46050,6 @@ components: - $ref: '#/components/schemas/CustomToolCall' discriminator: propertyName: type - mapping: - apply_patch_call: '#/components/schemas/ApplyPatchToolCallItemParam' - apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutputItemParam' - code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' - compaction: '#/components/schemas/CompactionSummaryItemParam' - computer_call: '#/components/schemas/ComputerToolCall' - computer_call_output: '#/components/schemas/ComputerCallOutputItemParam' - custom_tool_call: '#/components/schemas/CustomToolCall' - custom_tool_call_output: '#/components/schemas/CustomToolCallOutput' - file_search_call: '#/components/schemas/FileSearchToolCall' - function_call: '#/components/schemas/FunctionToolCall' - function_call_output: '#/components/schemas/FunctionCallOutputItemParam' - image_generation_call: '#/components/schemas/ImageGenToolCall' - local_shell_call: '#/components/schemas/LocalShellToolCall' - local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' - mcp_approval_request: '#/components/schemas/MCPApprovalRequest' - mcp_approval_response: '#/components/schemas/MCPApprovalResponse' - mcp_call: '#/components/schemas/MCPToolCall' - mcp_list_tools: '#/components/schemas/MCPListTools' - message: '#/components/schemas/OutputMessage' - reasoning: '#/components/schemas/ReasoningItem' - shell_call: '#/components/schemas/FunctionShellCallItemParam' - shell_call_output: '#/components/schemas/FunctionShellCallOutputItemParam' - tool_search_call: '#/components/schemas/ToolSearchCallItemParam' - tool_search_output: '#/components/schemas/ToolSearchOutputItemParam' - web_search_call: '#/components/schemas/WebSearchToolCall' ItemResource: description: | Content item used to generate a response. @@ -46207,32 +46082,6 @@ components: - $ref: '#/components/schemas/CustomToolCallOutputResource' discriminator: propertyName: type - mapping: - apply_patch_call: '#/components/schemas/ApplyPatchToolCall' - apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutput' - code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' - compaction: '#/components/schemas/CompactionBody' - computer_call: '#/components/schemas/ComputerToolCall' - computer_call_output: '#/components/schemas/ComputerToolCallOutputResource' - custom_tool_call: '#/components/schemas/CustomToolCallResource' - custom_tool_call_output: '#/components/schemas/CustomToolCallOutputResource' - file_search_call: '#/components/schemas/FileSearchToolCall' - function_call: '#/components/schemas/FunctionToolCallResource' - function_call_output: '#/components/schemas/FunctionToolCallOutputResource' - image_generation_call: '#/components/schemas/ImageGenToolCall' - local_shell_call: '#/components/schemas/LocalShellToolCall' - local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' - mcp_approval_request: '#/components/schemas/MCPApprovalRequest' - mcp_approval_response: '#/components/schemas/MCPApprovalResponseResource' - mcp_call: '#/components/schemas/MCPToolCall' - mcp_list_tools: '#/components/schemas/MCPListTools' - message: '#/components/schemas/OutputMessage' - reasoning: '#/components/schemas/ReasoningItem' - shell_call: '#/components/schemas/FunctionShellCall' - shell_call_output: '#/components/schemas/FunctionShellCallOutput' - tool_search_call: '#/components/schemas/ToolSearchCall' - tool_search_output: '#/components/schemas/ToolSearchOutput' - web_search_call: '#/components/schemas/WebSearchToolCall' ListAssistantsResponse: type: object properties: @@ -48462,10 +48311,6 @@ components: - $ref: '#/components/schemas/ReasoningTextContent' discriminator: propertyName: type - mapping: - output_text: '#/components/schemas/OutputTextContent' - reasoning_text: '#/components/schemas/ReasoningTextContent' - refusal: '#/components/schemas/RefusalContent' OutputItem: oneOf: - $ref: '#/components/schemas/OutputMessage' @@ -48495,32 +48340,6 @@ components: - $ref: '#/components/schemas/CustomToolCallOutputResource' discriminator: propertyName: type - mapping: - apply_patch_call: '#/components/schemas/ApplyPatchToolCall' - apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutput' - code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' - compaction: '#/components/schemas/CompactionBody' - computer_call: '#/components/schemas/ComputerToolCall' - computer_call_output: '#/components/schemas/ComputerToolCallOutputResource' - custom_tool_call: '#/components/schemas/CustomToolCall' - custom_tool_call_output: '#/components/schemas/CustomToolCallOutputResource' - file_search_call: '#/components/schemas/FileSearchToolCall' - function_call: '#/components/schemas/FunctionToolCall' - function_call_output: '#/components/schemas/FunctionToolCallOutputResource' - image_generation_call: '#/components/schemas/ImageGenToolCall' - local_shell_call: '#/components/schemas/LocalShellToolCall' - local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' - mcp_approval_request: '#/components/schemas/MCPApprovalRequest' - mcp_approval_response: '#/components/schemas/MCPApprovalResponseResource' - mcp_call: '#/components/schemas/MCPToolCall' - mcp_list_tools: '#/components/schemas/MCPListTools' - message: '#/components/schemas/OutputMessage' - reasoning: '#/components/schemas/ReasoningItem' - shell_call: '#/components/schemas/FunctionShellCall' - shell_call_output: '#/components/schemas/FunctionShellCallOutput' - tool_search_call: '#/components/schemas/ToolSearchCall' - tool_search_output: '#/components/schemas/ToolSearchOutput' - web_search_call: '#/components/schemas/WebSearchToolCall' OutputMessage: type: object title: Output message @@ -48578,9 +48397,6 @@ components: - $ref: '#/components/schemas/RefusalContent' discriminator: propertyName: type - mapping: - output_text: '#/components/schemas/OutputTextContent' - refusal: '#/components/schemas/RefusalContent' ParallelToolCalls: description: >- Whether to enable [parallel function @@ -52725,18 +52541,6 @@ components: RealtimeClientEvent: discriminator: propertyName: type - mapping: - conversation.item.create: '#/components/schemas/RealtimeClientEventConversationItemCreate' - conversation.item.delete: '#/components/schemas/RealtimeClientEventConversationItemDelete' - conversation.item.retrieve: '#/components/schemas/RealtimeClientEventConversationItemRetrieve' - conversation.item.truncate: '#/components/schemas/RealtimeClientEventConversationItemTruncate' - input_audio_buffer.append: '#/components/schemas/RealtimeClientEventInputAudioBufferAppend' - input_audio_buffer.clear: '#/components/schemas/RealtimeClientEventInputAudioBufferClear' - input_audio_buffer.commit: '#/components/schemas/RealtimeClientEventInputAudioBufferCommit' - output_audio_buffer.clear: '#/components/schemas/RealtimeClientEventOutputAudioBufferClear' - response.cancel: '#/components/schemas/RealtimeClientEventResponseCancel' - response.create: '#/components/schemas/RealtimeClientEventResponseCreate' - session.update: '#/components/schemas/RealtimeClientEventSessionUpdate' description: | A realtime client event. anyOf: @@ -53441,14 +53245,6 @@ components: - $ref: '#/components/schemas/RealtimeMCPApprovalRequest' discriminator: propertyName: type - mapping: - function_call: '#/components/schemas/RealtimeConversationItemFunctionCall' - function_call_output: '#/components/schemas/RealtimeConversationItemFunctionCallOutput' - mcp_approval_request: '#/components/schemas/RealtimeMCPApprovalRequest' - mcp_approval_response: '#/components/schemas/RealtimeMCPApprovalResponse' - mcp_call: '#/components/schemas/RealtimeMCPToolCall' - mcp_list_tools: '#/components/schemas/RealtimeMCPListTools' - message: '#/components/schemas/RealtimeConversationItemMessageAssistant' RealtimeConversationItemFunctionCall: type: object title: Realtime function call item @@ -53974,9 +53770,6 @@ components: #/components/schemas/RealtimeTranscriptionSessionCreateResponseGA discriminator: propertyName: type - mapping: - realtime: '#/components/schemas/RealtimeSessionCreateResponseGA' - transcription: '#/components/schemas/RealtimeTranscriptionSessionCreateResponseGA' required: - value - expires_at @@ -54615,53 +54408,6 @@ components: RealtimeServerEvent: discriminator: propertyName: type - mapping: - conversation.created: '#/components/schemas/RealtimeServerEventConversationCreated' - conversation.item.added: '#/components/schemas/RealtimeServerEventConversationItemAdded' - conversation.item.created: '#/components/schemas/RealtimeServerEventConversationItemCreated' - conversation.item.deleted: '#/components/schemas/RealtimeServerEventConversationItemDeleted' - conversation.item.done: '#/components/schemas/RealtimeServerEventConversationItemDone' - conversation.item.input_audio_transcription.completed: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionCompleted' - conversation.item.input_audio_transcription.delta: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionDelta' - conversation.item.input_audio_transcription.failed: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionFailed' - conversation.item.input_audio_transcription.segment: '#/components/schemas/RealtimeServerEventConversationItemInputAudioTranscriptionSegment' - conversation.item.retrieved: '#/components/schemas/RealtimeServerEventConversationItemRetrieved' - conversation.item.truncated: '#/components/schemas/RealtimeServerEventConversationItemTruncated' - error: '#/components/schemas/RealtimeServerEventError' - input_audio_buffer.cleared: '#/components/schemas/RealtimeServerEventInputAudioBufferCleared' - input_audio_buffer.committed: '#/components/schemas/RealtimeServerEventInputAudioBufferCommitted' - input_audio_buffer.dtmf_event_received: '#/components/schemas/RealtimeServerEventInputAudioBufferDtmfEventReceived' - input_audio_buffer.speech_started: '#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStarted' - input_audio_buffer.speech_stopped: '#/components/schemas/RealtimeServerEventInputAudioBufferSpeechStopped' - input_audio_buffer.timeout_triggered: '#/components/schemas/RealtimeServerEventInputAudioBufferTimeoutTriggered' - mcp_list_tools.completed: '#/components/schemas/RealtimeServerEventMCPListToolsCompleted' - mcp_list_tools.failed: '#/components/schemas/RealtimeServerEventMCPListToolsFailed' - mcp_list_tools.in_progress: '#/components/schemas/RealtimeServerEventMCPListToolsInProgress' - output_audio_buffer.cleared: '#/components/schemas/RealtimeServerEventOutputAudioBufferCleared' - output_audio_buffer.started: '#/components/schemas/RealtimeServerEventOutputAudioBufferStarted' - output_audio_buffer.stopped: '#/components/schemas/RealtimeServerEventOutputAudioBufferStopped' - rate_limits.updated: '#/components/schemas/RealtimeServerEventRateLimitsUpdated' - response.content_part.added: '#/components/schemas/RealtimeServerEventResponseContentPartAdded' - response.content_part.done: '#/components/schemas/RealtimeServerEventResponseContentPartDone' - response.created: '#/components/schemas/RealtimeServerEventResponseCreated' - response.done: '#/components/schemas/RealtimeServerEventResponseDone' - response.function_call_arguments.delta: '#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDelta' - response.function_call_arguments.done: '#/components/schemas/RealtimeServerEventResponseFunctionCallArgumentsDone' - response.mcp_call.completed: '#/components/schemas/RealtimeServerEventResponseMCPCallCompleted' - response.mcp_call.failed: '#/components/schemas/RealtimeServerEventResponseMCPCallFailed' - response.mcp_call.in_progress: '#/components/schemas/RealtimeServerEventResponseMCPCallInProgress' - response.mcp_call_arguments.delta: '#/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDelta' - response.mcp_call_arguments.done: '#/components/schemas/RealtimeServerEventResponseMCPCallArgumentsDone' - response.output_audio.delta: '#/components/schemas/RealtimeServerEventResponseAudioDelta' - response.output_audio.done: '#/components/schemas/RealtimeServerEventResponseAudioDone' - response.output_audio_transcript.delta: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDelta' - response.output_audio_transcript.done: '#/components/schemas/RealtimeServerEventResponseAudioTranscriptDone' - response.output_item.added: '#/components/schemas/RealtimeServerEventResponseOutputItemAdded' - response.output_item.done: '#/components/schemas/RealtimeServerEventResponseOutputItemDone' - response.output_text.delta: '#/components/schemas/RealtimeServerEventResponseTextDelta' - response.output_text.done: '#/components/schemas/RealtimeServerEventResponseTextDone' - session.created: '#/components/schemas/RealtimeServerEventSessionCreated' - session.updated: '#/components/schemas/RealtimeServerEventSessionUpdated' description: | A realtime server event. anyOf: @@ -62273,60 +62019,6 @@ components: - $ref: '#/components/schemas/ResponseCustomToolCallInputDoneEvent' discriminator: propertyName: type - mapping: - error: '#/components/schemas/ResponseErrorEvent' - response.audio.delta: '#/components/schemas/ResponseAudioDeltaEvent' - response.audio.done: '#/components/schemas/ResponseAudioDoneEvent' - response.audio.transcript.delta: '#/components/schemas/ResponseAudioTranscriptDeltaEvent' - response.audio.transcript.done: '#/components/schemas/ResponseAudioTranscriptDoneEvent' - response.code_interpreter_call.completed: '#/components/schemas/ResponseCodeInterpreterCallCompletedEvent' - response.code_interpreter_call.in_progress: '#/components/schemas/ResponseCodeInterpreterCallInProgressEvent' - response.code_interpreter_call.interpreting: '#/components/schemas/ResponseCodeInterpreterCallInterpretingEvent' - response.code_interpreter_call_code.delta: '#/components/schemas/ResponseCodeInterpreterCallCodeDeltaEvent' - response.code_interpreter_call_code.done: '#/components/schemas/ResponseCodeInterpreterCallCodeDoneEvent' - response.completed: '#/components/schemas/ResponseCompletedEvent' - response.content_part.added: '#/components/schemas/ResponseContentPartAddedEvent' - response.content_part.done: '#/components/schemas/ResponseContentPartDoneEvent' - response.created: '#/components/schemas/ResponseCreatedEvent' - response.custom_tool_call_input.delta: '#/components/schemas/ResponseCustomToolCallInputDeltaEvent' - response.custom_tool_call_input.done: '#/components/schemas/ResponseCustomToolCallInputDoneEvent' - response.failed: '#/components/schemas/ResponseFailedEvent' - response.file_search_call.completed: '#/components/schemas/ResponseFileSearchCallCompletedEvent' - response.file_search_call.in_progress: '#/components/schemas/ResponseFileSearchCallInProgressEvent' - response.file_search_call.searching: '#/components/schemas/ResponseFileSearchCallSearchingEvent' - response.function_call_arguments.delta: '#/components/schemas/ResponseFunctionCallArgumentsDeltaEvent' - response.function_call_arguments.done: '#/components/schemas/ResponseFunctionCallArgumentsDoneEvent' - response.image_generation_call.completed: '#/components/schemas/ResponseImageGenCallCompletedEvent' - response.image_generation_call.generating: '#/components/schemas/ResponseImageGenCallGeneratingEvent' - response.image_generation_call.in_progress: '#/components/schemas/ResponseImageGenCallInProgressEvent' - response.image_generation_call.partial_image: '#/components/schemas/ResponseImageGenCallPartialImageEvent' - response.in_progress: '#/components/schemas/ResponseInProgressEvent' - response.incomplete: '#/components/schemas/ResponseIncompleteEvent' - response.mcp_call.completed: '#/components/schemas/ResponseMCPCallCompletedEvent' - response.mcp_call.failed: '#/components/schemas/ResponseMCPCallFailedEvent' - response.mcp_call.in_progress: '#/components/schemas/ResponseMCPCallInProgressEvent' - response.mcp_call_arguments.delta: '#/components/schemas/ResponseMCPCallArgumentsDeltaEvent' - response.mcp_call_arguments.done: '#/components/schemas/ResponseMCPCallArgumentsDoneEvent' - response.mcp_list_tools.completed: '#/components/schemas/ResponseMCPListToolsCompletedEvent' - response.mcp_list_tools.failed: '#/components/schemas/ResponseMCPListToolsFailedEvent' - response.mcp_list_tools.in_progress: '#/components/schemas/ResponseMCPListToolsInProgressEvent' - response.output_item.added: '#/components/schemas/ResponseOutputItemAddedEvent' - response.output_item.done: '#/components/schemas/ResponseOutputItemDoneEvent' - response.output_text.annotation.added: '#/components/schemas/ResponseOutputTextAnnotationAddedEvent' - response.output_text.delta: '#/components/schemas/ResponseTextDeltaEvent' - response.output_text.done: '#/components/schemas/ResponseTextDoneEvent' - response.queued: '#/components/schemas/ResponseQueuedEvent' - response.reasoning_summary_part.added: '#/components/schemas/ResponseReasoningSummaryPartAddedEvent' - response.reasoning_summary_part.done: '#/components/schemas/ResponseReasoningSummaryPartDoneEvent' - response.reasoning_summary_text.delta: '#/components/schemas/ResponseReasoningSummaryTextDeltaEvent' - response.reasoning_summary_text.done: '#/components/schemas/ResponseReasoningSummaryTextDoneEvent' - response.reasoning_text.delta: '#/components/schemas/ResponseReasoningTextDeltaEvent' - response.reasoning_text.done: '#/components/schemas/ResponseReasoningTextDoneEvent' - response.refusal.delta: '#/components/schemas/ResponseRefusalDeltaEvent' - response.refusal.done: '#/components/schemas/ResponseRefusalDoneEvent' - response.web_search_call.completed: '#/components/schemas/ResponseWebSearchCallCompletedEvent' - response.web_search_call.in_progress: '#/components/schemas/ResponseWebSearchCallInProgressEvent' - response.web_search_call.searching: '#/components/schemas/ResponseWebSearchCallSearchingEvent' ResponseStreamOptions: anyOf: - description: > @@ -62641,8 +62333,6 @@ components: ResponsesClientEvent: discriminator: propertyName: type - mapping: - response.create: '#/components/schemas/ResponsesClientEventResponseCreate' description: | Client events accepted by the Responses WebSocket server. anyOf: @@ -64637,22 +64327,6 @@ components: A tool that can be used to generate a response. discriminator: propertyName: type - mapping: - apply_patch: '#/components/schemas/ApplyPatchToolParam' - code_interpreter: '#/components/schemas/CodeInterpreterTool' - computer: '#/components/schemas/ComputerTool' - computer_use_preview: '#/components/schemas/ComputerUsePreviewTool' - custom: '#/components/schemas/CustomToolParam' - file_search: '#/components/schemas/FileSearchTool' - function: '#/components/schemas/FunctionTool' - image_generation: '#/components/schemas/ImageGenTool' - local_shell: '#/components/schemas/LocalShellToolParam' - mcp: '#/components/schemas/MCPTool' - namespace: '#/components/schemas/NamespaceToolParam' - shell: '#/components/schemas/FunctionShellToolParam' - tool_search: '#/components/schemas/ToolSearchToolParam' - web_search: '#/components/schemas/WebSearchTool' - web_search_preview: '#/components/schemas/WebSearchPreviewTool' oneOf: - $ref: '#/components/schemas/FunctionTool' - $ref: '#/components/schemas/FileSearchTool' @@ -67239,10 +66913,6 @@ components: - $ref: '#/components/schemas/WebSearchActionFind' discriminator: propertyName: type - mapping: - find_in_page: '#/components/schemas/WebSearchActionFind' - open_page: '#/components/schemas/WebSearchActionOpenPage' - search: '#/components/schemas/WebSearchActionSearch' required: - id - type @@ -68437,11 +68107,6 @@ components: description: An annotation that applies to a span of output text. discriminator: propertyName: type - mapping: - container_file_citation: '#/components/schemas/ContainerFileCitationBody' - file_citation: '#/components/schemas/FileCitationBody' - file_path: '#/components/schemas/FilePath' - url_citation: '#/components/schemas/UrlCitationBody' TopLogProb: properties: token: @@ -68737,16 +68402,6 @@ components: description: A content part that makes up an input or output item. discriminator: propertyName: type - mapping: - computer_screenshot: '#/components/schemas/ComputerScreenshotContent' - input_file: '#/components/schemas/InputFileContent' - input_image: '#/components/schemas/InputImageContent' - input_text: '#/components/schemas/InputTextContent' - output_text: '#/components/schemas/OutputTextContent' - reasoning_text: '#/components/schemas/ReasoningTextContent' - refusal: '#/components/schemas/RefusalContent' - summary_text: '#/components/schemas/SummaryTextContent' - text: '#/components/schemas/TextContent' type: array description: The content of the message phase: @@ -69332,9 +68987,6 @@ components: description: Network access policy for the container. discriminator: propertyName: type - mapping: - allowlist: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' - disabled: '#/components/schemas/ContainerNetworkPolicyDisabledParam' type: object required: - type @@ -69403,9 +69055,6 @@ components: description: Network access policy for the container. discriminator: propertyName: type - mapping: - allowlist: '#/components/schemas/ContainerNetworkPolicyAllowlistParam' - disabled: '#/components/schemas/ContainerNetworkPolicyDisabledParam' skills: items: oneOf: @@ -69413,9 +69062,6 @@ components: - $ref: '#/components/schemas/InlineSkillParam' discriminator: propertyName: type - mapping: - inline: '#/components/schemas/InlineSkillParam' - skill_reference: '#/components/schemas/SkillReferenceParam' type: array maxItems: 200 description: An optional list of skills referenced by id or inline data. @@ -69490,10 +69136,6 @@ components: - $ref: '#/components/schemas/ContainerReferenceParam' discriminator: propertyName: type - mapping: - container_auto: '#/components/schemas/ContainerAutoParam' - container_reference: '#/components/schemas/ContainerReferenceParam' - local: '#/components/schemas/LocalEnvironmentParam' - type: 'null' type: object required: @@ -69565,9 +69207,6 @@ components: description: The input format for the custom tool. Default is unconstrained text. discriminator: propertyName: type - mapping: - grammar: '#/components/schemas/CustomGrammarFormatParam' - text: '#/components/schemas/CustomTextFormatParam' defer_loading: type: boolean description: Whether this tool should be deferred and discovered via tool search. @@ -69642,9 +69281,6 @@ components: description: A function or custom tool that belongs to a namespace. discriminator: propertyName: type - mapping: - custom: '#/components/schemas/CustomToolParam' - function: '#/components/schemas/FunctionToolParam' type: array minItems: 1 description: The function/custom tools available inside this namespace. @@ -70024,9 +69660,6 @@ components: - $ref: '#/components/schemas/ContainerReferenceResource' discriminator: propertyName: type - mapping: - container_reference: '#/components/schemas/ContainerReferenceResource' - local: '#/components/schemas/LocalEnvironmentResource' - type: 'null' created_by: type: string @@ -70099,9 +69732,6 @@ components: outcome for a shell call output chunk. discriminator: propertyName: type - mapping: - exit: '#/components/schemas/FunctionShellCallOutputExitOutcome' - timeout: '#/components/schemas/FunctionShellCallOutputTimeoutOutcome' created_by: type: string description: The identifier of the actor that created the item. @@ -70260,10 +69890,6 @@ components: applied via apply_patch. discriminator: propertyName: type - mapping: - create_file: '#/components/schemas/ApplyPatchCreateFileOperation' - delete_file: '#/components/schemas/ApplyPatchDeleteFileOperation' - update_file: '#/components/schemas/ApplyPatchUpdateFileOperation' created_by: type: string description: The ID of the entity that created this tool call. @@ -70530,10 +70156,6 @@ components: description: A piece of message content, such as text, an image, or a file. discriminator: propertyName: type - mapping: - input_file: '#/components/schemas/InputFileContentParam' - input_image: '#/components/schemas/InputImageContentParamAutoParam' - input_text: '#/components/schemas/InputTextContentParam' type: array description: >- An array of content outputs (text, image, file) for the function @@ -70732,9 +70354,6 @@ components: description: The environment to execute the shell commands in. discriminator: propertyName: type - mapping: - container_reference: '#/components/schemas/ContainerReferenceParam' - local: '#/components/schemas/LocalEnvironmentParam' - type: 'null' type: object required: @@ -70783,9 +70402,6 @@ components: description: The exit or timeout outcome associated with this shell call. discriminator: propertyName: type - mapping: - exit: '#/components/schemas/FunctionShellCallOutputExitOutcomeParam' - timeout: '#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam' FunctionShellCallOutputContentParam: properties: stdout: @@ -70939,10 +70555,6 @@ components: to the apply_patch tool. discriminator: propertyName: type - mapping: - create_file: '#/components/schemas/ApplyPatchCreateFileOperationParam' - delete_file: '#/components/schemas/ApplyPatchDeleteFileOperationParam' - update_file: '#/components/schemas/ApplyPatchUpdateFileOperationParam' ApplyPatchToolCallItemParam: properties: type: @@ -71892,32 +71504,6 @@ components: other response element. discriminator: propertyName: type - mapping: - apply_patch_call: '#/components/schemas/ApplyPatchToolCall' - apply_patch_call_output: '#/components/schemas/ApplyPatchToolCallOutput' - code_interpreter_call: '#/components/schemas/CodeInterpreterToolCall' - compaction: '#/components/schemas/CompactionBody' - computer_call: '#/components/schemas/ComputerToolCall' - computer_call_output: '#/components/schemas/ComputerToolCallOutputResource' - custom_tool_call: '#/components/schemas/CustomToolCall' - custom_tool_call_output: '#/components/schemas/CustomToolCallOutput' - file_search_call: '#/components/schemas/FileSearchToolCall' - function_call: '#/components/schemas/FunctionToolCall' - function_call_output: '#/components/schemas/FunctionToolCallOutput' - image_generation_call: '#/components/schemas/ImageGenToolCall' - local_shell_call: '#/components/schemas/LocalShellToolCall' - local_shell_call_output: '#/components/schemas/LocalShellToolCallOutput' - mcp_approval_request: '#/components/schemas/MCPApprovalRequest' - mcp_approval_response: '#/components/schemas/MCPApprovalResponseResource' - mcp_call: '#/components/schemas/MCPToolCall' - mcp_list_tools: '#/components/schemas/MCPListTools' - message: '#/components/schemas/Message' - reasoning: '#/components/schemas/ReasoningItem' - shell_call: '#/components/schemas/FunctionShellCall' - shell_call_output: '#/components/schemas/FunctionShellCallOutput' - tool_search_call: '#/components/schemas/ToolSearchCall' - tool_search_output: '#/components/schemas/ToolSearchOutput' - web_search_call: '#/components/schemas/WebSearchToolCall' CompactResource: properties: id: @@ -72719,9 +72305,6 @@ components: description: Content blocks that comprise a user message. discriminator: propertyName: type - mapping: - input_text: '#/components/schemas/UserMessageInputText' - quoted_text: '#/components/schemas/UserMessageQuotedText' type: array description: Ordered content elements supplied by the user. attachments: @@ -72842,9 +72425,6 @@ components: description: Annotation object describing a cited source. discriminator: propertyName: type - mapping: - file: '#/components/schemas/FileAnnotation' - url: '#/components/schemas/UrlAnnotation' type: array description: Ordered list of annotations attached to the response text. type: object @@ -73131,13 +72711,6 @@ components: title: The thread item discriminator: propertyName: type - mapping: - chatkit.assistant_message: '#/components/schemas/AssistantMessageItem' - chatkit.client_tool_call: '#/components/schemas/ClientToolCallItem' - chatkit.task: '#/components/schemas/TaskItem' - chatkit.task_group: '#/components/schemas/TaskGroupItem' - chatkit.user_message: '#/components/schemas/UserMessageItem' - chatkit.widget: '#/components/schemas/WidgetMessageItem' ThreadItemListResource: properties: object: @@ -73264,10 +72837,6 @@ components: created threads. discriminator: propertyName: type - mapping: - active: '#/components/schemas/ActiveStatus' - closed: '#/components/schemas/ClosedStatus' - locked: '#/components/schemas/LockedStatus' user: type: string description: Free-form string that identifies your end user who owns the thread. From f7e015e364ed9b05545ee4ac9ef301768385c315 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Fri, 22 May 2026 23:12:42 +0300 Subject: [PATCH 16/31] Add generation automation via Makefile and extraction script Adds `make generate` which runs swift-openapi-generator and then extracts the Components enum from the output into Components.swift, stripping typealias lines that shadow Swift built-in names and would cause invalid redeclaration build errors. Co-Authored-By: Claude Sonnet 4.6 --- Makefile | 13 ++ Scripts/extract_components.py | 98 ++++++++++++++ .../Public/Schemas/Generated/Components.swift | 120 +----------------- 3 files changed, 112 insertions(+), 119 deletions(-) create mode 100644 Makefile create mode 100644 Scripts/extract_components.py diff --git a/Makefile b/Makefile new file mode 100644 index 00000000..f70182cf --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ +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 + +.PHONY: generate +generate: + cd "$(GENERATOR_DIR)" && swift run swift-openapi-generator generate \ + --config "$(PROJECT_DIR)/openapi-generator-config.yaml" \ + "$(PROJECT_DIR)/openapi.with-code-samples.yml" + python3 "$(PROJECT_DIR)/Scripts/extract_components.py" \ + "$(TYPES_SWIFT)" \ + "$(COMPONENTS_SWIFT)" diff --git a/Scripts/extract_components.py b/Scripts/extract_components.py new file mode 100644 index 00000000..8de2af79 --- /dev/null +++ b/Scripts/extract_components.py @@ -0,0 +1,98 @@ +#!/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 + +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/Sources/OpenAI/Public/Schemas/Generated/Components.swift b/Sources/OpenAI/Public/Schemas/Generated/Components.swift index 334ecaf5..6b88d0b9 100644 --- a/Sources/OpenAI/Public/Schemas/Generated/Components.swift +++ b/Sources/OpenAI/Public/Schemas/Generated/Components.swift @@ -16,69 +16,6 @@ import struct Foundation.Data import struct Foundation.Date #endif -/** - The code here is generated using OpenAPI document provided by OpenAI. - - # OpenAI OpenAPI source: # - https://app.stainless.com/api/spec/documented/openai/openapi.documented.yml - - # openapi.documented.yml info: # - info: - title: OpenAI API - description: The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details. - version: 2.3.0 - termsOfService: https://openai.com/policies/terms-of-use - contact: - name: OpenAI Support - url: https://help.openai.com/ - license: - name: MIT - url: https://github.com/openai/openai-openapi/blob/master/LICENSE - - # Command that was used to generate the code # - `swift run swift-openapi-generator generate --config openapi-generator-config.yaml openapi.documented.yml` - - # Contents of config that was used to generate the code # - generate: - - types - namingStrategy: idiomatic - accessModifier: public - filter: - paths: - - /audio/transcriptions - - /responses - - /responses/{response_id} - - /responses/{response_id}/input_items - schemas: - - WebSearchLocation - - WebSearchContextSize - - # Console output describing how generator was configured for that run # - Swift OpenAPI Generator is running with the following configuration: - - OpenAPI document path: /Users/oleksiinezhyborets/Projects/swift-openapi-generator/openapi.documented.yml - - Configuration path: /Users/oleksiinezhyborets/Projects/swift-openapi-generator/openapi-generator-config.yaml - - Generator modes: types - - Access modifier: public - - Naming strategy: idiomatic - - Name overrides: - - Type overrides: - - Feature flags: - - Output file names: Types.swift - - Output directory: /Users/oleksiinezhyborets/Projects/swift-openapi-generator - - Diagnostics output path: - - Current directory: /Users/oleksiinezhyborets/Projects/swift-openapi-generator - - Plugin source: - - Is dry run: false - - Additional imports: - - Additional file comments: - - # Manual operations after Types.swift file was generated # - - Extract Components enum from Types.swift into it's own file, as we don't need other top level files - - Delete `generateSummary` from Reasoning.init to silence deprecation warnings - - Change discriminators of `Annotation` from FileCitationBody, UrlCitationBody, ContainerFileCitationBody, FilePath to file_citation, url_citation, container_file_citation, file_path. Seems that they either wrongly declared in yml or wrongly generated by Swift Generator. - */ - -/// Types generated from the components section of the OpenAPI document. public enum Components { /// Types generated from the `#/components/schemas` section of the OpenAPI document. public enum Schemas { @@ -220,7 +157,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/container_id`. public var containerId: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/code`. public var code: Swift.String? /// - Remark: Generated from `#/components/schemas/CodeInterpreterToolCall/OutputsPayload`. @@ -1042,12 +978,10 @@ public enum Components { public typealias IncludeEnum = [Components.Schemas.IncludeEnum] /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/include`. public var include: [Components.Schemas.IncludeEnum]? - public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/parallel_tool_calls`. public var parallelToolCalls: Swift.Bool? /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/store`. public var store: Swift.Bool? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/instructions`. public var instructions: Swift.String? /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/stream`. @@ -1062,7 +996,6 @@ public enum Components { public typealias ContextManagementParam = [Components.Schemas.ContextManagementParam] /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/context_management`. public var contextManagement: [Components.Schemas.ContextManagementParam]? - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/CreateResponse/value3/max_output_tokens`. public var maxOutputTokens: Swift.Int? /// Creates a new `Value3Payload`. @@ -2093,7 +2026,6 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/Error`. public struct _Error: Codable, Hashable, Sendable { - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/Error/code`. public var code: Swift.String? /// - Remark: Generated from `#/components/schemas/Error/message`. @@ -3029,7 +2961,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ImageGenToolCall/status`. public var status: Components.Schemas.ImageGenToolCall.StatusPayload - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ImageGenToolCall/result`. public var result: Swift.String? /// Creates a new `ImageGenToolCall`. @@ -3909,7 +3840,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/type`. public var _type: Components.Schemas.MCPApprovalResponse._TypePayload - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPApprovalResponse/id`. public var id: Swift.String? /// The ID of the approval request being answered. @@ -3985,7 +3915,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPApprovalResponseResource/approve`. public var approve: Swift.Bool - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPApprovalResponseResource/reason`. public var reason: Swift.String? /// Creates a new `MCPApprovalResponseResource`. @@ -4049,7 +3978,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPListTools/tools`. public var tools: [Components.Schemas.MCPListToolsTool] - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPListTools/error`. public var error: Swift.String? /// Creates a new `MCPListTools`. @@ -4091,7 +4019,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/name`. public var name: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPListToolsTool/description`. public var description: Swift.String? /// The JSON schema describing the tool's input. @@ -4470,7 +4397,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/MCPToolCall/arguments`. public var arguments: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/MCPToolCall/output`. public var output: Swift.String? /// - Remark: Generated from `#/components/schemas/MCPToolCall/error`. @@ -4807,10 +4733,8 @@ public enum Components { public struct ModelResponseProperties: Codable, Hashable, Sendable { /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/metadata`. public var metadata: Components.Schemas.Metadata? - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/top_logprobs`. public var topLogprobs: Swift.Int? - public typealias Double = Swift.Double /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/temperature`. public var temperature: Swift.Double? /// - Remark: Generated from `#/components/schemas/ModelResponseProperties/top_p`. @@ -5248,7 +5172,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/Prompt/id`. public var id: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/Prompt/version`. public var version: Swift.String? /// - Remark: Generated from `#/components/schemas/Prompt/variables`. @@ -5381,7 +5304,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ReasoningItem/id`. public var id: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ReasoningItem/encrypted_content`. public var encryptedContent: Swift.String? /// Reasoning summary content. @@ -5492,7 +5414,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/Response/value3/created_at`. public var createdAt: Swift.Double - public typealias Double = Swift.Double /// - Remark: Generated from `#/components/schemas/Response/value3/completed_at`. public var completedAt: Swift.Double? /// - Remark: Generated from `#/components/schemas/Response/value3/error`. @@ -5590,7 +5511,6 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/Response/value3/instructions`. public var instructions: Components.Schemas.Response.Value3Payload.InstructionsPayload? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/Response/value3/output_text`. public var outputText: Swift.String? /// - Remark: Generated from `#/components/schemas/Response/value3/usage`. @@ -5604,7 +5524,6 @@ public enum Components { public typealias Conversation2 = Components.Schemas.Conversation2 /// - Remark: Generated from `#/components/schemas/Response/value3/conversation`. public var conversation: Components.Schemas.Conversation2? - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/Response/value3/max_output_tokens`. public var maxOutputTokens: Swift.Int? /// Creates a new `Value3Payload`. @@ -6594,7 +6513,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/type`. public var _type: Components.Schemas.ResponseErrorEvent._TypePayload - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ResponseErrorEvent/code`. public var code: Swift.String? /// The error message. @@ -8205,7 +8123,6 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/ResponseProperties`. public struct ResponseProperties: Codable, Hashable, Sendable { - public typealias String = Swift.String /// - 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 @@ -8220,10 +8137,8 @@ public enum Components { public typealias Reasoning = Components.Schemas.Reasoning /// - Remark: Generated from `#/components/schemas/ResponseProperties/reasoning`. public var reasoning: Components.Schemas.Reasoning? - public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/ResponseProperties/background`. public var background: Swift.Bool? - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/ResponseProperties/max_tool_calls`. public var maxToolCalls: Swift.Int? /// - Remark: Generated from `#/components/schemas/ResponseProperties/text`. @@ -10250,7 +10165,6 @@ public enum Components { public var name: Swift.String /// - Remark: Generated from `#/components/schemas/TextResponseFormatJsonSchema/schema`. public var schema: Components.Schemas.ResponseFormatJsonSchemaSchema - public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/TextResponseFormatJsonSchema/strict`. public var strict: Swift.Bool? /// Creates a new `TextResponseFormatJsonSchema`. @@ -10600,7 +10514,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolChoiceMCP/server_label`. public var serverLabel: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ToolChoiceMCP/name`. public var name: Swift.String? /// Creates a new `ToolChoiceMCP`. @@ -11632,7 +11545,6 @@ public enum Components { public var _type: Components.Schemas.WebSearchActionOpenPage._TypePayload /// The URL opened by the model. /// - public typealias String = Swift.String /// The URL opened by the model. /// /// @@ -11771,7 +11683,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/type`. public var _type: Components.Schemas.WebSearchApproximateLocation._TypePayload? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/country`. public var country: Swift.String? /// - Remark: Generated from `#/components/schemas/WebSearchApproximateLocation/region`. @@ -12827,7 +12738,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/InputImageContent/type`. public var _type: Components.Schemas.InputImageContent._TypePayload - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputImageContent/image_url`. public var imageUrl: Swift.String? /// - Remark: Generated from `#/components/schemas/InputImageContent/file_id`. @@ -12880,7 +12790,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/InputFileContent/type`. public var _type: Components.Schemas.InputFileContent._TypePayload - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputFileContent/file_id`. public var fileId: Swift.String? /// The name of the file to be sent to the model. @@ -13377,7 +13286,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/id`. public var id: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/code`. public var code: Swift.String? /// - Remark: Generated from `#/components/schemas/ComputerCallSafetyCheckParam/message`. @@ -13430,7 +13338,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolSearchCall/id`. public var id: Swift.String - public typealias String = Swift.String /// - 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. @@ -13504,7 +13411,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionTool/name`. public var name: Swift.String - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/FunctionTool/description`. public var description: Swift.String? /// A JSON schema object describing the parameters of the function. @@ -13529,7 +13435,6 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/FunctionTool/parameters`. public var parameters: Components.Schemas.FunctionTool.ParametersPayload? - public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/FunctionTool/strict`. public var strict: Swift.Bool? /// Whether this function is deferred and loaded via tool search. @@ -14450,14 +14355,12 @@ public enum Components { public struct FunctionToolParam: Codable, Hashable, Sendable { /// - Remark: Generated from `#/components/schemas/FunctionToolParam/name`. public var name: Swift.String - public typealias String = 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? - public typealias Bool = Swift.Bool /// - Remark: Generated from `#/components/schemas/FunctionToolParam/strict`. public var strict: Swift.Bool? /// - Remark: Generated from `#/components/schemas/FunctionToolParam/type`. @@ -14615,7 +14518,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolSearchToolParam/execution`. public var execution: Components.Schemas.ToolSearchExecutionType? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ToolSearchToolParam/description`. public var description: Swift.String? /// - Remark: Generated from `#/components/schemas/EmptyModelParam`. @@ -14659,7 +14561,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApproximateLocation/type`. public var _type: Components.Schemas.ApproximateLocation._TypePayload - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ApproximateLocation/country`. public var country: Swift.String? /// - Remark: Generated from `#/components/schemas/ApproximateLocation/region`. @@ -14799,7 +14700,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ToolSearchOutput/id`. public var id: Swift.String - public typealias String = Swift.String /// - 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. @@ -14994,10 +14894,8 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/command`. public var command: [Swift.String] - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/timeout_ms`. public var timeoutMs: Swift.Int? - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/LocalShellExecAction/working_directory`. public var workingDirectory: Swift.String? /// Environment variables to set for the command. @@ -15065,7 +14963,6 @@ public enum Components { public struct FunctionShellAction: Codable, Hashable, Sendable { /// - Remark: Generated from `#/components/schemas/FunctionShellAction/commands`. public var commands: [Swift.String] - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/FunctionShellAction/timeout_ms`. public var timeoutMs: Swift.Int? /// - Remark: Generated from `#/components/schemas/FunctionShellAction/max_output_length`. @@ -15445,7 +15342,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/output`. public var output: [Components.Schemas.FunctionShellCallOutputContent] - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutput/max_output_length`. public var maxOutputLength: Swift.Int? /// The identifier of the actor that created the item. @@ -15758,7 +15654,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/status`. public var status: Components.Schemas.ApplyPatchCallOutputStatus - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutput/output`. public var output: Swift.String? /// The ID of the entity that created this tool call output. @@ -15823,7 +15718,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam`. public struct ComputerCallOutputItemParam: Codable, Hashable, Sendable { - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ComputerCallOutputItemParam/id`. public var id: Swift.String? /// The ID of the computer tool call that produced the output. @@ -15932,7 +15826,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/type`. public var _type: Components.Schemas.InputImageContentParamAutoParam._TypePayload - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/image_url`. public var imageUrl: Swift.String? /// - Remark: Generated from `#/components/schemas/InputImageContentParamAutoParam/file_id`. @@ -15985,7 +15878,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/InputFileContentParam/type`. public var _type: Components.Schemas.InputFileContentParam._TypePayload - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/InputFileContentParam/file_id`. public var fileId: Swift.String? /// - Remark: Generated from `#/components/schemas/InputFileContentParam/filename`. @@ -16035,7 +15927,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam`. public struct FunctionCallOutputItemParam: Codable, Hashable, Sendable { - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/FunctionCallOutputItemParam/id`. public var id: Swift.String? /// The unique ID of the function tool call generated by the model. @@ -16181,7 +16072,6 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam`. public struct ToolSearchCallItemParam: Codable, Hashable, Sendable { - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/id`. public var id: Swift.String? /// - Remark: Generated from `#/components/schemas/ToolSearchCallItemParam/call_id`. @@ -16243,7 +16133,6 @@ public enum Components { } /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam`. public struct ToolSearchOutputItemParam: Codable, Hashable, Sendable { - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/id`. public var id: Swift.String? /// - Remark: Generated from `#/components/schemas/ToolSearchOutputItemParam/call_id`. @@ -16307,7 +16196,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/CompactionSummaryItemParam`. public struct CompactionSummaryItemParam: Codable, Hashable, Sendable { - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/CompactionSummaryItemParam/id`. public var id: Swift.String? /// The type of the item. Always `compaction`. @@ -16353,7 +16241,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/commands`. public var commands: [Swift.String] - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/timeout_ms`. public var timeoutMs: Swift.Int? /// - Remark: Generated from `#/components/schemas/FunctionShellActionParam/max_output_length`. @@ -16391,7 +16278,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam`. public struct FunctionShellCallItemParam: Codable, Hashable, Sendable { - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/FunctionShellCallItemParam/id`. public var id: Swift.String? /// The unique ID of the shell tool call generated by the model. @@ -16630,7 +16516,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam`. public struct FunctionShellCallOutputItemParam: Codable, Hashable, Sendable { - public typealias String = Swift.String /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/id`. public var id: Swift.String? /// The unique ID of the shell tool call generated by the model. @@ -16655,7 +16540,6 @@ public enum Components { public typealias FunctionShellCallItemStatus = Components.Schemas.FunctionShellCallItemStatus /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/status`. public var status: Components.Schemas.FunctionShellCallItemStatus? - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/FunctionShellCallOutputItemParam/max_output_length`. public var maxOutputLength: Swift.Int? /// Creates a new `FunctionShellCallOutputItemParam`. @@ -16878,7 +16762,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallItemParam/type`. public var _type: Components.Schemas.ApplyPatchToolCallItemParam._TypePayload - public typealias String = Swift.String /// - 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. @@ -16943,7 +16826,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ApplyPatchToolCallOutputItemParam/type`. public var _type: Components.Schemas.ApplyPatchToolCallOutputItemParam._TypePayload - public typealias String = Swift.String /// - 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. @@ -17093,7 +16975,6 @@ public enum Components { /// /// - Remark: Generated from `#/components/schemas/ContextManagementParam/type`. public var _type: Swift.String - public typealias Int = Swift.Int /// - Remark: Generated from `#/components/schemas/ContextManagementParam/compact_threshold`. public var compactThreshold: Swift.Int? /// Creates a new `ContextManagementParam`. @@ -17142,3 +17023,4 @@ public enum Components { /// Types generated from the `#/components/headers` section of the OpenAPI document. public enum Headers {} } + From 900e01aec86f3dc3ac01256025bb631ec626b06a Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Sat, 23 May 2026 00:04:58 +0300 Subject: [PATCH 17/31] Make WebSearchActionSearch.query optional, regenerate Components query is deprecated and no longer sent by the API, causing keyNotFound decoding errors. Removed it from the required list in the spec. See https://github.com/openai/openai-openapi/issues/544. Co-Authored-By: Claude Sonnet 4.6 --- Makefile | 3 + .../Public/Schemas/Generated/Components.swift | 296 +++++++++--------- openapi.with-code-samples.yml | 1 - 3 files changed, 151 insertions(+), 149 deletions(-) diff --git a/Makefile b/Makefile index f70182cf..0d47e509 100644 --- a/Makefile +++ b/Makefile @@ -1,3 +1,6 @@ +# 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. 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 diff --git a/Sources/OpenAI/Public/Schemas/Generated/Components.swift b/Sources/OpenAI/Public/Schemas/Generated/Components.swift index 6b88d0b9..34c80c61 100644 --- a/Sources/OpenAI/Public/Schemas/Generated/Components.swift +++ b/Sources/OpenAI/Public/Schemas/Generated/Components.swift @@ -175,9 +175,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "CodeInterpreterOutputLogs", "#/components/schemas/CodeInterpreterOutputLogs": + case "CodeInterpreterOutputLogs", "#/components/schemas/CodeInterpreterOutputLogs", "logs": self = .codeInterpreterOutputLogs(try .init(from: decoder)) - case "CodeInterpreterOutputImage", "#/components/schemas/CodeInterpreterOutputImage": + case "CodeInterpreterOutputImage", "#/components/schemas/CodeInterpreterOutputImage", "image": self = .codeInterpreterOutputImage(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -449,7 +449,7 @@ public enum Components { forKey: ._type ) switch discriminator { - case "ComparisonFilter", "#/components/schemas/ComparisonFilter": + case "ComparisonFilter", "#/components/schemas/ComparisonFilter", "eq", "ne", "gt", "gte", "lt", "lte", "in", "nin": self = .comparisonFilter(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -536,23 +536,23 @@ public enum Components { forKey: ._type ) switch discriminator { - case "ClickParam", "#/components/schemas/ClickParam": + case "ClickParam", "#/components/schemas/ClickParam", "click": self = .clickParam(try .init(from: decoder)) - case "DoubleClickAction", "#/components/schemas/DoubleClickAction": + case "DoubleClickAction", "#/components/schemas/DoubleClickAction", "double_click": self = .doubleClickAction(try .init(from: decoder)) - case "DragParam", "#/components/schemas/DragParam": + case "DragParam", "#/components/schemas/DragParam", "drag": self = .dragParam(try .init(from: decoder)) - case "KeyPressAction", "#/components/schemas/KeyPressAction": + case "KeyPressAction", "#/components/schemas/KeyPressAction", "keypress": self = .keyPressAction(try .init(from: decoder)) - case "MoveParam", "#/components/schemas/MoveParam": + case "MoveParam", "#/components/schemas/MoveParam", "move": self = .moveParam(try .init(from: decoder)) - case "ScreenshotParam", "#/components/schemas/ScreenshotParam": + case "ScreenshotParam", "#/components/schemas/ScreenshotParam", "screenshot": self = .screenshotParam(try .init(from: decoder)) - case "ScrollParam", "#/components/schemas/ScrollParam": + case "ScrollParam", "#/components/schemas/ScrollParam", "scroll": self = .scrollParam(try .init(from: decoder)) - case "TypeParam", "#/components/schemas/TypeParam": + case "TypeParam", "#/components/schemas/TypeParam", "type": self = .typeParam(try .init(from: decoder)) - case "WaitParam", "#/components/schemas/WaitParam": + case "WaitParam", "#/components/schemas/WaitParam", "wait": self = .waitParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -1314,9 +1314,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "TranscriptTextUsageTokens", "#/components/schemas/TranscriptTextUsageTokens": + case "TranscriptTextUsageTokens", "#/components/schemas/TranscriptTextUsageTokens", "tokens": self = .transcriptTextUsageTokens(try .init(from: decoder)) - case "TranscriptTextUsageDuration", "#/components/schemas/TranscriptTextUsageDuration": + case "TranscriptTextUsageDuration", "#/components/schemas/TranscriptTextUsageDuration", "duration": self = .transcriptTextUsageDuration(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -2260,11 +2260,11 @@ public enum Components { forKey: ._type ) switch discriminator { - case "InputTextContent", "#/components/schemas/InputTextContent": + case "InputTextContent", "#/components/schemas/InputTextContent", "input_text": self = .inputTextContent(try .init(from: decoder)) - case "InputImageContent", "#/components/schemas/InputImageContent": + case "InputImageContent", "#/components/schemas/InputImageContent", "input_image": self = .inputImageContent(try .init(from: decoder)) - case "InputFileContent", "#/components/schemas/InputFileContent": + case "InputFileContent", "#/components/schemas/InputFileContent", "input_file": self = .inputFileContent(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -3006,11 +3006,11 @@ public enum Components { forKey: ._type ) switch discriminator { - case "InputTextContent", "#/components/schemas/InputTextContent": + case "InputTextContent", "#/components/schemas/InputTextContent", "input_text": self = .inputTextContent(try .init(from: decoder)) - case "InputImageContent", "#/components/schemas/InputImageContent": + case "InputImageContent", "#/components/schemas/InputImageContent", "input_image": self = .inputImageContent(try .init(from: decoder)) - case "InputFileContent", "#/components/schemas/InputFileContent": + case "InputFileContent", "#/components/schemas/InputFileContent", "input_file": self = .inputFileContent(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -3049,7 +3049,7 @@ public enum Components { forKey: ._type ) switch discriminator { - case "EasyInputMessage", "#/components/schemas/EasyInputMessage": + case "EasyInputMessage", "#/components/schemas/EasyInputMessage", "message": self = .easyInputMessage(try .init(from: decoder)) case "Item", "#/components/schemas/Item": self = .item(try .init(from: decoder)) @@ -3321,57 +3321,57 @@ public enum Components { forKey: ._type ) switch discriminator { - case "InputMessage", "#/components/schemas/InputMessage": + case "InputMessage", "#/components/schemas/InputMessage", "message": self = .inputMessage(try .init(from: decoder)) - case "OutputMessage", "#/components/schemas/OutputMessage": + case "OutputMessage", "#/components/schemas/OutputMessage", "message": self = .outputMessage(try .init(from: decoder)) - case "FileSearchToolCall", "#/components/schemas/FileSearchToolCall": + case "FileSearchToolCall", "#/components/schemas/FileSearchToolCall", "file_search_call": self = .fileSearchToolCall(try .init(from: decoder)) - case "ComputerToolCall", "#/components/schemas/ComputerToolCall": + case "ComputerToolCall", "#/components/schemas/ComputerToolCall", "computer_call": self = .computerToolCall(try .init(from: decoder)) - case "ComputerCallOutputItemParam", "#/components/schemas/ComputerCallOutputItemParam": + case "ComputerCallOutputItemParam", "#/components/schemas/ComputerCallOutputItemParam", "computer_call_output": self = .computerCallOutputItemParam(try .init(from: decoder)) - case "WebSearchToolCall", "#/components/schemas/WebSearchToolCall": + case "WebSearchToolCall", "#/components/schemas/WebSearchToolCall", "web_search_call": self = .webSearchToolCall(try .init(from: decoder)) - case "FunctionToolCall", "#/components/schemas/FunctionToolCall": + case "FunctionToolCall", "#/components/schemas/FunctionToolCall", "function_call": self = .functionToolCall(try .init(from: decoder)) - case "FunctionCallOutputItemParam", "#/components/schemas/FunctionCallOutputItemParam": + case "FunctionCallOutputItemParam", "#/components/schemas/FunctionCallOutputItemParam", "function_call_output": self = .functionCallOutputItemParam(try .init(from: decoder)) - case "ToolSearchCallItemParam", "#/components/schemas/ToolSearchCallItemParam": + case "ToolSearchCallItemParam", "#/components/schemas/ToolSearchCallItemParam", "tool_search_call": self = .toolSearchCallItemParam(try .init(from: decoder)) - case "ToolSearchOutputItemParam", "#/components/schemas/ToolSearchOutputItemParam": + case "ToolSearchOutputItemParam", "#/components/schemas/ToolSearchOutputItemParam", "tool_search_output": self = .toolSearchOutputItemParam(try .init(from: decoder)) - case "ReasoningItem", "#/components/schemas/ReasoningItem": + case "ReasoningItem", "#/components/schemas/ReasoningItem", "reasoning": self = .reasoningItem(try .init(from: decoder)) - case "CompactionSummaryItemParam", "#/components/schemas/CompactionSummaryItemParam": + case "CompactionSummaryItemParam", "#/components/schemas/CompactionSummaryItemParam", "compaction": self = .compactionSummaryItemParam(try .init(from: decoder)) - case "ImageGenToolCall", "#/components/schemas/ImageGenToolCall": + case "ImageGenToolCall", "#/components/schemas/ImageGenToolCall", "image_generation_call": self = .imageGenToolCall(try .init(from: decoder)) - case "CodeInterpreterToolCall", "#/components/schemas/CodeInterpreterToolCall": + case "CodeInterpreterToolCall", "#/components/schemas/CodeInterpreterToolCall", "code_interpreter_call": self = .codeInterpreterToolCall(try .init(from: decoder)) - case "LocalShellToolCall", "#/components/schemas/LocalShellToolCall": + case "LocalShellToolCall", "#/components/schemas/LocalShellToolCall", "local_shell_call": self = .localShellToolCall(try .init(from: decoder)) - case "LocalShellToolCallOutput", "#/components/schemas/LocalShellToolCallOutput": + case "LocalShellToolCallOutput", "#/components/schemas/LocalShellToolCallOutput", "local_shell_call_output": self = .localShellToolCallOutput(try .init(from: decoder)) - case "FunctionShellCallItemParam", "#/components/schemas/FunctionShellCallItemParam": + case "FunctionShellCallItemParam", "#/components/schemas/FunctionShellCallItemParam", "shell_call": self = .functionShellCallItemParam(try .init(from: decoder)) - case "FunctionShellCallOutputItemParam", "#/components/schemas/FunctionShellCallOutputItemParam": + case "FunctionShellCallOutputItemParam", "#/components/schemas/FunctionShellCallOutputItemParam", "shell_call_output": self = .functionShellCallOutputItemParam(try .init(from: decoder)) - case "ApplyPatchToolCallItemParam", "#/components/schemas/ApplyPatchToolCallItemParam": + case "ApplyPatchToolCallItemParam", "#/components/schemas/ApplyPatchToolCallItemParam", "apply_patch_call": self = .applyPatchToolCallItemParam(try .init(from: decoder)) - case "ApplyPatchToolCallOutputItemParam", "#/components/schemas/ApplyPatchToolCallOutputItemParam": + case "ApplyPatchToolCallOutputItemParam", "#/components/schemas/ApplyPatchToolCallOutputItemParam", "apply_patch_call_output": self = .applyPatchToolCallOutputItemParam(try .init(from: decoder)) - case "MCPListTools", "#/components/schemas/MCPListTools": + case "MCPListTools", "#/components/schemas/MCPListTools", "mcp_list_tools": self = .mcpListTools(try .init(from: decoder)) - case "MCPApprovalRequest", "#/components/schemas/MCPApprovalRequest": + case "MCPApprovalRequest", "#/components/schemas/MCPApprovalRequest", "mcp_approval_request": self = .mcpApprovalRequest(try .init(from: decoder)) - case "MCPApprovalResponse", "#/components/schemas/MCPApprovalResponse": + case "MCPApprovalResponse", "#/components/schemas/MCPApprovalResponse", "mcp_approval_response": self = .mcpApprovalResponse(try .init(from: decoder)) - case "MCPToolCall", "#/components/schemas/MCPToolCall": + case "MCPToolCall", "#/components/schemas/MCPToolCall", "mcp_call": self = .mcpToolCall(try .init(from: decoder)) - case "CustomToolCallOutput", "#/components/schemas/CustomToolCallOutput": + case "CustomToolCallOutput", "#/components/schemas/CustomToolCallOutput", "custom_tool_call_output": self = .customToolCallOutput(try .init(from: decoder)) - case "CustomToolCall", "#/components/schemas/CustomToolCall": + case "CustomToolCall", "#/components/schemas/CustomToolCall", "custom_tool_call": self = .customToolCall(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -3507,51 +3507,51 @@ public enum Components { switch discriminator { case "InputMessageResource", "#/components/schemas/InputMessageResource": self = .inputMessageResource(try .init(from: decoder)) - case "OutputMessage", "#/components/schemas/OutputMessage": + case "OutputMessage", "#/components/schemas/OutputMessage", "message": self = .outputMessage(try .init(from: decoder)) - case "FileSearchToolCall", "#/components/schemas/FileSearchToolCall": + case "FileSearchToolCall", "#/components/schemas/FileSearchToolCall", "file_search_call": self = .fileSearchToolCall(try .init(from: decoder)) - case "ComputerToolCall", "#/components/schemas/ComputerToolCall": + case "ComputerToolCall", "#/components/schemas/ComputerToolCall", "computer_call": self = .computerToolCall(try .init(from: decoder)) case "ComputerToolCallOutputResource", "#/components/schemas/ComputerToolCallOutputResource": self = .computerToolCallOutputResource(try .init(from: decoder)) - case "WebSearchToolCall", "#/components/schemas/WebSearchToolCall": + case "WebSearchToolCall", "#/components/schemas/WebSearchToolCall", "web_search_call": self = .webSearchToolCall(try .init(from: decoder)) case "FunctionToolCallResource", "#/components/schemas/FunctionToolCallResource": self = .functionToolCallResource(try .init(from: decoder)) case "FunctionToolCallOutputResource", "#/components/schemas/FunctionToolCallOutputResource": self = .functionToolCallOutputResource(try .init(from: decoder)) - case "ToolSearchCall", "#/components/schemas/ToolSearchCall": + case "ToolSearchCall", "#/components/schemas/ToolSearchCall", "tool_search_call": self = .toolSearchCall(try .init(from: decoder)) - case "ToolSearchOutput", "#/components/schemas/ToolSearchOutput": + case "ToolSearchOutput", "#/components/schemas/ToolSearchOutput", "tool_search_output": self = .toolSearchOutput(try .init(from: decoder)) - case "ReasoningItem", "#/components/schemas/ReasoningItem": + case "ReasoningItem", "#/components/schemas/ReasoningItem", "reasoning": self = .reasoningItem(try .init(from: decoder)) - case "CompactionBody", "#/components/schemas/CompactionBody": + case "CompactionBody", "#/components/schemas/CompactionBody", "compaction": self = .compactionBody(try .init(from: decoder)) - case "ImageGenToolCall", "#/components/schemas/ImageGenToolCall": + case "ImageGenToolCall", "#/components/schemas/ImageGenToolCall", "image_generation_call": self = .imageGenToolCall(try .init(from: decoder)) - case "CodeInterpreterToolCall", "#/components/schemas/CodeInterpreterToolCall": + case "CodeInterpreterToolCall", "#/components/schemas/CodeInterpreterToolCall", "code_interpreter_call": self = .codeInterpreterToolCall(try .init(from: decoder)) - case "LocalShellToolCall", "#/components/schemas/LocalShellToolCall": + case "LocalShellToolCall", "#/components/schemas/LocalShellToolCall", "local_shell_call": self = .localShellToolCall(try .init(from: decoder)) - case "LocalShellToolCallOutput", "#/components/schemas/LocalShellToolCallOutput": + case "LocalShellToolCallOutput", "#/components/schemas/LocalShellToolCallOutput", "local_shell_call_output": self = .localShellToolCallOutput(try .init(from: decoder)) - case "FunctionShellCall", "#/components/schemas/FunctionShellCall": + case "FunctionShellCall", "#/components/schemas/FunctionShellCall", "shell_call": self = .functionShellCall(try .init(from: decoder)) - case "FunctionShellCallOutput", "#/components/schemas/FunctionShellCallOutput": + case "FunctionShellCallOutput", "#/components/schemas/FunctionShellCallOutput", "shell_call_output": self = .functionShellCallOutput(try .init(from: decoder)) - case "ApplyPatchToolCall", "#/components/schemas/ApplyPatchToolCall": + case "ApplyPatchToolCall", "#/components/schemas/ApplyPatchToolCall", "apply_patch_call": self = .applyPatchToolCall(try .init(from: decoder)) - case "ApplyPatchToolCallOutput", "#/components/schemas/ApplyPatchToolCallOutput": + case "ApplyPatchToolCallOutput", "#/components/schemas/ApplyPatchToolCallOutput", "apply_patch_call_output": self = .applyPatchToolCallOutput(try .init(from: decoder)) - case "MCPListTools", "#/components/schemas/MCPListTools": + case "MCPListTools", "#/components/schemas/MCPListTools", "mcp_list_tools": self = .mcpListTools(try .init(from: decoder)) - case "MCPApprovalRequest", "#/components/schemas/MCPApprovalRequest": + case "MCPApprovalRequest", "#/components/schemas/MCPApprovalRequest", "mcp_approval_request": self = .mcpApprovalRequest(try .init(from: decoder)) - case "MCPApprovalResponseResource", "#/components/schemas/MCPApprovalResponseResource": + case "MCPApprovalResponseResource", "#/components/schemas/MCPApprovalResponseResource", "mcp_approval_response": self = .mcpApprovalResponseResource(try .init(from: decoder)) - case "MCPToolCall", "#/components/schemas/MCPToolCall": + case "MCPToolCall", "#/components/schemas/MCPToolCall", "mcp_call": self = .mcpToolCall(try .init(from: decoder)) case "CustomToolCallResource", "#/components/schemas/CustomToolCallResource": self = .customToolCallResource(try .init(from: decoder)) @@ -4833,11 +4833,11 @@ public enum Components { forKey: ._type ) switch discriminator { - case "OutputTextContent", "#/components/schemas/OutputTextContent": + case "OutputTextContent", "#/components/schemas/OutputTextContent", "output_text": self = .outputTextContent(try .init(from: decoder)) - case "RefusalContent", "#/components/schemas/RefusalContent": + case "RefusalContent", "#/components/schemas/RefusalContent", "refusal": self = .refusalContent(try .init(from: decoder)) - case "ReasoningTextContent", "#/components/schemas/ReasoningTextContent": + case "ReasoningTextContent", "#/components/schemas/ReasoningTextContent", "reasoning_text": self = .reasoningTextContent(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -4920,53 +4920,53 @@ public enum Components { forKey: ._type ) switch discriminator { - case "OutputMessage", "#/components/schemas/OutputMessage": + case "OutputMessage", "#/components/schemas/OutputMessage", "message": self = .outputMessage(try .init(from: decoder)) - case "FileSearchToolCall", "#/components/schemas/FileSearchToolCall": + case "FileSearchToolCall", "#/components/schemas/FileSearchToolCall", "file_search_call": self = .fileSearchToolCall(try .init(from: decoder)) - case "FunctionToolCall", "#/components/schemas/FunctionToolCall": + case "FunctionToolCall", "#/components/schemas/FunctionToolCall", "function_call": self = .functionToolCall(try .init(from: decoder)) case "FunctionToolCallOutputResource", "#/components/schemas/FunctionToolCallOutputResource": self = .functionToolCallOutputResource(try .init(from: decoder)) - case "WebSearchToolCall", "#/components/schemas/WebSearchToolCall": + case "WebSearchToolCall", "#/components/schemas/WebSearchToolCall", "web_search_call": self = .webSearchToolCall(try .init(from: decoder)) - case "ComputerToolCall", "#/components/schemas/ComputerToolCall": + case "ComputerToolCall", "#/components/schemas/ComputerToolCall", "computer_call": self = .computerToolCall(try .init(from: decoder)) case "ComputerToolCallOutputResource", "#/components/schemas/ComputerToolCallOutputResource": self = .computerToolCallOutputResource(try .init(from: decoder)) - case "ReasoningItem", "#/components/schemas/ReasoningItem": + case "ReasoningItem", "#/components/schemas/ReasoningItem", "reasoning": self = .reasoningItem(try .init(from: decoder)) - case "ToolSearchCall", "#/components/schemas/ToolSearchCall": + case "ToolSearchCall", "#/components/schemas/ToolSearchCall", "tool_search_call": self = .toolSearchCall(try .init(from: decoder)) - case "ToolSearchOutput", "#/components/schemas/ToolSearchOutput": + case "ToolSearchOutput", "#/components/schemas/ToolSearchOutput", "tool_search_output": self = .toolSearchOutput(try .init(from: decoder)) - case "CompactionBody", "#/components/schemas/CompactionBody": + case "CompactionBody", "#/components/schemas/CompactionBody", "compaction": self = .compactionBody(try .init(from: decoder)) - case "ImageGenToolCall", "#/components/schemas/ImageGenToolCall": + case "ImageGenToolCall", "#/components/schemas/ImageGenToolCall", "image_generation_call": self = .imageGenToolCall(try .init(from: decoder)) - case "CodeInterpreterToolCall", "#/components/schemas/CodeInterpreterToolCall": + case "CodeInterpreterToolCall", "#/components/schemas/CodeInterpreterToolCall", "code_interpreter_call": self = .codeInterpreterToolCall(try .init(from: decoder)) - case "LocalShellToolCall", "#/components/schemas/LocalShellToolCall": + case "LocalShellToolCall", "#/components/schemas/LocalShellToolCall", "local_shell_call": self = .localShellToolCall(try .init(from: decoder)) - case "LocalShellToolCallOutput", "#/components/schemas/LocalShellToolCallOutput": + case "LocalShellToolCallOutput", "#/components/schemas/LocalShellToolCallOutput", "local_shell_call_output": self = .localShellToolCallOutput(try .init(from: decoder)) - case "FunctionShellCall", "#/components/schemas/FunctionShellCall": + case "FunctionShellCall", "#/components/schemas/FunctionShellCall", "shell_call": self = .functionShellCall(try .init(from: decoder)) - case "FunctionShellCallOutput", "#/components/schemas/FunctionShellCallOutput": + case "FunctionShellCallOutput", "#/components/schemas/FunctionShellCallOutput", "shell_call_output": self = .functionShellCallOutput(try .init(from: decoder)) - case "ApplyPatchToolCall", "#/components/schemas/ApplyPatchToolCall": + case "ApplyPatchToolCall", "#/components/schemas/ApplyPatchToolCall", "apply_patch_call": self = .applyPatchToolCall(try .init(from: decoder)) - case "ApplyPatchToolCallOutput", "#/components/schemas/ApplyPatchToolCallOutput": + case "ApplyPatchToolCallOutput", "#/components/schemas/ApplyPatchToolCallOutput", "apply_patch_call_output": self = .applyPatchToolCallOutput(try .init(from: decoder)) - case "MCPToolCall", "#/components/schemas/MCPToolCall": + case "MCPToolCall", "#/components/schemas/MCPToolCall", "mcp_call": self = .mcpToolCall(try .init(from: decoder)) - case "MCPListTools", "#/components/schemas/MCPListTools": + case "MCPListTools", "#/components/schemas/MCPListTools", "mcp_list_tools": self = .mcpListTools(try .init(from: decoder)) - case "MCPApprovalRequest", "#/components/schemas/MCPApprovalRequest": + case "MCPApprovalRequest", "#/components/schemas/MCPApprovalRequest", "mcp_approval_request": self = .mcpApprovalRequest(try .init(from: decoder)) - case "MCPApprovalResponseResource", "#/components/schemas/MCPApprovalResponseResource": + case "MCPApprovalResponseResource", "#/components/schemas/MCPApprovalResponseResource", "mcp_approval_response": self = .mcpApprovalResponseResource(try .init(from: decoder)) - case "CustomToolCall", "#/components/schemas/CustomToolCall": + case "CustomToolCall", "#/components/schemas/CustomToolCall", "custom_tool_call": self = .customToolCall(try .init(from: decoder)) case "CustomToolCallOutputResource", "#/components/schemas/CustomToolCallOutputResource": self = .customToolCallOutputResource(try .init(from: decoder)) @@ -5141,9 +5141,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "OutputTextContent", "#/components/schemas/OutputTextContent": + case "OutputTextContent", "#/components/schemas/OutputTextContent", "output_text": self = .outputTextContent(try .init(from: decoder)) - case "RefusalContent", "#/components/schemas/RefusalContent": + case "RefusalContent", "#/components/schemas/RefusalContent", "refusal": self = .refusalContent(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -10241,35 +10241,35 @@ public enum Components { forKey: ._type ) switch discriminator { - case "FunctionTool", "#/components/schemas/FunctionTool": + case "FunctionTool", "#/components/schemas/FunctionTool", "function": self = .functionTool(try .init(from: decoder)) - case "FileSearchTool", "#/components/schemas/FileSearchTool": + case "FileSearchTool", "#/components/schemas/FileSearchTool", "file_search": self = .fileSearchTool(try .init(from: decoder)) - case "ComputerTool", "#/components/schemas/ComputerTool": + case "ComputerTool", "#/components/schemas/ComputerTool", "computer": self = .computerTool(try .init(from: decoder)) - case "ComputerUsePreviewTool", "#/components/schemas/ComputerUsePreviewTool": + case "ComputerUsePreviewTool", "#/components/schemas/ComputerUsePreviewTool", "computer_use_preview": self = .computerUsePreviewTool(try .init(from: decoder)) - case "WebSearchTool", "#/components/schemas/WebSearchTool": + case "WebSearchTool", "#/components/schemas/WebSearchTool", "web_search", "web_search_2025_08_26": self = .webSearchTool(try .init(from: decoder)) - case "MCPTool", "#/components/schemas/MCPTool": + case "MCPTool", "#/components/schemas/MCPTool", "mcp": self = .mcpTool(try .init(from: decoder)) - case "CodeInterpreterTool", "#/components/schemas/CodeInterpreterTool": + case "CodeInterpreterTool", "#/components/schemas/CodeInterpreterTool", "code_interpreter": self = .codeInterpreterTool(try .init(from: decoder)) - case "ImageGenTool", "#/components/schemas/ImageGenTool": + case "ImageGenTool", "#/components/schemas/ImageGenTool", "image_generation": self = .imageGenTool(try .init(from: decoder)) - case "LocalShellToolParam", "#/components/schemas/LocalShellToolParam": + case "LocalShellToolParam", "#/components/schemas/LocalShellToolParam", "local_shell": self = .localShellToolParam(try .init(from: decoder)) - case "FunctionShellToolParam", "#/components/schemas/FunctionShellToolParam": + case "FunctionShellToolParam", "#/components/schemas/FunctionShellToolParam", "shell": self = .functionShellToolParam(try .init(from: decoder)) - case "CustomToolParam", "#/components/schemas/CustomToolParam": + case "CustomToolParam", "#/components/schemas/CustomToolParam", "custom": self = .customToolParam(try .init(from: decoder)) - case "NamespaceToolParam", "#/components/schemas/NamespaceToolParam": + case "NamespaceToolParam", "#/components/schemas/NamespaceToolParam", "namespace": self = .namespaceToolParam(try .init(from: decoder)) - case "ToolSearchToolParam", "#/components/schemas/ToolSearchToolParam": + case "ToolSearchToolParam", "#/components/schemas/ToolSearchToolParam", "tool_search": self = .toolSearchToolParam(try .init(from: decoder)) - case "WebSearchPreviewTool", "#/components/schemas/WebSearchPreviewTool": + case "WebSearchPreviewTool", "#/components/schemas/WebSearchPreviewTool", "web_search_preview", "web_search_preview_2025_03_11": self = .webSearchPreviewTool(try .init(from: decoder)) - case "ApplyPatchToolParam", "#/components/schemas/ApplyPatchToolParam": + case "ApplyPatchToolParam", "#/components/schemas/ApplyPatchToolParam", "apply_patch": self = .applyPatchToolParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -11588,7 +11588,7 @@ public enum Components { /// /// /// - Remark: Generated from `#/components/schemas/WebSearchActionSearch/query`. - public var query: Swift.String + public var query: Swift.String? /// The search queries. /// /// @@ -11652,7 +11652,7 @@ public enum Components { /// - sources: The sources used in the search. public init( _type: Components.Schemas.WebSearchActionSearch._TypePayload, - query: Swift.String, + query: Swift.String? = nil, queries: [Swift.String]? = nil, sources: Components.Schemas.WebSearchActionSearch.SourcesPayload? = nil ) { @@ -11918,11 +11918,11 @@ public enum Components { forKey: ._type ) switch discriminator { - case "WebSearchActionSearch", "#/components/schemas/WebSearchActionSearch": + case "WebSearchActionSearch", "#/components/schemas/WebSearchActionSearch", "search": self = .webSearchActionSearch(try .init(from: decoder)) - case "WebSearchActionOpenPage", "#/components/schemas/WebSearchActionOpenPage": + case "WebSearchActionOpenPage", "#/components/schemas/WebSearchActionOpenPage", "open_page": self = .webSearchActionOpenPage(try .init(from: decoder)) - case "WebSearchActionFind", "#/components/schemas/WebSearchActionFind": + case "WebSearchActionFind", "#/components/schemas/WebSearchActionFind", "find_in_page": self = .webSearchActionFind(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -12466,13 +12466,13 @@ public enum Components { forKey: ._type ) switch discriminator { - case "FileCitationBody", "#/components/schemas/FileCitationBody": + case "FileCitationBody", "#/components/schemas/FileCitationBody", "file_citation": self = .fileCitationBody(try .init(from: decoder)) - case "UrlCitationBody", "#/components/schemas/UrlCitationBody": + case "UrlCitationBody", "#/components/schemas/UrlCitationBody", "url_citation": self = .urlCitationBody(try .init(from: decoder)) - case "ContainerFileCitationBody", "#/components/schemas/ContainerFileCitationBody": + case "ContainerFileCitationBody", "#/components/schemas/ContainerFileCitationBody", "container_file_citation": self = .containerFileCitationBody(try .init(from: decoder)) - case "FilePath", "#/components/schemas/FilePath": + case "FilePath", "#/components/schemas/FilePath", "file_path": self = .filePath(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -13776,9 +13776,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "ContainerNetworkPolicyDisabledParam", "#/components/schemas/ContainerNetworkPolicyDisabledParam": + case "ContainerNetworkPolicyDisabledParam", "#/components/schemas/ContainerNetworkPolicyDisabledParam", "disabled": self = .containerNetworkPolicyDisabledParam(try .init(from: decoder)) - case "ContainerNetworkPolicyAllowlistParam", "#/components/schemas/ContainerNetworkPolicyAllowlistParam": + case "ContainerNetworkPolicyAllowlistParam", "#/components/schemas/ContainerNetworkPolicyAllowlistParam", "allowlist": self = .containerNetworkPolicyAllowlistParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -13902,9 +13902,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "ContainerNetworkPolicyDisabledParam", "#/components/schemas/ContainerNetworkPolicyDisabledParam": + case "ContainerNetworkPolicyDisabledParam", "#/components/schemas/ContainerNetworkPolicyDisabledParam", "disabled": self = .containerNetworkPolicyDisabledParam(try .init(from: decoder)) - case "ContainerNetworkPolicyAllowlistParam", "#/components/schemas/ContainerNetworkPolicyAllowlistParam": + case "ContainerNetworkPolicyAllowlistParam", "#/components/schemas/ContainerNetworkPolicyAllowlistParam", "allowlist": self = .containerNetworkPolicyAllowlistParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -13943,9 +13943,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "SkillReferenceParam", "#/components/schemas/SkillReferenceParam": + case "SkillReferenceParam", "#/components/schemas/SkillReferenceParam", "skill_reference": self = .skillReferenceParam(try .init(from: decoder)) - case "InlineSkillParam", "#/components/schemas/InlineSkillParam": + case "InlineSkillParam", "#/components/schemas/InlineSkillParam", "inline": self = .inlineSkillParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -14134,11 +14134,11 @@ public enum Components { forKey: ._type ) switch discriminator { - case "ContainerAutoParam", "#/components/schemas/ContainerAutoParam": + case "ContainerAutoParam", "#/components/schemas/ContainerAutoParam", "container_auto": self = .containerAutoParam(try .init(from: decoder)) - case "LocalEnvironmentParam", "#/components/schemas/LocalEnvironmentParam": + case "LocalEnvironmentParam", "#/components/schemas/LocalEnvironmentParam", "local": self = .localEnvironmentParam(try .init(from: decoder)) - case "ContainerReferenceParam", "#/components/schemas/ContainerReferenceParam": + case "ContainerReferenceParam", "#/components/schemas/ContainerReferenceParam", "container_reference": self = .containerReferenceParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -14291,9 +14291,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "CustomTextFormatParam", "#/components/schemas/CustomTextFormatParam": + case "CustomTextFormatParam", "#/components/schemas/CustomTextFormatParam", "text": self = .customTextFormatParam(try .init(from: decoder)) - case "CustomGrammarFormatParam", "#/components/schemas/CustomGrammarFormatParam": + case "CustomGrammarFormatParam", "#/components/schemas/CustomGrammarFormatParam", "grammar": self = .customGrammarFormatParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -14446,9 +14446,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "FunctionToolParam", "#/components/schemas/FunctionToolParam": + case "FunctionToolParam", "#/components/schemas/FunctionToolParam", "function": self = .functionToolParam(try .init(from: decoder)) - case "CustomToolParam", "#/components/schemas/CustomToolParam": + case "CustomToolParam", "#/components/schemas/CustomToolParam", "custom": self = .customToolParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -15098,9 +15098,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "LocalEnvironmentResource", "#/components/schemas/LocalEnvironmentResource": + case "LocalEnvironmentResource", "#/components/schemas/LocalEnvironmentResource", "local": self = .localEnvironmentResource(try .init(from: decoder)) - case "ContainerReferenceResource", "#/components/schemas/ContainerReferenceResource": + case "ContainerReferenceResource", "#/components/schemas/ContainerReferenceResource", "container_reference": self = .containerReferenceResource(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -15258,9 +15258,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "FunctionShellCallOutputTimeoutOutcome", "#/components/schemas/FunctionShellCallOutputTimeoutOutcome": + case "FunctionShellCallOutputTimeoutOutcome", "#/components/schemas/FunctionShellCallOutputTimeoutOutcome", "timeout": self = .functionShellCallOutputTimeoutOutcome(try .init(from: decoder)) - case "FunctionShellCallOutputExitOutcome", "#/components/schemas/FunctionShellCallOutputExitOutcome": + case "FunctionShellCallOutputExitOutcome", "#/components/schemas/FunctionShellCallOutputExitOutcome", "exit": self = .functionShellCallOutputExitOutcome(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -15557,11 +15557,11 @@ public enum Components { forKey: ._type ) switch discriminator { - case "ApplyPatchCreateFileOperation", "#/components/schemas/ApplyPatchCreateFileOperation": + case "ApplyPatchCreateFileOperation", "#/components/schemas/ApplyPatchCreateFileOperation", "create_file": self = .applyPatchCreateFileOperation(try .init(from: decoder)) - case "ApplyPatchDeleteFileOperation", "#/components/schemas/ApplyPatchDeleteFileOperation": + case "ApplyPatchDeleteFileOperation", "#/components/schemas/ApplyPatchDeleteFileOperation", "delete_file": self = .applyPatchDeleteFileOperation(try .init(from: decoder)) - case "ApplyPatchUpdateFileOperation", "#/components/schemas/ApplyPatchUpdateFileOperation": + case "ApplyPatchUpdateFileOperation", "#/components/schemas/ApplyPatchUpdateFileOperation", "update_file": self = .applyPatchUpdateFileOperation(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -15971,11 +15971,11 @@ public enum Components { forKey: ._type ) switch discriminator { - case "InputTextContentParam", "#/components/schemas/InputTextContentParam": + case "InputTextContentParam", "#/components/schemas/InputTextContentParam", "input_text": self = .inputTextContentParam(try .init(from: decoder)) - case "InputImageContentParamAutoParam", "#/components/schemas/InputImageContentParamAutoParam": + case "InputImageContentParamAutoParam", "#/components/schemas/InputImageContentParamAutoParam", "input_image": self = .inputImageContentParamAutoParam(try .init(from: decoder)) - case "InputFileContentParam", "#/components/schemas/InputFileContentParam": + case "InputFileContentParam", "#/components/schemas/InputFileContentParam", "input_file": self = .inputFileContentParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -16320,9 +16320,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "LocalEnvironmentParam", "#/components/schemas/LocalEnvironmentParam": + case "LocalEnvironmentParam", "#/components/schemas/LocalEnvironmentParam", "local": self = .localEnvironmentParam(try .init(from: decoder)) - case "ContainerReferenceParam", "#/components/schemas/ContainerReferenceParam": + case "ContainerReferenceParam", "#/components/schemas/ContainerReferenceParam", "container_reference": self = .containerReferenceParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -16454,9 +16454,9 @@ public enum Components { forKey: ._type ) switch discriminator { - case "FunctionShellCallOutputTimeoutOutcomeParam", "#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam": + case "FunctionShellCallOutputTimeoutOutcomeParam", "#/components/schemas/FunctionShellCallOutputTimeoutOutcomeParam", "timeout": self = .functionShellCallOutputTimeoutOutcomeParam(try .init(from: decoder)) - case "FunctionShellCallOutputExitOutcomeParam", "#/components/schemas/FunctionShellCallOutputExitOutcomeParam": + case "FunctionShellCallOutputExitOutcomeParam", "#/components/schemas/FunctionShellCallOutputExitOutcomeParam", "exit": self = .functionShellCallOutputExitOutcomeParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( @@ -16723,11 +16723,11 @@ public enum Components { forKey: ._type ) switch discriminator { - case "ApplyPatchCreateFileOperationParam", "#/components/schemas/ApplyPatchCreateFileOperationParam": + case "ApplyPatchCreateFileOperationParam", "#/components/schemas/ApplyPatchCreateFileOperationParam", "create_file": self = .applyPatchCreateFileOperationParam(try .init(from: decoder)) - case "ApplyPatchDeleteFileOperationParam", "#/components/schemas/ApplyPatchDeleteFileOperationParam": + case "ApplyPatchDeleteFileOperationParam", "#/components/schemas/ApplyPatchDeleteFileOperationParam", "delete_file": self = .applyPatchDeleteFileOperationParam(try .init(from: decoder)) - case "ApplyPatchUpdateFileOperationParam", "#/components/schemas/ApplyPatchUpdateFileOperationParam": + case "ApplyPatchUpdateFileOperationParam", "#/components/schemas/ApplyPatchUpdateFileOperationParam", "update_file": self = .applyPatchUpdateFileOperationParam(try .init(from: decoder)) default: throw Swift.DecodingError.unknownOneOfDiscriminator( diff --git a/openapi.with-code-samples.yml b/openapi.with-code-samples.yml index b494033d..a7c35b9a 100644 --- a/openapi.with-code-samples.yml +++ b/openapi.with-code-samples.yml @@ -66728,7 +66728,6 @@ components: - url required: - type - - query WebSearchApproximateLocation: anyOf: - type: object From 92149603f2c49fc4e9534a08daf0f61dd231f91d Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Sat, 23 May 2026 00:36:52 +0300 Subject: [PATCH 18/31] Fix output_text.annotation.added event type, remove fixMappingError MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The stream event type was incorrectly mapped to the underscore variant in ModelResponseStreamEventType; corrected to match the spec value response.output_text.annotation.added. fixMappingError() was doing the opposite transformation (dot→underscore) before decoding, which broke decoding after the generated enum was updated to use the spec's dot-separated value. Removed the function along with its call site; getPayloadType() is retained as it serves an unrelated fallback purpose. Co-Authored-By: Claude Sonnet 4.6 --- Demo/Demo.xcodeproj/project.pbxproj | 2 ++ ...ModelResponseEventsStreamInterpreter.swift | 31 ++----------------- .../ModelResponseStreamEventType.swift | 2 +- 3 files changed, 6 insertions(+), 29 deletions(-) diff --git a/Demo/Demo.xcodeproj/project.pbxproj b/Demo/Demo.xcodeproj/project.pbxproj index 6a29e203..baf8dacf 100644 --- a/Demo/Demo.xcodeproj/project.pbxproj +++ b/Demo/Demo.xcodeproj/project.pbxproj @@ -315,6 +315,7 @@ GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = "Demo-Info.plist"; INFOPLIST_KEY_NSCameraUsageDescription = "Use camera to send media input to OpenAI"; + INFOPLIST_KEY_NSMicrophoneUsageDescription = "Exyte/Chat needs it for some reason"; INFOPLIST_KEY_NSPhotoLibraryUsageDescription = "Use media picker to send media input to OpenAI"; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; @@ -355,6 +356,7 @@ GENERATE_INFOPLIST_FILE = YES; INFOPLIST_FILE = "Demo-Info.plist"; INFOPLIST_KEY_NSCameraUsageDescription = "Use camera to send media input to OpenAI"; + INFOPLIST_KEY_NSMicrophoneUsageDescription = "Exyte/Chat needs it for some reason"; INFOPLIST_KEY_NSPhotoLibraryUsageDescription = "Use media picker to send media input to OpenAI"; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphoneos*]" = YES; "INFOPLIST_KEY_UIApplicationSceneManifest_Generation[sdk=iphonesimulator*]" = YES; diff --git a/Sources/OpenAI/Private/Streaming/ModelResponseEventsStreamInterpreter.swift b/Sources/OpenAI/Private/Streaming/ModelResponseEventsStreamInterpreter.swift index 3b472b97..5ceabe62 100644 --- a/Sources/OpenAI/Private/Streaming/ModelResponseEventsStreamInterpreter.swift +++ b/Sources/OpenAI/Private/Streaming/ModelResponseEventsStreamInterpreter.swift @@ -55,13 +55,12 @@ final class ModelResponseEventsStreamInterpreter: @unchecked Sendable, StreamInt } private func processEvent(_ event: ServerSentEventsStreamParser.Event) throws { - let finalEvent = event.fixMappingError() - var eventType = finalEvent.eventType + var eventType = event.eventType /// If the SSE `event` property is not specified by the provider service, our parser defaults it to "message" which is not a valid model response type. /// In this case we check the `data.type` property for a valid model response type. if eventType == "message" || eventType.isEmpty, - let payloadEventType = finalEvent.getPayloadType() { + let payloadEventType = event.getPayloadType() { eventType = payloadEventType } @@ -69,7 +68,7 @@ final class ModelResponseEventsStreamInterpreter: @unchecked Sendable, StreamInt throw InterpreterError.unknownEventType(eventType) } - let responseStreamEvent = try responseStreamEvent(modelResponseEventType: modelResponseEventType, data: finalEvent.data) + let responseStreamEvent = try responseStreamEvent(modelResponseEventType: modelResponseEventType, data: event.data) onEventDispatched?(responseStreamEvent) } @@ -211,30 +210,6 @@ final class ModelResponseEventsStreamInterpreter: @unchecked Sendable, StreamInt } private extension ServerSentEventsStreamParser.Event { - - // Remove when they have fixed (unified)! - // - // By looking at [API Reference](https://platform.openai.com/docs/api-reference/responses-streaming/response/output_text_annotation/added) - // and generated type `Schemas.ResponseOutputTextAnnotationAddedEvent` - // We can see that "output_text.annotation" is incorrect, whereas output_text_annotation is the correct one - func fixMappingError() -> Self { - let incorrectEventType = "response.output_text.annotation.added" - let correctEventType = "response.output_text_annotation.added" - - guard self.eventType == incorrectEventType || self.getPayloadType() == incorrectEventType else { - return self - } - - let fixedDataString = self.decodedData.replacingOccurrences(of: incorrectEventType, with: correctEventType) - return .init( - id: self.id, - data: fixedDataString.data(using: .utf8) ?? self.data, - decodedData: fixedDataString, - eventType: correctEventType, - retry: self.retry - ) - } - struct TypeEnvelope: Decodable { let type: String } func getPayloadType() -> String? { diff --git a/Sources/OpenAI/Private/Streaming/ModelResponseStreamEventType.swift b/Sources/OpenAI/Private/Streaming/ModelResponseStreamEventType.swift index cc7806a2..a20491e4 100644 --- a/Sources/OpenAI/Private/Streaming/ModelResponseStreamEventType.swift +++ b/Sources/OpenAI/Private/Streaming/ModelResponseStreamEventType.swift @@ -63,7 +63,7 @@ enum ModelResponseStreamEventType: String { case responseMcpListToolsFailed = "response.mcp_list_tools.failed" case responseMcpListToolsInProgress = "response.mcp_list_tools.in_progress" - case responseOutputTextAnnotationAdded = "response.output_text_annotation.added" + case responseOutputTextAnnotationAdded = "response.output_text.annotation.added" case responseReasoningDelta = "response.reasoning.delta" case responseReasoningDone = "response.reasoning.done" From dafa5799043ed52fb6594420f334ef9f995da6d7 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Sat, 23 May 2026 00:57:25 +0300 Subject: [PATCH 19/31] Make ResponseFunctionCallArgumentsDoneEvent.name optional, regenerate The API does not send name in response.function_call_arguments.done events, despite the spec marking it required. Removed it from required. See https://github.com/openai/openai-openapi/issues/545. Co-Authored-By: Claude Sonnet 4.6 --- Sources/OpenAI/Public/Schemas/Generated/Components.swift | 4 ++-- openapi.with-code-samples.yml | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/Sources/OpenAI/Public/Schemas/Generated/Components.swift b/Sources/OpenAI/Public/Schemas/Generated/Components.swift index 34c80c61..dc064a7f 100644 --- a/Sources/OpenAI/Public/Schemas/Generated/Components.swift +++ b/Sources/OpenAI/Public/Schemas/Generated/Components.swift @@ -6925,7 +6925,7 @@ public enum Components { /// The name of the function that was called. /// /// - Remark: Generated from `#/components/schemas/ResponseFunctionCallArgumentsDoneEvent/name`. - public var name: Swift.String + public var name: Swift.String? /// The index of the output item. /// /// - Remark: Generated from `#/components/schemas/ResponseFunctionCallArgumentsDoneEvent/output_index`. @@ -6950,7 +6950,7 @@ public enum Components { public init( _type: Components.Schemas.ResponseFunctionCallArgumentsDoneEvent._TypePayload, itemId: Swift.String, - name: Swift.String, + name: Swift.String? = nil, outputIndex: Swift.Int, sequenceNumber: Swift.Int, arguments: Swift.String diff --git a/openapi.with-code-samples.yml b/openapi.with-code-samples.yml index a7c35b9a..8ec4305b 100644 --- a/openapi.with-code-samples.yml +++ b/openapi.with-code-samples.yml @@ -60510,7 +60510,6 @@ components: required: - type - item_id - - name - output_index - arguments - sequence_number From b942e06aadc0b7f9dad8ee978d4a1b188e8db21a Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Wed, 3 Jun 2026 16:41:59 +0300 Subject: [PATCH 20/31] Rewrite ResponseStreamEvent decoding to dispatch on type field first Replaces the fragile try-catch chain with a type-first switch over ModelResponseStreamEventType, making every event type's handler explicit and compiler-enforced. Also removes the stale response.reasoning_summary.delta/done event types and the ReasoningSummaryEvent enum, which have no corresponding generated schema types and are absent from the current OpenAI API reference. Co-Authored-By: Claude Sonnet 4.6 --- Demo/DemoChat/Sources/ResponsesStore.swift | 8 - ...ModelResponseEventsStreamInterpreter.swift | 4 - .../ModelResponseStreamEventType.swift | 3 - .../Schemas/Facade/ResponseStreamEvent.swift | 307 +++++++----------- 4 files changed, 110 insertions(+), 212 deletions(-) diff --git a/Demo/DemoChat/Sources/ResponsesStore.swift b/Demo/DemoChat/Sources/ResponsesStore.swift index ad68db39..85f2acf8 100644 --- a/Demo/DemoChat/Sources/ResponsesStore.swift +++ b/Demo/DemoChat/Sources/ResponsesStore.swift @@ -583,14 +583,6 @@ public final class ResponsesStore: ObservableObject { case .done(let event): print("Reasoning done: \(event.sequenceNumber)") } - case .reasoningSummary(let reasoningSummaryEvent): - // Handle reasoning summary events - switch reasoningSummaryEvent { - case .delta(let event): - print("Reasoning summary delta: \(event.sequenceNumber)") - case .done(let event): - print("Reasoning summary done: \(event.sequenceNumber)") - } case .audio(_ /* let audioEvent */): // Audio events - not implemented yet print("Audio event received (not implemented)") diff --git a/Sources/OpenAI/Private/Streaming/ModelResponseEventsStreamInterpreter.swift b/Sources/OpenAI/Private/Streaming/ModelResponseEventsStreamInterpreter.swift index 5ceabe62..e6cd9b95 100644 --- a/Sources/OpenAI/Private/Streaming/ModelResponseEventsStreamInterpreter.swift +++ b/Sources/OpenAI/Private/Streaming/ModelResponseEventsStreamInterpreter.swift @@ -163,10 +163,6 @@ final class ModelResponseEventsStreamInterpreter: @unchecked Sendable, StreamInt .reasoning(.delta(try decode(data: data))) case .responseReasoningDone: .reasoning(.done(try decode(data: data))) - case .responseReasoningSummaryDelta: - .reasoningSummary(.delta(try decode(data: data))) - case .responseReasoningSummaryDone: - .reasoningSummary(.done(try decode(data: data))) case .responseOutputTextAnnotationAdded: .outputTextAnnotation(.added(try decode(data: data))) case .responseAudioDelta: diff --git a/Sources/OpenAI/Private/Streaming/ModelResponseStreamEventType.swift b/Sources/OpenAI/Private/Streaming/ModelResponseStreamEventType.swift index a20491e4..d21c9611 100644 --- a/Sources/OpenAI/Private/Streaming/ModelResponseStreamEventType.swift +++ b/Sources/OpenAI/Private/Streaming/ModelResponseStreamEventType.swift @@ -68,9 +68,6 @@ enum ModelResponseStreamEventType: String { case responseReasoningDelta = "response.reasoning.delta" case responseReasoningDone = "response.reasoning.done" - case responseReasoningSummaryDelta = "response.reasoning_summary.delta" - case responseReasoningSummaryDone = "response.reasoning_summary.done" - case error = "error" // The following events are not present in the API Reference at the moment, but they are in generated code, so we also include them just in case diff --git a/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift b/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift index 0033bcf1..9fdbcf66 100644 --- a/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift +++ b/Sources/OpenAI/Public/Schemas/Facade/ResponseStreamEvent.swift @@ -138,13 +138,6 @@ public enum ResponseStreamEvent: Codable, Equatable, Sendable { case done(Schemas.ResponseReasoningTextDoneEvent) } - public enum ReasoningSummaryEvent: Codable, Equatable, Sendable { - /// Emitted when a delta is added to a reasoning summary text. - case delta(Schemas.ResponseReasoningSummaryTextDeltaEvent) - /// Emitted when a reasoning summary text is completed. - case done(Schemas.ResponseReasoningSummaryTextDoneEvent) - } - public enum AudioEvent: Codable, Equatable, Sendable { case delta(Schemas.ResponseAudioDeltaEvent) case done(Schemas.ResponseAudioDoneEvent) @@ -199,204 +192,124 @@ public enum ResponseStreamEvent: Codable, Equatable, Sendable { case mcpListTools(MCPListToolsEvent) case outputTextAnnotation(OutputTextAnnotationEvent) case reasoning(ReasoningEvent) - case reasoningSummary(ReasoningSummaryEvent) enum ResponseStreamEventDecodingError: Error { case unknownEventType(String) - case unknownEvent(Components.Schemas.ResponseStreamEvent) - case unexpectedParsingCase } - + public init(from decoder: any Decoder) throws { - do { - // Decoding Response Event - let responseEvent = try ResponseEvent(from: decoder) - guard let responseEventType = ModelResponseStreamEventType(rawValue: responseEvent.type) else { - throw ResponseStreamEventDecodingError.unknownEventType(responseEvent.type) - } - - switch responseEventType { - case .responseCreated: - self = .created(responseEvent) - case .responseInProgress: - self = .inProgress(responseEvent) - case .responseCompleted: - self = .completed(responseEvent) - case .responseFailed: - self = .failed(responseEvent) - case .responseIncomplete: - self = .incomplete(responseEvent) - case .responseQueued: - self = .queued(responseEvent) - default: - throw ResponseStreamEventDecodingError.unknownEventType(responseEvent.type) - } - return - } catch { - // Do nothing, will try other coding types - } - - do { - // Decoding Output Item events - let outputItemAddedEvent = try ResponseOutputItemAddedEvent(from: decoder) - self = .outputItem(.added(outputItemAddedEvent)) - return - } catch { - // Do nothing, will try other coding types - } - - do { - // Decoding Output Item events - let outputItemDoneEvent = try ResponseOutputItemDoneEvent(from: decoder) - self = .outputItem(.done(outputItemDoneEvent)) - return - } catch { - // Do nothing, will try other coding types - } - - // Decoding MCPCallArgumentsEvent - // Once OPENAI fix the response issue, can put back below code to rawEvent - // else if let value = rawEvent.value40 { - // self = .mcpCallArguments(.delta(value)) - // } else if let value = rawEvent.value41 { - // self = .mcpCallArguments(.done(value)) - // } - do { - let mcpCallArgumentsEvent = try MCPCallArgumentsEvent(from: decoder) - switch mcpCallArgumentsEvent { - case .delta(let deltaEvent): - self = .mcpCallArguments(.delta(deltaEvent)) - case .done(let doneEvent): - self = .mcpCallArguments(.done(doneEvent)) - } - return - } catch { - // - } + struct TypeProbe: Decodable { let type: String } - // Decoding ResponseFunctionCallArgumentsDoneEvent via the locally - // extracted type so that `name` (missing from the generated schema) - // is preserved. - do { - let functionCallDoneEvent = try ResponseFunctionCallArgumentsDoneEvent(from: decoder) - self = .functionCallArguments(.done(functionCallDoneEvent)) - return - } catch { - // + let eventTypeString = try TypeProbe(from: decoder).type + guard let eventType = ModelResponseStreamEventType(rawValue: eventTypeString) else { + throw ResponseStreamEventDecodingError.unknownEventType(eventTypeString) } - let rawEvent = try Components.Schemas.ResponseStreamEvent(from: decoder) - if rawEvent.value10 != nil || rawEvent.value13 != nil || rawEvent.value20 != nil || rawEvent.value21 != nil, rawEvent.value22 != nil, rawEvent.value42 != nil, rawEvent.value43 != nil, rawEvent.value51 != nil { - // The following events are handled elsewhere by non-generated types - // (search "Decoding Response Event") - // - // `response.completed` - // `response.created` - // `response.inProgress` - // `response.failed` - // `response.incomplete` - // `response.queued` - // `response.response.mcp_call_arguments.delta` - // `response.mcp_call_arguments.done` - throw ResponseStreamEventDecodingError.unexpectedParsingCase - } else if rawEvent.value23 != nil || rawEvent.value24 != nil { - // The following events are handled elsewhere by non-generated types - // (search "Decoding Output Item events") - // - // `response.output_item.added` - // `response.output_item.done` - throw ResponseStreamEventDecodingError.unexpectedParsingCase - } else if let audioDelta = rawEvent.value1 { - self = .audio(.delta(audioDelta)) - } else if let value = rawEvent.value2 { - self = .audio(.done(value)) - } else if let value = rawEvent.value3 { - self = .audioTranscript(.delta(value)) - } else if let value = rawEvent.value4 { - self = .audioTranscript(.done(value)) - } else if let value = rawEvent.value5 { - self = .codeInterpreterCall(.code(.delta(value))) - } else if let value = rawEvent.value6 { - self = .codeInterpreterCall(.code(.done(value))) - } else if let value = rawEvent.value7 { - self = .codeInterpreterCall(.completed(value)) - } else if let value = rawEvent.value8 { - self = .codeInterpreterCall(.inProgress(value)) - } else if let value = rawEvent.value9 { - self = .codeInterpreterCall(.interpreting(value)) - } else if let value = rawEvent.value11 { - self = .contentPart(.added(value)) - } else if let value = rawEvent.value12 { - self = .contentPart(.done(value)) - } else if let value = rawEvent.value14 { - self = .error(value) - } else if let value = rawEvent.value15 { - self = .fileSearchCall(.completed(value)) - } else if let value = rawEvent.value16 { - self = .fileSearchCall(.inProgress(value)) - } else if let value = rawEvent.value17 { - self = .fileSearchCall(.searching(value)) - } else if let value = rawEvent.value18 { - self = .functionCallArguments(.delta(value)) - } else if let value = rawEvent.value19 { - self = .functionCallArguments(.done(.init( - _type: .response_functionCallArguments_done, - itemId: value.itemId, - outputIndex: value.outputIndex, - sequenceNumber: value.sequenceNumber, - arguments: value.arguments, - name: nil - ))) - } else if let value = rawEvent.value25 { - self = .reasoningSummaryPart(.added(value)) - } else if let value = rawEvent.value26 { - self = .reasoningSummaryPart(.done(value)) - } else if let value = rawEvent.value27 { - self = .reasoningSummaryText(.delta(value)) - } else if let value = rawEvent.value28 { - self = .reasoningSummaryText(.done(value)) - } else if let value = rawEvent.value29 { - self = .reasoning(.delta(value)) - } else if let value = rawEvent.value30 { - self = .reasoning(.done(value)) - } else if let value = rawEvent.value31 { - self = .refusal(.delta(value)) - } else if let value = rawEvent.value32 { - self = .refusal(.done(value)) - } else if let value = rawEvent.value33 { - self = .outputText(.delta(value)) - } else if let value = rawEvent.value34 { - self = .outputText(.done(value)) - } else if let value = rawEvent.value35 { - self = .webSearchCall(.completed(value)) - } else if let value = rawEvent.value36 { - self = .webSearchCall(.inProgress(value)) - } else if let value = rawEvent.value37 { - self = .webSearchCall(.searching(value)) - } else if let value = rawEvent.value38 { - self = .imageGenerationCall(.completed(value)) - } else if let value = rawEvent.value39 { - self = .imageGenerationCall(.generating(value)) - } else if let value = rawEvent.value40 { - self = .imageGenerationCall(.inProgress(value)) - } else if let value = rawEvent.value41 { - self = .imageGenerationCall(.partialImage(value)) - } else if let value = rawEvent.value44 { - self = .mcpCall(.completed(value)) - } else if let value = rawEvent.value45 { - self = .mcpCall(.failed(value)) - } else if let value = rawEvent.value46 { - self = .mcpCall(.inProgress(value)) - } else if let value = rawEvent.value47 { - self = .mcpListTools(.completed(value)) - } else if let value = rawEvent.value48 { - self = .mcpListTools(.failed(value)) - } else if let value = rawEvent.value49 { - self = .mcpListTools(.inProgress(value)) - } else if let value = rawEvent.value50 { - self = .outputTextAnnotation(.added(value)) - } else { - throw ResponseStreamEventDecodingError.unknownEvent(rawEvent) + switch eventType { + case .responseCreated: + self = .created(try ResponseEvent(from: decoder)) + case .responseInProgress: + self = .inProgress(try ResponseEvent(from: decoder)) + case .responseCompleted: + self = .completed(try ResponseEvent(from: decoder)) + case .responseFailed: + self = .failed(try ResponseEvent(from: decoder)) + case .responseIncomplete: + self = .incomplete(try ResponseEvent(from: decoder)) + case .responseQueued: + self = .queued(try ResponseEvent(from: decoder)) + case .responseOutputItemAdded: + self = .outputItem(.added(try ResponseOutputItemAddedEvent(from: decoder))) + case .responseOutputItemDone: + self = .outputItem(.done(try ResponseOutputItemDoneEvent(from: decoder))) + case .responseContentPartAdded: + self = .contentPart(.added(try Schemas.ResponseContentPartAddedEvent(from: decoder))) + case .responseContentPartDone: + self = .contentPart(.done(try Schemas.ResponseContentPartDoneEvent(from: decoder))) + case .responseOutputTextDelta: + self = .outputText(.delta(try Schemas.ResponseTextDeltaEvent(from: decoder))) + case .responseOutputTextDone: + self = .outputText(.done(try Schemas.ResponseTextDoneEvent(from: decoder))) + case .responseRefusalDelta: + self = .refusal(.delta(try Schemas.ResponseRefusalDeltaEvent(from: decoder))) + case .responseRefusalDone: + self = .refusal(.done(try Schemas.ResponseRefusalDoneEvent(from: decoder))) + case .responseFunctionCallArgumentsDelta: + self = .functionCallArguments(.delta(try Schemas.ResponseFunctionCallArgumentsDeltaEvent(from: decoder))) + case .responseFunctionCallArgumentsDone: + // Uses the locally extracted type to preserve `name` (missing from the generated schema). + self = .functionCallArguments(.done(try ResponseFunctionCallArgumentsDoneEvent(from: decoder))) + case .responseFileSearchCallInProgress: + self = .fileSearchCall(.inProgress(try Schemas.ResponseFileSearchCallInProgressEvent(from: decoder))) + case .responseFileSearchCallSearching: + self = .fileSearchCall(.searching(try Schemas.ResponseFileSearchCallSearchingEvent(from: decoder))) + case .responseFileSearchCallCompleted: + self = .fileSearchCall(.completed(try Schemas.ResponseFileSearchCallCompletedEvent(from: decoder))) + case .responseWebSearchCallInProgress: + self = .webSearchCall(.inProgress(try Schemas.ResponseWebSearchCallInProgressEvent(from: decoder))) + case .responseWebSearchCallSearching: + self = .webSearchCall(.searching(try Schemas.ResponseWebSearchCallSearchingEvent(from: decoder))) + case .responseWebSearchCallCompleted: + self = .webSearchCall(.completed(try Schemas.ResponseWebSearchCallCompletedEvent(from: decoder))) + case .responseReasoningSummaryPartAdded: + self = .reasoningSummaryPart(.added(try Schemas.ResponseReasoningSummaryPartAddedEvent(from: decoder))) + case .responseReasoningSummaryPartDone: + self = .reasoningSummaryPart(.done(try Schemas.ResponseReasoningSummaryPartDoneEvent(from: decoder))) + case .responseReasoningSummaryTextDelta: + self = .reasoningSummaryText(.delta(try Schemas.ResponseReasoningSummaryTextDeltaEvent(from: decoder))) + case .responseReasoningSummaryTextDone: + self = .reasoningSummaryText(.done(try Schemas.ResponseReasoningSummaryTextDoneEvent(from: decoder))) + case .responseImageGenerationCallCompleted: + self = .imageGenerationCall(.completed(try Schemas.ResponseImageGenCallCompletedEvent(from: decoder))) + case .responseImageGenerationCallGenerating: + self = .imageGenerationCall(.generating(try Schemas.ResponseImageGenCallGeneratingEvent(from: decoder))) + case .responseImageGenerationCallInProgress: + self = .imageGenerationCall(.inProgress(try Schemas.ResponseImageGenCallInProgressEvent(from: decoder))) + case .responseImageGenerationCallPartialImage: + self = .imageGenerationCall(.partialImage(try Schemas.ResponseImageGenCallPartialImageEvent(from: decoder))) + case .responseMcpCallArgumentsDelta: + // 😌(🤬) See ModelResponseStreamEventType.responseMcpCallArgumentsDelta for context. + self = .mcpCallArguments(.delta(try ResponseMCPCallArgumentsDeltaEvent(from: decoder))) + case .responseMcpCallArgumentsDone: + self = .mcpCallArguments(.done(try ResponseMCPCallArgumentsDoneEvent(from: decoder))) + case .responseMcpCallCompleted: + self = .mcpCall(.completed(try Schemas.ResponseMCPCallCompletedEvent(from: decoder))) + case .responseMcpCallFailed: + self = .mcpCall(.failed(try Schemas.ResponseMCPCallFailedEvent(from: decoder))) + case .responseMcpCallInProgress: + self = .mcpCall(.inProgress(try Schemas.ResponseMCPCallInProgressEvent(from: decoder))) + case .responseMcpListToolsCompleted: + self = .mcpListTools(.completed(try Schemas.ResponseMCPListToolsCompletedEvent(from: decoder))) + case .responseMcpListToolsFailed: + self = .mcpListTools(.failed(try Schemas.ResponseMCPListToolsFailedEvent(from: decoder))) + case .responseMcpListToolsInProgress: + self = .mcpListTools(.inProgress(try Schemas.ResponseMCPListToolsInProgressEvent(from: decoder))) + case .responseOutputTextAnnotationAdded: + self = .outputTextAnnotation(.added(try Schemas.ResponseOutputTextAnnotationAddedEvent(from: decoder))) + case .responseReasoningDelta: + self = .reasoning(.delta(try Schemas.ResponseReasoningTextDeltaEvent(from: decoder))) + case .responseReasoningDone: + self = .reasoning(.done(try Schemas.ResponseReasoningTextDoneEvent(from: decoder))) + case .error: + self = .error(try Schemas.ResponseErrorEvent(from: decoder)) + case .responseAudioDelta: + self = .audio(.delta(try Schemas.ResponseAudioDeltaEvent(from: decoder))) + case .responseAudioDone: + self = .audio(.done(try Schemas.ResponseAudioDoneEvent(from: decoder))) + case .responseAudioTranscriptDelta: + self = .audioTranscript(.delta(try Schemas.ResponseAudioTranscriptDeltaEvent(from: decoder))) + case .responseAudioTranscriptDone: + self = .audioTranscript(.done(try Schemas.ResponseAudioTranscriptDoneEvent(from: decoder))) + case .responseCodeInterpreterCallCodeDelta: + self = .codeInterpreterCall(.code(.delta(try Schemas.ResponseCodeInterpreterCallCodeDeltaEvent(from: decoder)))) + case .responseCodeInterpreterCallCodeDone: + self = .codeInterpreterCall(.code(.done(try Schemas.ResponseCodeInterpreterCallCodeDoneEvent(from: decoder)))) + case .responseCodeInterpreterCallInProgress: + self = .codeInterpreterCall(.inProgress(try Schemas.ResponseCodeInterpreterCallInProgressEvent(from: decoder))) + case .responseCodeInterpreterCallInterpreting: + self = .codeInterpreterCall(.interpreting(try Schemas.ResponseCodeInterpreterCallInterpretingEvent(from: decoder))) + case .responseCodeInterpreterCallCompleted: + self = .codeInterpreterCall(.completed(try Schemas.ResponseCodeInterpreterCallCompletedEvent(from: decoder))) } } } From 19ef09cc42872d86b82dcdc1121fdc5ef51c49c9 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Wed, 3 Jun 2026 21:30:42 +0300 Subject: [PATCH 21/31] Use type discriminator in Tool.init(from:) instead of trial-and-error Co-Authored-By: Claude Sonnet 4.6 --- Demo/DemoChat/Sources/ResponsesStore.swift | 2 + .../OpenAI/Public/Schemas/Edited/Tool.swift | 108 +++++------------- 2 files changed, 30 insertions(+), 80 deletions(-) diff --git a/Demo/DemoChat/Sources/ResponsesStore.swift b/Demo/DemoChat/Sources/ResponsesStore.swift index 85f2acf8..44e30762 100644 --- a/Demo/DemoChat/Sources/ResponsesStore.swift +++ b/Demo/DemoChat/Sources/ResponsesStore.swift @@ -484,6 +484,8 @@ public final class ResponsesStore: ObservableObject { chatMessage: message ) ) + case .functionToolCall(let functionToolCall): + lastFinishedFunctionToolCall = functionToolCall default: throw StoreError.unhandledOutputItem(output) } diff --git a/Sources/OpenAI/Public/Schemas/Edited/Tool.swift b/Sources/OpenAI/Public/Schemas/Edited/Tool.swift index 3eed40c4..ae3f3058 100644 --- a/Sources/OpenAI/Public/Schemas/Edited/Tool.swift +++ b/Sources/OpenAI/Public/Schemas/Edited/Tool.swift @@ -48,102 +48,50 @@ case applyPatchTool(Schemas.ApplyPatchToolParam) public init(from decoder: any Decoder) throws { - var errors: [any Error] = [] - do { + let container = try decoder.container(keyedBy: _TypeCodingKey.self) + let type = try container.decode(String.self, forKey: .type) + switch type { + case "file_search": self = .fileSearchTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "function": self = .functionTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "computer": self = .computerTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "computer_use_preview": self = .computerUsePreviewTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "web_search", "web_search_2025_08_26": self = .webSearchTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "web_search_preview", "web_search_preview_2025_03_11": self = .webSearchPreviewTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "mcp": self = .mcpTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "code_interpreter": self = .codeInterpreterTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "image_generation": self = .imageGenerationTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "local_shell": self = .localShellTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "shell": self = .functionShellTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "custom": self = .customTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "namespace": self = .namespaceTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "tool_search": self = .toolSearchTool(try .init(from: decoder)) - return - } catch { - errors.append(error) - } - do { + case "apply_patch": self = .applyPatchTool(try .init(from: decoder)) - return - } catch { - errors.append(error) + default: + throw DecodingError.dataCorruptedError( + forKey: .type, + in: container, + debugDescription: "Unknown tool type: \(type)" + ) } - throw Swift.DecodingError.failedToDecodeOneOfSchema( - type: Self.self, - codingPath: decoder.codingPath, - errors: errors - ) + } + + private enum _TypeCodingKey: String, CodingKey { + case type } public func encode(to encoder: any Encoder) throws { switch self { From cf910504bf85fc0be8e0981749453cfa703cc120 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Wed, 3 Jun 2026 22:58:36 +0300 Subject: [PATCH 22/31] Add tests for response.output_text.annotation.added event dispatch Co-Authored-By: Claude Sonnet 4.6 --- Tests/OpenAITests/MockServerSentEvent.swift | 9 +++ ...ResponseEventsStreamInterpreterTests.swift | 60 +++++++++++++++++++ 2 files changed, 69 insertions(+) diff --git a/Tests/OpenAITests/MockServerSentEvent.swift b/Tests/OpenAITests/MockServerSentEvent.swift index 67f3a7fd..c7e363ce 100644 --- a/Tests/OpenAITests/MockServerSentEvent.swift +++ b/Tests/OpenAITests/MockServerSentEvent.swift @@ -34,4 +34,13 @@ struct MockServerSentEvent { """ return "data: \(json)\n\n".data(using: .utf8)! } + + static func annotationAddedEvent(withExplicitEventField: Bool) -> Data { + let json = #"{"type":"response.output_text.annotation.added","item_id":"item_1","output_index":0,"content_index":0,"annotation_index":2,"sequence_number":5,"annotation":{}}"# + if withExplicitEventField { + return "event: response.output_text.annotation.added\ndata: \(json)\n\n".data(using: .utf8)! + } else { + return "data: \(json)\n\n".data(using: .utf8)! + } + } } diff --git a/Tests/OpenAITests/ModelResponseEventsStreamInterpreterTests.swift b/Tests/OpenAITests/ModelResponseEventsStreamInterpreterTests.swift index 37422ce1..0468587e 100644 --- a/Tests/OpenAITests/ModelResponseEventsStreamInterpreterTests.swift +++ b/Tests/OpenAITests/ModelResponseEventsStreamInterpreterTests.swift @@ -84,4 +84,64 @@ final class ModelResponseEventsStreamInterpreterTests: XCTestCase { XCTFail("Expected .outputText(.delta), got \(receivedEvent)") } } + + func testOutputTextAnnotationAdded_withExplicitEventField() async throws { + let expectation = XCTestExpectation(description: "outputTextAnnotation(.added) received via SSE event field") + var receivedEvent: ResponseStreamEvent? + + interpreter.setCallbackClosures { event in + Task { + await MainActor.run { + receivedEvent = event + expectation.fulfill() + } + } + } onError: { error in + XCTFail("Unexpected error: \(error)") + } + + interpreter.processData(MockServerSentEvent.annotationAddedEvent(withExplicitEventField: true)) + + await fulfillment(of: [expectation], timeout: 1.0) + + guard case .outputTextAnnotation(.added(let event)) = receivedEvent else { + XCTFail("Expected .outputTextAnnotation(.added), got \(String(describing: receivedEvent))") + return + } + XCTAssertEqual(event.itemId, "item_1") + XCTAssertEqual(event.outputIndex, 0) + XCTAssertEqual(event.contentIndex, 0) + XCTAssertEqual(event.annotationIndex, 2) + XCTAssertEqual(event.sequenceNumber, 5) + } + + func testOutputTextAnnotationAdded_withoutEventField_fallsBackToPayloadType() async throws { + let expectation = XCTestExpectation(description: "outputTextAnnotation(.added) received via data.type fallback") + var receivedEvent: ResponseStreamEvent? + + interpreter.setCallbackClosures { event in + Task { + await MainActor.run { + receivedEvent = event + expectation.fulfill() + } + } + } onError: { error in + XCTFail("Unexpected error: \(error)") + } + + interpreter.processData(MockServerSentEvent.annotationAddedEvent(withExplicitEventField: false)) + + await fulfillment(of: [expectation], timeout: 1.0) + + guard case .outputTextAnnotation(.added(let event)) = receivedEvent else { + XCTFail("Expected .outputTextAnnotation(.added), got \(String(describing: receivedEvent))") + return + } + XCTAssertEqual(event.itemId, "item_1") + XCTAssertEqual(event.outputIndex, 0) + XCTAssertEqual(event.contentIndex, 0) + XCTAssertEqual(event.annotationIndex, 2) + XCTAssertEqual(event.sequenceNumber, 5) + } } From ceb230af5533867c0e9823c84dc385f009a961aa Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Wed, 3 Jun 2026 23:11:59 +0300 Subject: [PATCH 23/31] Extract shared apply helpers to remove duplication in updateMessageBeingStreamed overloads Co-Authored-By: Claude Sonnet 4.6 --- Demo/DemoChat/Sources/ResponsesStore.swift | 26 ++++++++++++---------- 1 file changed, 14 insertions(+), 12 deletions(-) diff --git a/Demo/DemoChat/Sources/ResponsesStore.swift b/Demo/DemoChat/Sources/ResponsesStore.swift index 44e30762..68156094 100644 --- a/Demo/DemoChat/Sources/ResponsesStore.swift +++ b/Demo/DemoChat/Sources/ResponsesStore.swift @@ -770,13 +770,9 @@ public final class ResponsesStore: ObservableObject { ) throws { try updateMessageBeingStreamed(messageId: messageId) { message in switch outputContent { - case .outputTextContent(let outputText): - message.text = outputText.text - message.annotations = outputText.annotations - case .refusalContent(let refusal): - message.refusalText = refusal.refusal - case .reasoningTextContent: - break + case .outputTextContent(let c): Self.apply(c, to: message) + case .refusalContent(let c): Self.apply(c, to: message) + case .reasoningTextContent: break } } } @@ -787,14 +783,20 @@ public final class ResponsesStore: ObservableObject { ) throws { try updateMessageBeingStreamed(messageId: messageId) { message in switch outputContent { - case .outputTextContent(let outputText): - message.text = outputText.text - message.annotations = outputText.annotations - case .refusalContent(let refusal): - message.refusalText = refusal.refusal + case .outputTextContent(let c): Self.apply(c, to: message) + case .refusalContent(let c): Self.apply(c, to: message) } } } + + private static func apply(_ outputText: Components.Schemas.OutputTextContent, to message: MessageData) { + message.text = outputText.text + message.annotations = outputText.annotations + } + + private static func apply(_ refusal: Components.Schemas.RefusalContent, to message: MessageData) { + message.refusalText = refusal.refusal + } private func conversationTurn(withResponseData responseData: ResponseData, messageData: MessageData) -> ConversationTurn { .init( From b9b5bb0654bd00a8d4d7236ace89b33ffe8844d3 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Thu, 4 Jun 2026 13:34:11 +0300 Subject: [PATCH 24/31] Fix YAML indentation in openapi-generator-config.yaml Remove erroneous leading space from top-level keys and properly indent list items under paths: and schemas: so the config is unambiguously valid YAML. Co-Authored-By: Claude Sonnet 4.6 --- openapi-generator-config.yaml | 26 +++++++++++++------------- 1 file changed, 13 insertions(+), 13 deletions(-) diff --git a/openapi-generator-config.yaml b/openapi-generator-config.yaml index fdd5dfbf..3c0cefa8 100644 --- a/openapi-generator-config.yaml +++ b/openapi-generator-config.yaml @@ -1,13 +1,13 @@ - generate: - - types - namingStrategy: idiomatic - accessModifier: public - filter: - paths: - - /audio/transcriptions - - /responses - - /responses/{response_id} - - /responses/{response_id}/input_items - schemas: - - WebSearchLocation - - WebSearchContextSize +generate: + - types +namingStrategy: idiomatic +accessModifier: public +filter: + paths: + - /audio/transcriptions + - /responses + - /responses/{response_id} + - /responses/{response_id}/input_items + schemas: + - WebSearchLocation + - WebSearchContextSize From ae2f9290b7261b8cce4f82b4509d986bc9e76bb2 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Thu, 4 Jun 2026 13:36:26 +0300 Subject: [PATCH 25/31] Add argument count guard to extract_components.py Validate that exactly two arguments are passed before indexing sys.argv, so a missing argument produces a clear usage message instead of a bare IndexError. Co-Authored-By: Claude Sonnet 4.6 --- Scripts/extract_components.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Scripts/extract_components.py b/Scripts/extract_components.py index 8de2af79..e601384b 100644 --- a/Scripts/extract_components.py +++ b/Scripts/extract_components.py @@ -7,6 +7,10 @@ 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 From e00dcdeae9c17fea29263c8b2f15942182953496 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Thu, 4 Jun 2026 14:31:03 +0300 Subject: [PATCH 26/31] Align ResponseObject with current API spec - Make text and toolChoice optional (spec marks both as optional) - Change status from String to typed Status? (Schemas.Response.Value3Payload.StatusPayload), adding cancelled and queued to the documented values - Change truncation from String? to typed Truncation? (Schemas.ResponseProperties.TruncationPayload), update doc comment to match current spec wording - Add model doc comment explaining why it stays as non-optional String rather than the spec's optional ModelIdsResponses enum - Deprecate user field, pointing to safetyIdentifier and promptCacheKey - Add 11 missing fields: background, completedAt, conversation, maxToolCalls, outputText, prompt, promptCacheKey, promptCacheRetention, safetyIdentifier, serviceTier, topLogprobs Co-Authored-By: Claude Sonnet 4.6 --- .../Models/Responses API/ResponseObject.swift | 112 +++++++++++++----- 1 file changed, 81 insertions(+), 31 deletions(-) diff --git a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift index 98fda867..3b047960 100644 --- a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift +++ b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift @@ -13,115 +13,165 @@ public struct ResponseObject: Codable, Equatable, Sendable { public typealias Schemas = Components.Schemas public typealias ResponseProperties = Schemas.ResponseProperties public typealias IncompleteDetails = Schemas.Response.Value3Payload.IncompleteDetailsPayload? - + public typealias Status = Schemas.Response.Value3Payload.StatusPayload + public typealias Truncation = Schemas.ResponseProperties.TruncationPayload + public typealias PromptCacheRetention = Schemas.ModelResponseProperties.PromptCacheRetentionPayload + + /// Whether to run the model response in the background. + public let background: Bool? + + /// Unix timestamp (in seconds) of when this Response was completed. + public let completedAt: Double? + + /// The conversation associated with this response. + public let conversation: Schemas.Conversation2? + /// Unix timestamp (in seconds) of when this Response was created. public let createdAt: Int - + /// An error object returned when the model fails to generate a Response. public let error: Schemas.ResponseError? - + /// Unique identifier for this Response. public let id: String - + /// Details about why the response is incomplete. public let incompleteDetails: IncompleteDetails? - + /// Inserts a system (or developer) message as the first item in 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. public let instructions: String? - + /// An upper bound for the number of tokens that can be generated for a response, including visible output tokens and [reasoning tokens](https://platform.openai.com/docs/guides/reasoning). public let maxOutputTokens: Int? - + + /// The maximum number of tool calls that can be made during a model response. + public let maxToolCalls: Int? + /// Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a structured format, and querying for objects via API or the dashboard. /// /// Keys are strings with a maximum length of 64 characters. Values are strings with a maximum length of 512 characters. public let metadata: [String: String] - - /// Model ID used to generate the response, like `gpt-4o` or `o1`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare available models. + + /// Model ID used to generate the response, like `gpt-4o` or `o3`. OpenAI offers a wide range of models with different capabilities, performance characteristics, and price points. Refer to the [model guide](https://platform.openai.com/docs/models) to browse and compare available models. + /// + /// Typed as `String` rather than the spec's `ModelIdsResponses` enum because the API returns arbitrary model strings (including `ResponsesOnlyModel` variants) and an open-ended string avoids breaking changes as new models are added. public let model: String - + /// The object type of this resource - always set to `response`. public let object: String - + /// An array of content items generated by the model. /// * The length and order of items in the `output` array is dependent on the model's response. /// * Rather than accessing the first item in the `output` array and assuming it's an `assistant` message with the content generated by the model, you might consider using the `output_text` property where supported in SDKs. public let output: [OutputItem] - + + /// The concatenated text output from all `output_text` items in the `output` array, if any. + public let outputText: String? + /// Whether to allow the model to run tool calls in parallel. public let parallelToolCalls: Bool - + /// The unique ID of the previous response to the model. Use this to create multi-turn conversations. Learn more about [conversation state](https://platform.openai.com/docs/guides/conversation-state). public let previousResponseId: String? - + + /// The prompt template and its variables used to generate this response, if any. + public let prompt: Schemas.Prompt? + + /// Used by OpenAI to cache responses for similar requests to optimize your cache hit rates. Replaces the deprecated `user` field. [Learn more](https://platform.openai.com/docs/guides/prompt-caching). + public let promptCacheKey: String? + + /// The retention policy for the prompt cache. + public let promptCacheRetention: PromptCacheRetention? + /// **o-series models only** /// /// Configuration options for [reasoning models](https://platform.openai.com/docs/guides/reasoning). public let reasoning: Schemas.Reasoning? - - /// The status of the response generation. One of `completed`, `failed`, `in_progress`, or `incomplete`. - public let status: String - + + /// A stable identifier used to help detect users of your application that may be violating OpenAI's usage policies. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#safety-identifiers). + public let safetyIdentifier: String? + + /// Specifies the latency tier to use for processing the request. + public let serviceTier: Schemas.ServiceTier? + + /// The status of the response generation. One of `completed`, `failed`, `in_progress`, `cancelled`, `queued`, or `incomplete`. + public let status: Status? + /// 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. public let temperature: Double? - + /// Configuration options for a text response from the model. Can be plain text or structured JSON data. Learn more: /// - [Text inputs and outputs](https://platform.openai.com/docs/guides/text) /// - [Structured Outputs](https://platform.openai.com/docs/guides/structured-outputs) - public let text: Schemas.ResponseTextParam + public let text: Schemas.ResponseTextParam? /// How the model should select which tool (or tools) to use when generating a response. See the `tools` parameter to see how to specify which tools the model can call. - public let toolChoice: Schemas.ToolChoiceParam - + public let toolChoice: Schemas.ToolChoiceParam? + /// An array of tools the model may call while generating a response. You can specify which tool to use by setting the `tool_choice` parameter. /// /// The two categories of tools you can provide the model are: /// - **Built-in tools:** Tools that are provided by OpenAI that extend the model's capabilities, like [web search](https://platform.openai.com/docs/guides/tools-web-search) or [file search](https://platform.openai.com/docs/guides/tools-file-search). Learn more about [built-in tools](https://platform.openai.com/docs/guides/tools). /// - **Function calls (custom tools):** Functions that are defined by you, enabling the model to call your own code. Learn more about [function calling](https://platform.openai.com/docs/guides/function-calling). public let tools: [Tool] - + + /// The number of top log probabilities to return for each output token. + public let topLogprobs: Int? + /// 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. public let topP: Double? - + /// The truncation strategy to use for the model response. /// - /// - `auto`: If the context of this response and previous ones exceeds the model's context window size, the model will truncate the response to fit the context window by dropping input items in the middle of the conversation. - /// - `disabled (default)`: If a model response will exceed the context window size for a model, the request will fail with a 400 error. - public let truncation: String? - + /// - `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 a model response will exceed the context window size for a model, the request will fail with a 400 error. + public let truncation: Truncation? + /// Represents token usage details including input tokens, output tokens, a breakdown of output tokens, and the total tokens used. /// [The Response Object API Reference Page](https://platform.openai.com/docs/api-reference/responses/object) says that the type of the field is Object, aka non-optional /// But an example of [Streaming's response.created] shows that `usage` can be null. And a the moment we use this struct for both regulard and streaming replies. public let usage: Schemas.ResponseUsage? - - /// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). + + /// A stable identifier for your end-user. /// - /// API reference declares that it's type is non-optional string, but the example they provide shows that it can be null + /// API reference declares that it's type is non-optional string, but the example they provide shows that it can be null. + @available(*, deprecated, message: "Use safetyIdentifier or promptCacheKey instead.") public let user: String? private enum CodingKeys: String, CodingKey { + case background + case completedAt = "completed_at" + case conversation case createdAt = "created_at" case error case id case incompleteDetails = "incomplete_details" case instructions case maxOutputTokens = "max_output_tokens" + case maxToolCalls = "max_tool_calls" case metadata case model case object case output + case outputText = "output_text" case parallelToolCalls = "parallel_tool_calls" case previousResponseId = "previous_response_id" + case prompt + case promptCacheKey = "prompt_cache_key" + case promptCacheRetention = "prompt_cache_retention" case reasoning + case safetyIdentifier = "safety_identifier" + case serviceTier = "service_tier" case status case temperature case text case toolChoice = "tool_choice" case tools + case topLogprobs = "top_logprobs" case topP = "top_p" case truncation case usage From cacb5198463eda6996acd6db4ecc3ac6d23e2fa9 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Thu, 4 Jun 2026 19:14:04 +0300 Subject: [PATCH 27/31] Fix CI build failure: update tests for ResponseObject changes Add ResponseObject+Mock.swift with a makeMock(output:tools:status:) helper following the pattern of other mock extensions. Update ResponsesEndpointTests to use it, removing the inline memberwise init and the private makeResponse helper. Co-Authored-By: Claude Sonnet 4.6 --- .../Extensions/ResponseObject+Mock.swift | 51 ++++++++++++++ .../OpenAITests/ResponsesEndpointTests.swift | 66 ++----------------- 2 files changed, 57 insertions(+), 60 deletions(-) create mode 100644 Tests/OpenAITests/Extensions/ResponseObject+Mock.swift diff --git a/Tests/OpenAITests/Extensions/ResponseObject+Mock.swift b/Tests/OpenAITests/Extensions/ResponseObject+Mock.swift new file mode 100644 index 00000000..eb48e8c1 --- /dev/null +++ b/Tests/OpenAITests/Extensions/ResponseObject+Mock.swift @@ -0,0 +1,51 @@ +// +// ResponseObject+Mock.swift +// OpenAI +// + +import Foundation +@testable import OpenAI + +extension ResponseObject { + static func makeMock( + output: [OutputItem] = [], + tools: [Tool] = [], + status: Status? = .completed + ) -> ResponseObject { + .init( + background: nil, + completedAt: nil, + conversation: nil, + createdAt: 123, + error: nil, + id: "resp-1", + incompleteDetails: nil, + instructions: nil, + maxOutputTokens: nil, + maxToolCalls: nil, + metadata: [:], + model: "test-model", + object: "response", + output: output, + outputText: nil, + parallelToolCalls: false, + previousResponseId: nil, + prompt: nil, + promptCacheKey: nil, + promptCacheRetention: nil, + reasoning: nil, + safetyIdentifier: nil, + serviceTier: nil, + status: status, + temperature: nil, + text: .init(format: nil), + toolChoice: .ToolChoiceOptions(.auto), + tools: tools, + topLogprobs: nil, + topP: nil, + truncation: nil, + usage: nil, + user: nil + ) + } +} diff --git a/Tests/OpenAITests/ResponsesEndpointTests.swift b/Tests/OpenAITests/ResponsesEndpointTests.swift index 6ca04ae3..13515608 100644 --- a/Tests/OpenAITests/ResponsesEndpointTests.swift +++ b/Tests/OpenAITests/ResponsesEndpointTests.swift @@ -28,39 +28,14 @@ class ResponsesEndpointTests: XCTestCase { let task = DataTaskMock.successful(with: data) urlSession.dataTask = task } - + func testCreateResponse() async throws { - // Build the query let query = CreateModelResponseQuery( input: .textInput("Hello"), model: "test-model" ) - // Dummy response object - let dummy = ResponseObject( - createdAt: 123, - error: nil, - id: "resp-1", - incompleteDetails: nil, - instructions: nil, - maxOutputTokens: nil, - metadata: [:], - model: "test-model", - object: "response", - output: [], - parallelToolCalls: false, - previousResponseId: nil, - reasoning: nil, - status: "completed", - temperature: nil, - text: .init(format: nil), - toolChoice: .ToolChoiceOptions(.auto), - tools: [], - topP: nil, - truncation: nil, - usage: nil, - user: nil - ) + let dummy = ResponseObject.makeMock() try stub(dummy) let result = try await openAI.responses.createResponse(query: query) @@ -77,7 +52,6 @@ class ResponsesEndpointTests: XCTestCase { JSONSchemaField.properties(["foo": propSchema]), JSONSchemaField.required(["foo"]) ]) - // Create the function tool wrapper let functionTool = FunctionTool( type: "function", name: "my_function", @@ -87,15 +61,13 @@ class ResponsesEndpointTests: XCTestCase { ) let tool = Tool.functionTool(functionTool) - // Build the query let query = CreateModelResponseQuery( input: .textInput("Hello"), model: "test-model", tools: [tool] ) - // Dummy response object - let dummy = makeResponse(tools: [tool]) + let dummy = ResponseObject.makeMock(tools: [tool]) try stub(dummy) let result = try await openAI.responses.createResponse(query: query) @@ -105,44 +77,18 @@ class ResponsesEndpointTests: XCTestCase { XCTFail("Expected function.parameters to be object") return } - + let type = (jsonSchemaObject["type"]?.value as? String) XCTAssertEqual(type, "object") - + let properties = try XCTUnwrap(jsonSchemaObject["properties"]?.value as? JSONObject) let fooProperty = try XCTUnwrap(properties["foo"]?.value as? JSONObject) XCTAssertEqual(fooProperty["type"]?.value as? String, "string") - + let required = try XCTUnwrap(jsonSchemaObject["required"]?.value as? [AnyJSONDocument]) XCTAssertEqual(required.compactMap({ $0.value as? String }), ["foo"]) default: XCTFail("Expected tool in response to be a function") } } - private func makeResponse(output: [OutputItem] = [], tools: [Tool] = []) -> ResponseObject { - .init( - createdAt: 123, - error: nil, - id: "resp-1", - incompleteDetails: nil, - instructions: nil, - maxOutputTokens: nil, - metadata: [:], - model: "test-model", - object: "response", - output: output, - parallelToolCalls: false, - previousResponseId: nil, - reasoning: nil, - status: "completed", - temperature: nil, - text: .init(format: nil), - toolChoice: .ToolChoiceOptions(.auto), - tools: tools, - topP: nil, - truncation: nil, - usage: nil, - user: nil - ) - } } From b82a9386f4d7da889fa7a9fa713ef0dca257be01 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Thu, 4 Jun 2026 19:20:38 +0300 Subject: [PATCH 28/31] Change createdAt to Double to match API spec number type Co-Authored-By: Claude Sonnet 4.6 --- Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift index 3b047960..1d0f5a93 100644 --- a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift +++ b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift @@ -27,7 +27,7 @@ public struct ResponseObject: Codable, Equatable, Sendable { public let conversation: Schemas.Conversation2? /// Unix timestamp (in seconds) of when this Response was created. - public let createdAt: Int + public let createdAt: Double /// An error object returned when the model fails to generate a Response. public let error: Schemas.ResponseError? From 13a6bf511c49cac85722d9ca32334b222e461748 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Thu, 4 Jun 2026 19:28:12 +0300 Subject: [PATCH 29/31] Fix double-optional IncompleteDetails and add ResponseObject decoding tests Co-Authored-By: Claude Sonnet 4.6 --- .../Models/Responses API/ResponseObject.swift | 2 +- .../ResponseObjectCodingTests.swift | 82 +++++++++++++++++++ 2 files changed, 83 insertions(+), 1 deletion(-) create mode 100644 Tests/OpenAITests/ResponseObjectCodingTests.swift diff --git a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift index 1d0f5a93..b1ec3eb5 100644 --- a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift +++ b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift @@ -12,7 +12,7 @@ import OpenAPIRuntime public struct ResponseObject: Codable, Equatable, Sendable { public typealias Schemas = Components.Schemas public typealias ResponseProperties = Schemas.ResponseProperties - public typealias IncompleteDetails = Schemas.Response.Value3Payload.IncompleteDetailsPayload? + public typealias IncompleteDetails = Schemas.Response.Value3Payload.IncompleteDetailsPayload public typealias Status = Schemas.Response.Value3Payload.StatusPayload public typealias Truncation = Schemas.ResponseProperties.TruncationPayload public typealias PromptCacheRetention = Schemas.ModelResponseProperties.PromptCacheRetentionPayload diff --git a/Tests/OpenAITests/ResponseObjectCodingTests.swift b/Tests/OpenAITests/ResponseObjectCodingTests.swift new file mode 100644 index 00000000..87c9dbe5 --- /dev/null +++ b/Tests/OpenAITests/ResponseObjectCodingTests.swift @@ -0,0 +1,82 @@ +// +// ResponseObjectCodingTests.swift +// OpenAI +// + +import Testing +@testable import OpenAI +import Foundation + +struct ResponseObjectCodingTests { + private let minimalJSON = """ + { + "id": "resp-abc123", + "object": "response", + "model": "gpt-4o", + "created_at": 1717459200, + "output": [], + "tools": [], + "metadata": {}, + "parallel_tool_calls": false + } + """ + + @Test func decodeMinimalResponse() throws { + let response = try decode(minimalJSON) + #expect(response.id == "resp-abc123") + #expect(response.object == "response") + #expect(response.model == "gpt-4o") + #expect(response.output.isEmpty) + #expect(response.tools.isEmpty) + } + + @Test func decodeCreatedAtAsDouble() throws { + let response = try decode(minimalJSON) + #expect(response.createdAt == 1717459200.0) + } + + @Test func decodeIncompleteDetailsAbsent() throws { + let response = try decode(minimalJSON) + #expect(response.incompleteDetails == nil) + } + + @Test func decodeIncompleteDetailsNull() throws { + let json = """ + { + "id": "resp-abc123", + "object": "response", + "model": "gpt-4o", + "created_at": 1717459200, + "output": [], + "tools": [], + "metadata": {}, + "parallel_tool_calls": false, + "incomplete_details": null + } + """ + let response = try decode(json) + #expect(response.incompleteDetails == nil) + } + + @Test func decodeIncompleteDetailsPresent() throws { + let json = """ + { + "id": "resp-abc123", + "object": "response", + "model": "gpt-4o", + "created_at": 1717459200, + "output": [], + "tools": [], + "metadata": {}, + "parallel_tool_calls": false, + "incomplete_details": { "reason": "max_output_tokens" } + } + """ + let response = try decode(json) + #expect(response.incompleteDetails != nil) + } + + private func decode(_ json: String) throws -> ResponseObject { + try JSONDecoder().decode(ResponseObject.self, from: Data(json.utf8)) + } +} From c5b3b2bc5456ec2fd2ab5c339ddaafbb62cab760 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Thu, 4 Jun 2026 19:47:47 +0300 Subject: [PATCH 30/31] Fix usage doc comment: remove outdated rationale, spec now marks it optional Co-Authored-By: Claude Sonnet 4.6 --- Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift | 2 -- 1 file changed, 2 deletions(-) diff --git a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift index b1ec3eb5..454554b8 100644 --- a/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift +++ b/Sources/OpenAI/Public/Models/Responses API/ResponseObject.swift @@ -132,8 +132,6 @@ public struct ResponseObject: Codable, Equatable, Sendable { public let truncation: Truncation? /// Represents token usage details including input tokens, output tokens, a breakdown of output tokens, and the total tokens used. - /// [The Response Object API Reference Page](https://platform.openai.com/docs/api-reference/responses/object) says that the type of the field is Object, aka non-optional - /// But an example of [Streaming's response.created] shows that `usage` can be null. And a the moment we use this struct for both regulard and streaming replies. public let usage: Schemas.ResponseUsage? /// A stable identifier for your end-user. From 124eb1de959c647cc3e8e0f537a112cbe2c9ee98 Mon Sep 17 00:00:00 2001 From: nezhyborets Date: Thu, 4 Jun 2026 19:50:07 +0300 Subject: [PATCH 31/31] Use JSONSerialization in responseStreamEvent to safely escape string params Co-Authored-By: Claude Sonnet 4.6 --- Tests/OpenAITests/MockServerSentEvent.swift | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Tests/OpenAITests/MockServerSentEvent.swift b/Tests/OpenAITests/MockServerSentEvent.swift index c7e363ce..9a2c185d 100644 --- a/Tests/OpenAITests/MockServerSentEvent.swift +++ b/Tests/OpenAITests/MockServerSentEvent.swift @@ -29,10 +29,17 @@ struct MockServerSentEvent { delta: String = "", sequenceNumber: Int = 1 ) -> Data { - let json = """ - {"type":"\(payloadType)","output_index":\(outputIndex),"item_id":"\(itemId)","content_index":\(contentIndex),"delta":"\(delta)","sequence_number":\(sequenceNumber),"logprobs":[]} - """ - return "data: \(json)\n\n".data(using: .utf8)! + let payload: [String: Any] = [ + "type": payloadType, + "output_index": outputIndex, + "item_id": itemId, + "content_index": contentIndex, + "delta": delta, + "sequence_number": sequenceNumber, + "logprobs": [Any]() + ] + let jsonData = try! JSONSerialization.data(withJSONObject: payload) + return "data: \(String(data: jsonData, encoding: .utf8)!)\n\n".data(using: .utf8)! } static func annotationAddedEvent(withExplicitEventField: Bool) -> Data {