// File generated from our OpenAPI spec by Stainless.

package com.openai.models.responses

import com.fasterxml.jackson.annotation.JsonAnyGetter
import com.fasterxml.jackson.annotation.JsonAnySetter
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.ObjectCodec
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import com.fasterxml.jackson.databind.annotation.JsonSerialize
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import com.openai.core.BaseDeserializer
import com.openai.core.BaseSerializer
import com.openai.core.Enum
import com.openai.core.ExcludeMissing
import com.openai.core.JsonField
import com.openai.core.JsonMissing
import com.openai.core.JsonValue
import com.openai.core.allMaxBy
import com.openai.core.checkKnown
import com.openai.core.checkRequired
import com.openai.core.getOrThrow
import com.openai.core.toImmutable
import com.openai.core.toJsonString
import com.openai.errors.OpenAIInvalidDataException
import java.util.Collections
import java.util.Objects
import java.util.Optional
import kotlin.jvm.optionals.getOrNull

/**
 * 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.
 */
@JsonDeserialize(using = ResponseInputItem.Deserializer::class)
@JsonSerialize(using = ResponseInputItem.Serializer::class)
class ResponseInputItem
private constructor(
    private val easyInputMessage: EasyInputMessage? = null,
    private val message: Message? = null,
    private val responseOutputMessage: ResponseOutputMessage? = null,
    private val fileSearchCall: ResponseFileSearchToolCall? = null,
    private val computerCall: ResponseComputerToolCall? = null,
    private val computerCallOutput: ComputerCallOutput? = null,
    private val webSearchCall: ResponseFunctionWebSearch? = null,
    private val functionCall: ResponseFunctionToolCall? = null,
    private val functionCallOutput: FunctionCallOutput? = null,
    private val toolSearchCall: ToolSearchCall? = null,
    private val toolSearchOutput: ResponseToolSearchOutputItemParam? = null,
    private val additionalTools: AdditionalTools? = null,
    private val reasoning: ResponseReasoningItem? = null,
    private val compaction: ResponseCompactionItemParam? = null,
    private val imageGenerationCall: ImageGenerationCall? = null,
    private val codeInterpreterCall: ResponseCodeInterpreterToolCall? = null,
    private val localShellCall: LocalShellCall? = null,
    private val localShellCallOutput: LocalShellCallOutput? = null,
    private val shellCall: ShellCall? = null,
    private val shellCallOutput: ShellCallOutput? = null,
    private val applyPatchCall: ApplyPatchCall? = null,
    private val applyPatchCallOutput: ApplyPatchCallOutput? = null,
    private val mcpListTools: McpListTools? = null,
    private val mcpApprovalRequest: McpApprovalRequest? = null,
    private val mcpApprovalResponse: McpApprovalResponse? = null,
    private val mcpCall: McpCall? = null,
    private val customToolCallOutput: ResponseCustomToolCallOutput? = null,
    private val customToolCall: ResponseCustomToolCall? = null,
    private val compactionTrigger: JsonValue? = null,
    private val itemReference: ItemReference? = null,
    private val _json: JsonValue? = null,
) {

    /**
     * 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.
     */
    fun easyInputMessage(): Optional<EasyInputMessage> = Optional.ofNullable(easyInputMessage)

    /**
     * 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.
     */
    fun message(): Optional<Message> = Optional.ofNullable(message)

    /** An output message from the model. */
    fun responseOutputMessage(): Optional<ResponseOutputMessage> =
        Optional.ofNullable(responseOutputMessage)

    /**
     * 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.
     */
    fun fileSearchCall(): Optional<ResponseFileSearchToolCall> = Optional.ofNullable(fileSearchCall)

    /**
     * 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.
     */
    fun computerCall(): Optional<ResponseComputerToolCall> = Optional.ofNullable(computerCall)

    /** The output of a computer tool call. */
    fun computerCallOutput(): Optional<ComputerCallOutput> = Optional.ofNullable(computerCallOutput)

    /**
     * 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.
     */
    fun webSearchCall(): Optional<ResponseFunctionWebSearch> = Optional.ofNullable(webSearchCall)

    /**
     * A tool call to run a function. See the
     * [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more
     * information.
     */
    fun functionCall(): Optional<ResponseFunctionToolCall> = Optional.ofNullable(functionCall)

    /** The output of a function tool call. */
    fun functionCallOutput(): Optional<FunctionCallOutput> = Optional.ofNullable(functionCallOutput)

    fun toolSearchCall(): Optional<ToolSearchCall> = Optional.ofNullable(toolSearchCall)

    fun toolSearchOutput(): Optional<ResponseToolSearchOutputItemParam> =
        Optional.ofNullable(toolSearchOutput)

    fun additionalTools(): Optional<AdditionalTools> = Optional.ofNullable(additionalTools)

    /**
     * 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](https://platform.openai.com/docs/guides/conversation-state).
     */
    fun reasoning(): Optional<ResponseReasoningItem> = Optional.ofNullable(reasoning)

    /**
     * A compaction item generated by the
     * [`v1/responses/compact` API](https://platform.openai.com/docs/api-reference/responses/compact).
     */
    fun compaction(): Optional<ResponseCompactionItemParam> = Optional.ofNullable(compaction)

    /** An image generation request made by the model. */
    fun imageGenerationCall(): Optional<ImageGenerationCall> =
        Optional.ofNullable(imageGenerationCall)

    /** A tool call to run code. */
    fun codeInterpreterCall(): Optional<ResponseCodeInterpreterToolCall> =
        Optional.ofNullable(codeInterpreterCall)

    /** A tool call to run a command on the local shell. */
    fun localShellCall(): Optional<LocalShellCall> = Optional.ofNullable(localShellCall)

    /** The output of a local shell tool call. */
    fun localShellCallOutput(): Optional<LocalShellCallOutput> =
        Optional.ofNullable(localShellCallOutput)

    /** A tool representing a request to execute one or more shell commands. */
    fun shellCall(): Optional<ShellCall> = Optional.ofNullable(shellCall)

    /** The streamed output items emitted by a shell tool call. */
    fun shellCallOutput(): Optional<ShellCallOutput> = Optional.ofNullable(shellCallOutput)

    /** A tool call representing a request to create, delete, or update files using diff patches. */
    fun applyPatchCall(): Optional<ApplyPatchCall> = Optional.ofNullable(applyPatchCall)

    /** The streamed output emitted by an apply patch tool call. */
    fun applyPatchCallOutput(): Optional<ApplyPatchCallOutput> =
        Optional.ofNullable(applyPatchCallOutput)

    /** A list of tools available on an MCP server. */
    fun mcpListTools(): Optional<McpListTools> = Optional.ofNullable(mcpListTools)

    /** A request for human approval of a tool invocation. */
    fun mcpApprovalRequest(): Optional<McpApprovalRequest> = Optional.ofNullable(mcpApprovalRequest)

    /** A response to an MCP approval request. */
    fun mcpApprovalResponse(): Optional<McpApprovalResponse> =
        Optional.ofNullable(mcpApprovalResponse)

    /** An invocation of a tool on an MCP server. */
    fun mcpCall(): Optional<McpCall> = Optional.ofNullable(mcpCall)

    /** The output of a custom tool call from your code, being sent back to the model. */
    fun customToolCallOutput(): Optional<ResponseCustomToolCallOutput> =
        Optional.ofNullable(customToolCallOutput)

    /** A call to a custom tool created by the model. */
    fun customToolCall(): Optional<ResponseCustomToolCall> = Optional.ofNullable(customToolCall)

    /** Compacts the current context. Must be the final input item. */
    fun compactionTrigger(): Optional<JsonValue> = Optional.ofNullable(compactionTrigger)

    /** An internal identifier for an item to reference. */
    fun itemReference(): Optional<ItemReference> = Optional.ofNullable(itemReference)

    fun isEasyInputMessage(): Boolean = easyInputMessage != null

    fun isMessage(): Boolean = message != null

    fun isResponseOutputMessage(): Boolean = responseOutputMessage != null

    fun isFileSearchCall(): Boolean = fileSearchCall != null

    fun isComputerCall(): Boolean = computerCall != null

    fun isComputerCallOutput(): Boolean = computerCallOutput != null

    fun isWebSearchCall(): Boolean = webSearchCall != null

    fun isFunctionCall(): Boolean = functionCall != null

    fun isFunctionCallOutput(): Boolean = functionCallOutput != null

    fun isToolSearchCall(): Boolean = toolSearchCall != null

    fun isToolSearchOutput(): Boolean = toolSearchOutput != null

    fun isAdditionalTools(): Boolean = additionalTools != null

    fun isReasoning(): Boolean = reasoning != null

    fun isCompaction(): Boolean = compaction != null

    fun isImageGenerationCall(): Boolean = imageGenerationCall != null

    fun isCodeInterpreterCall(): Boolean = codeInterpreterCall != null

    fun isLocalShellCall(): Boolean = localShellCall != null

    fun isLocalShellCallOutput(): Boolean = localShellCallOutput != null

    fun isShellCall(): Boolean = shellCall != null

    fun isShellCallOutput(): Boolean = shellCallOutput != null

    fun isApplyPatchCall(): Boolean = applyPatchCall != null

    fun isApplyPatchCallOutput(): Boolean = applyPatchCallOutput != null

    fun isMcpListTools(): Boolean = mcpListTools != null

    fun isMcpApprovalRequest(): Boolean = mcpApprovalRequest != null

    fun isMcpApprovalResponse(): Boolean = mcpApprovalResponse != null

    fun isMcpCall(): Boolean = mcpCall != null

    fun isCustomToolCallOutput(): Boolean = customToolCallOutput != null

    fun isCustomToolCall(): Boolean = customToolCall != null

    fun isCompactionTrigger(): Boolean = compactionTrigger != null

    fun isItemReference(): Boolean = itemReference != null

    /**
     * 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.
     */
    fun asEasyInputMessage(): EasyInputMessage = easyInputMessage.getOrThrow("easyInputMessage")

    /**
     * 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.
     */
    fun asMessage(): Message = message.getOrThrow("message")

    /** An output message from the model. */
    fun asResponseOutputMessage(): ResponseOutputMessage =
        responseOutputMessage.getOrThrow("responseOutputMessage")

    /**
     * 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.
     */
    fun asFileSearchCall(): ResponseFileSearchToolCall = fileSearchCall.getOrThrow("fileSearchCall")

    /**
     * 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.
     */
    fun asComputerCall(): ResponseComputerToolCall = computerCall.getOrThrow("computerCall")

    /** The output of a computer tool call. */
    fun asComputerCallOutput(): ComputerCallOutput =
        computerCallOutput.getOrThrow("computerCallOutput")

    /**
     * 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.
     */
    fun asWebSearchCall(): ResponseFunctionWebSearch = webSearchCall.getOrThrow("webSearchCall")

    /**
     * A tool call to run a function. See the
     * [function calling guide](https://platform.openai.com/docs/guides/function-calling) for more
     * information.
     */
    fun asFunctionCall(): ResponseFunctionToolCall = functionCall.getOrThrow("functionCall")

    /** The output of a function tool call. */
    fun asFunctionCallOutput(): FunctionCallOutput =
        functionCallOutput.getOrThrow("functionCallOutput")

    fun asToolSearchCall(): ToolSearchCall = toolSearchCall.getOrThrow("toolSearchCall")

    fun asToolSearchOutput(): ResponseToolSearchOutputItemParam =
        toolSearchOutput.getOrThrow("toolSearchOutput")

    fun asAdditionalTools(): AdditionalTools = additionalTools.getOrThrow("additionalTools")

    /**
     * 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](https://platform.openai.com/docs/guides/conversation-state).
     */
    fun asReasoning(): ResponseReasoningItem = reasoning.getOrThrow("reasoning")

    /**
     * A compaction item generated by the
     * [`v1/responses/compact` API](https://platform.openai.com/docs/api-reference/responses/compact).
     */
    fun asCompaction(): ResponseCompactionItemParam = compaction.getOrThrow("compaction")

    /** An image generation request made by the model. */
    fun asImageGenerationCall(): ImageGenerationCall =
        imageGenerationCall.getOrThrow("imageGenerationCall")

    /** A tool call to run code. */
    fun asCodeInterpreterCall(): ResponseCodeInterpreterToolCall =
        codeInterpreterCall.getOrThrow("codeInterpreterCall")

    /** A tool call to run a command on the local shell. */
    fun asLocalShellCall(): LocalShellCall = localShellCall.getOrThrow("localShellCall")

    /** The output of a local shell tool call. */
    fun asLocalShellCallOutput(): LocalShellCallOutput =
        localShellCallOutput.getOrThrow("localShellCallOutput")

    /** A tool representing a request to execute one or more shell commands. */
    fun asShellCall(): ShellCall = shellCall.getOrThrow("shellCall")

    /** The streamed output items emitted by a shell tool call. */
    fun asShellCallOutput(): ShellCallOutput = shellCallOutput.getOrThrow("shellCallOutput")

    /** A tool call representing a request to create, delete, or update files using diff patches. */
    fun asApplyPatchCall(): ApplyPatchCall = applyPatchCall.getOrThrow("applyPatchCall")

    /** The streamed output emitted by an apply patch tool call. */
    fun asApplyPatchCallOutput(): ApplyPatchCallOutput =
        applyPatchCallOutput.getOrThrow("applyPatchCallOutput")

    /** A list of tools available on an MCP server. */
    fun asMcpListTools(): McpListTools = mcpListTools.getOrThrow("mcpListTools")

    /** A request for human approval of a tool invocation. */
    fun asMcpApprovalRequest(): McpApprovalRequest =
        mcpApprovalRequest.getOrThrow("mcpApprovalRequest")

    /** A response to an MCP approval request. */
    fun asMcpApprovalResponse(): McpApprovalResponse =
        mcpApprovalResponse.getOrThrow("mcpApprovalResponse")

    /** An invocation of a tool on an MCP server. */
    fun asMcpCall(): McpCall = mcpCall.getOrThrow("mcpCall")

    /** The output of a custom tool call from your code, being sent back to the model. */
    fun asCustomToolCallOutput(): ResponseCustomToolCallOutput =
        customToolCallOutput.getOrThrow("customToolCallOutput")

    /** A call to a custom tool created by the model. */
    fun asCustomToolCall(): ResponseCustomToolCall = customToolCall.getOrThrow("customToolCall")

    /** Compacts the current context. Must be the final input item. */
    fun asCompactionTrigger(): JsonValue = compactionTrigger.getOrThrow("compactionTrigger")

    /** An internal identifier for an item to reference. */
    fun asItemReference(): ItemReference = itemReference.getOrThrow("itemReference")

    fun _json(): Optional<JsonValue> = Optional.ofNullable(_json)

    /**
     * Maps this instance's current variant to a value of type [T] using the given [visitor].
     *
     * Note that this method is _not_ forwards compatible with new variants from the API, unless
     * [visitor] overrides [Visitor.unknown]. To handle variants not known to this version of the
     * SDK gracefully, consider overriding [Visitor.unknown]:
     * ```java
     * import com.openai.core.JsonValue;
     * import java.util.Optional;
     *
     * Optional<String> result = responseInputItem.accept(new ResponseInputItem.Visitor<Optional<String>>() {
     *     @Override
     *     public Optional<String> visitEasyInputMessage(EasyInputMessage easyInputMessage) {
     *         return Optional.of(easyInputMessage.toString());
     *     }
     *
     *     // ...
     *
     *     @Override
     *     public Optional<String> unknown(JsonValue json) {
     *         // Or inspect the `json`.
     *         return Optional.empty();
     *     }
     * });
     * ```
     *
     * @throws OpenAIInvalidDataException if [Visitor.unknown] is not overridden in [visitor] and
     *   the current variant is unknown.
     */
    fun <T> accept(visitor: Visitor<T>): T =
        when {
            easyInputMessage != null -> visitor.visitEasyInputMessage(easyInputMessage)
            message != null -> visitor.visitMessage(message)
            responseOutputMessage != null ->
                visitor.visitResponseOutputMessage(responseOutputMessage)
            fileSearchCall != null -> visitor.visitFileSearchCall(fileSearchCall)
            computerCall != null -> visitor.visitComputerCall(computerCall)
            computerCallOutput != null -> visitor.visitComputerCallOutput(computerCallOutput)
            webSearchCall != null -> visitor.visitWebSearchCall(webSearchCall)
            functionCall != null -> visitor.visitFunctionCall(functionCall)
            functionCallOutput != null -> visitor.visitFunctionCallOutput(functionCallOutput)
            toolSearchCall != null -> visitor.visitToolSearchCall(toolSearchCall)
            toolSearchOutput != null -> visitor.visitToolSearchOutput(toolSearchOutput)
            additionalTools != null -> visitor.visitAdditionalTools(additionalTools)
            reasoning != null -> visitor.visitReasoning(reasoning)
            compaction != null -> visitor.visitCompaction(compaction)
            imageGenerationCall != null -> visitor.visitImageGenerationCall(imageGenerationCall)
            codeInterpreterCall != null -> visitor.visitCodeInterpreterCall(codeInterpreterCall)
            localShellCall != null -> visitor.visitLocalShellCall(localShellCall)
            localShellCallOutput != null -> visitor.visitLocalShellCallOutput(localShellCallOutput)
            shellCall != null -> visitor.visitShellCall(shellCall)
            shellCallOutput != null -> visitor.visitShellCallOutput(shellCallOutput)
            applyPatchCall != null -> visitor.visitApplyPatchCall(applyPatchCall)
            applyPatchCallOutput != null -> visitor.visitApplyPatchCallOutput(applyPatchCallOutput)
            mcpListTools != null -> visitor.visitMcpListTools(mcpListTools)
            mcpApprovalRequest != null -> visitor.visitMcpApprovalRequest(mcpApprovalRequest)
            mcpApprovalResponse != null -> visitor.visitMcpApprovalResponse(mcpApprovalResponse)
            mcpCall != null -> visitor.visitMcpCall(mcpCall)
            customToolCallOutput != null -> visitor.visitCustomToolCallOutput(customToolCallOutput)
            customToolCall != null -> visitor.visitCustomToolCall(customToolCall)
            compactionTrigger != null -> visitor.visitCompactionTrigger(compactionTrigger)
            itemReference != null -> visitor.visitItemReference(itemReference)
            else -> visitor.unknown(_json)
        }

    private var validated: Boolean = false

    /**
     * Validates that the types of all values in this object match their expected types recursively.
     *
     * This method is _not_ forwards compatible with new types from the API for existing fields.
     *
     * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
     *   expected type.
     */
    fun validate(): ResponseInputItem = apply {
        if (validated) {
            return@apply
        }

        accept(
            object : Visitor<Unit> {
                override fun visitEasyInputMessage(easyInputMessage: EasyInputMessage) {
                    easyInputMessage.validate()
                }

                override fun visitMessage(message: Message) {
                    message.validate()
                }

                override fun visitResponseOutputMessage(
                    responseOutputMessage: ResponseOutputMessage
                ) {
                    responseOutputMessage.validate()
                }

                override fun visitFileSearchCall(fileSearchCall: ResponseFileSearchToolCall) {
                    fileSearchCall.validate()
                }

                override fun visitComputerCall(computerCall: ResponseComputerToolCall) {
                    computerCall.validate()
                }

                override fun visitComputerCallOutput(computerCallOutput: ComputerCallOutput) {
                    computerCallOutput.validate()
                }

                override fun visitWebSearchCall(webSearchCall: ResponseFunctionWebSearch) {
                    webSearchCall.validate()
                }

                override fun visitFunctionCall(functionCall: ResponseFunctionToolCall) {
                    functionCall.validate()
                }

                override fun visitFunctionCallOutput(functionCallOutput: FunctionCallOutput) {
                    functionCallOutput.validate()
                }

                override fun visitToolSearchCall(toolSearchCall: ToolSearchCall) {
                    toolSearchCall.validate()
                }

                override fun visitToolSearchOutput(
                    toolSearchOutput: ResponseToolSearchOutputItemParam
                ) {
                    toolSearchOutput.validate()
                }

                override fun visitAdditionalTools(additionalTools: AdditionalTools) {
                    additionalTools.validate()
                }

                override fun visitReasoning(reasoning: ResponseReasoningItem) {
                    reasoning.validate()
                }

                override fun visitCompaction(compaction: ResponseCompactionItemParam) {
                    compaction.validate()
                }

                override fun visitImageGenerationCall(imageGenerationCall: ImageGenerationCall) {
                    imageGenerationCall.validate()
                }

                override fun visitCodeInterpreterCall(
                    codeInterpreterCall: ResponseCodeInterpreterToolCall
                ) {
                    codeInterpreterCall.validate()
                }

                override fun visitLocalShellCall(localShellCall: LocalShellCall) {
                    localShellCall.validate()
                }

                override fun visitLocalShellCallOutput(localShellCallOutput: LocalShellCallOutput) {
                    localShellCallOutput.validate()
                }

                override fun visitShellCall(shellCall: ShellCall) {
                    shellCall.validate()
                }

                override fun visitShellCallOutput(shellCallOutput: ShellCallOutput) {
                    shellCallOutput.validate()
                }

                override fun visitApplyPatchCall(applyPatchCall: ApplyPatchCall) {
                    applyPatchCall.validate()
                }

                override fun visitApplyPatchCallOutput(applyPatchCallOutput: ApplyPatchCallOutput) {
                    applyPatchCallOutput.validate()
                }

                override fun visitMcpListTools(mcpListTools: McpListTools) {
                    mcpListTools.validate()
                }

                override fun visitMcpApprovalRequest(mcpApprovalRequest: McpApprovalRequest) {
                    mcpApprovalRequest.validate()
                }

                override fun visitMcpApprovalResponse(mcpApprovalResponse: McpApprovalResponse) {
                    mcpApprovalResponse.validate()
                }

                override fun visitMcpCall(mcpCall: McpCall) {
                    mcpCall.validate()
                }

                override fun visitCustomToolCallOutput(
                    customToolCallOutput: ResponseCustomToolCallOutput
                ) {
                    customToolCallOutput.validate()
                }

                override fun visitCustomToolCall(customToolCall: ResponseCustomToolCall) {
                    customToolCall.validate()
                }

                override fun visitCompactionTrigger(compactionTrigger: JsonValue) {
                    compactionTrigger.let {
                        if (it != JsonValue.from(mapOf("type" to "compaction_trigger"))) {
                            throw OpenAIInvalidDataException(
                                "'compactionTrigger' is invalid, received $it"
                            )
                        }
                    }
                }

                override fun visitItemReference(itemReference: ItemReference) {
                    itemReference.validate()
                }
            }
        )
        validated = true
    }

    fun isValid(): Boolean =
        try {
            validate()
            true
        } catch (e: OpenAIInvalidDataException) {
            false
        }

    /**
     * Returns a score indicating how many valid values are contained in this object recursively.
     *
     * Used for best match union deserialization.
     */
    @JvmSynthetic
    internal fun validity(): Int =
        accept(
            object : Visitor<Int> {
                override fun visitEasyInputMessage(easyInputMessage: EasyInputMessage) =
                    easyInputMessage.validity()

                override fun visitMessage(message: Message) = message.validity()

                override fun visitResponseOutputMessage(
                    responseOutputMessage: ResponseOutputMessage
                ) = responseOutputMessage.validity()

                override fun visitFileSearchCall(fileSearchCall: ResponseFileSearchToolCall) =
                    fileSearchCall.validity()

                override fun visitComputerCall(computerCall: ResponseComputerToolCall) =
                    computerCall.validity()

                override fun visitComputerCallOutput(computerCallOutput: ComputerCallOutput) =
                    computerCallOutput.validity()

                override fun visitWebSearchCall(webSearchCall: ResponseFunctionWebSearch) =
                    webSearchCall.validity()

                override fun visitFunctionCall(functionCall: ResponseFunctionToolCall) =
                    functionCall.validity()

                override fun visitFunctionCallOutput(functionCallOutput: FunctionCallOutput) =
                    functionCallOutput.validity()

                override fun visitToolSearchCall(toolSearchCall: ToolSearchCall) =
                    toolSearchCall.validity()

                override fun visitToolSearchOutput(
                    toolSearchOutput: ResponseToolSearchOutputItemParam
                ) = toolSearchOutput.validity()

                override fun visitAdditionalTools(additionalTools: AdditionalTools) =
                    additionalTools.validity()

                override fun visitReasoning(reasoning: ResponseReasoningItem) = reasoning.validity()

                override fun visitCompaction(compaction: ResponseCompactionItemParam) =
                    compaction.validity()

                override fun visitImageGenerationCall(imageGenerationCall: ImageGenerationCall) =
                    imageGenerationCall.validity()

                override fun visitCodeInterpreterCall(
                    codeInterpreterCall: ResponseCodeInterpreterToolCall
                ) = codeInterpreterCall.validity()

                override fun visitLocalShellCall(localShellCall: LocalShellCall) =
                    localShellCall.validity()

                override fun visitLocalShellCallOutput(localShellCallOutput: LocalShellCallOutput) =
                    localShellCallOutput.validity()

                override fun visitShellCall(shellCall: ShellCall) = shellCall.validity()

                override fun visitShellCallOutput(shellCallOutput: ShellCallOutput) =
                    shellCallOutput.validity()

                override fun visitApplyPatchCall(applyPatchCall: ApplyPatchCall) =
                    applyPatchCall.validity()

                override fun visitApplyPatchCallOutput(applyPatchCallOutput: ApplyPatchCallOutput) =
                    applyPatchCallOutput.validity()

                override fun visitMcpListTools(mcpListTools: McpListTools) = mcpListTools.validity()

                override fun visitMcpApprovalRequest(mcpApprovalRequest: McpApprovalRequest) =
                    mcpApprovalRequest.validity()

                override fun visitMcpApprovalResponse(mcpApprovalResponse: McpApprovalResponse) =
                    mcpApprovalResponse.validity()

                override fun visitMcpCall(mcpCall: McpCall) = mcpCall.validity()

                override fun visitCustomToolCallOutput(
                    customToolCallOutput: ResponseCustomToolCallOutput
                ) = customToolCallOutput.validity()

                override fun visitCustomToolCall(customToolCall: ResponseCustomToolCall) =
                    customToolCall.validity()

                override fun visitCompactionTrigger(compactionTrigger: JsonValue) =
                    compactionTrigger.let {
                        if (it == JsonValue.from(mapOf("type" to "compaction_trigger"))) 1 else 0
                    }

                override fun visitItemReference(itemReference: ItemReference) =
                    itemReference.validity()

                override fun unknown(json: JsonValue?) = 0
            }
        )

    override fun equals(other: Any?): Boolean {
        if (this === other) {
            return true
        }

        return other is ResponseInputItem &&
            easyInputMessage == other.easyInputMessage &&
            message == other.message &&
            responseOutputMessage == other.responseOutputMessage &&
            fileSearchCall == other.fileSearchCall &&
            computerCall == other.computerCall &&
            computerCallOutput == other.computerCallOutput &&
            webSearchCall == other.webSearchCall &&
            functionCall == other.functionCall &&
            functionCallOutput == other.functionCallOutput &&
            toolSearchCall == other.toolSearchCall &&
            toolSearchOutput == other.toolSearchOutput &&
            additionalTools == other.additionalTools &&
            reasoning == other.reasoning &&
            compaction == other.compaction &&
            imageGenerationCall == other.imageGenerationCall &&
            codeInterpreterCall == other.codeInterpreterCall &&
            localShellCall == other.localShellCall &&
            localShellCallOutput == other.localShellCallOutput &&
            shellCall == other.shellCall &&
            shellCallOutput == other.shellCallOutput &&
            applyPatchCall == other.applyPatchCall &&
            applyPatchCallOutput == other.applyPatchCallOutput &&
            mcpListTools == other.mcpListTools &&
            mcpApprovalRequest == other.mcpApprovalRequest &&
            mcpApprovalResponse == other.mcpApprovalResponse &&
            mcpCall == other.mcpCall &&
            customToolCallOutput == other.customToolCallOutput &&
            customToolCall == other.customToolCall &&
            compactionTrigger == other.compactionTrigger &&
            itemReference == other.itemReference
    }

    override fun hashCode(): Int =
        Objects.hash(
            easyInputMessage,
            message,
            responseOutputMessage,
            fileSearchCall,
            computerCall,
            computerCallOutput,
            webSearchCall,
            functionCall,
            functionCallOutput,
            toolSearchCall,
            toolSearchOutput,
            additionalTools,
            reasoning,
            compaction,
            imageGenerationCall,
            codeInterpreterCall,
            localShellCall,
            localShellCallOutput,
            shellCall,
            shellCallOutput,
            applyPatchCall,
            applyPatchCallOutput,
            mcpListTools,
            mcpApprovalRequest,
            mcpApprovalResponse,
            mcpCall,
            customToolCallOutput,
            customToolCall,
            compactionTrigger,
            itemReference,
        )

    override fun toString(): String =
        when {
            easyInputMessage != null -> "ResponseInputItem{easyInputMessage=$easyInputMessage}"
            message != null -> "ResponseInputItem{message=$message}"
            responseOutputMessage != null ->
                "ResponseInputItem{responseOutputMessage=$responseOutputMessage}"
            fileSearchCall != null -> "ResponseInputItem{fileSearchCall=$fileSearchCall}"
            computerCall != null -> "ResponseInputItem{computerCall=$computerCall}"
            computerCallOutput != null ->
                "ResponseInputItem{computerCallOutput=$computerCallOutput}"
            webSearchCall != null -> "ResponseInputItem{webSearchCall=$webSearchCall}"
            functionCall != null -> "ResponseInputItem{functionCall=$functionCall}"
            functionCallOutput != null ->
                "ResponseInputItem{functionCallOutput=$functionCallOutput}"
            toolSearchCall != null -> "ResponseInputItem{toolSearchCall=$toolSearchCall}"
            toolSearchOutput != null -> "ResponseInputItem{toolSearchOutput=$toolSearchOutput}"
            additionalTools != null -> "ResponseInputItem{additionalTools=$additionalTools}"
            reasoning != null -> "ResponseInputItem{reasoning=$reasoning}"
            compaction != null -> "ResponseInputItem{compaction=$compaction}"
            imageGenerationCall != null ->
                "ResponseInputItem{imageGenerationCall=$imageGenerationCall}"
            codeInterpreterCall != null ->
                "ResponseInputItem{codeInterpreterCall=$codeInterpreterCall}"
            localShellCall != null -> "ResponseInputItem{localShellCall=$localShellCall}"
            localShellCallOutput != null ->
                "ResponseInputItem{localShellCallOutput=$localShellCallOutput}"
            shellCall != null -> "ResponseInputItem{shellCall=$shellCall}"
            shellCallOutput != null -> "ResponseInputItem{shellCallOutput=$shellCallOutput}"
            applyPatchCall != null -> "ResponseInputItem{applyPatchCall=$applyPatchCall}"
            applyPatchCallOutput != null ->
                "ResponseInputItem{applyPatchCallOutput=$applyPatchCallOutput}"
            mcpListTools != null -> "ResponseInputItem{mcpListTools=$mcpListTools}"
            mcpApprovalRequest != null ->
                "ResponseInputItem{mcpApprovalRequest=$mcpApprovalRequest}"
            mcpApprovalResponse != null ->
                "ResponseInputItem{mcpApprovalResponse=$mcpApprovalResponse}"
            mcpCall != null -> "ResponseInputItem{mcpCall=$mcpCall}"
            customToolCallOutput != null ->
                "ResponseInputItem{customToolCallOutput=$customToolCallOutput}"
            customToolCall != null -> "ResponseInputItem{customToolCall=$customToolCall}"
            compactionTrigger != null -> "ResponseInputItem{compactionTrigger=$compactionTrigger}"
            itemReference != null -> "ResponseInputItem{itemReference=$itemReference}"
            _json != null -> "ResponseInputItem{_unknown=$_json}"
            else -> throw IllegalStateException("Invalid ResponseInputItem")
        }

    companion object {

        /**
         * 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.
         */
        @JvmStatic
        fun ofEasyInputMessage(easyInputMessage: EasyInputMessage) =
            ResponseInputItem(easyInputMessage = easyInputMessage)

        /**
         * 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.
         */
        @JvmStatic fun ofMessage(message: Message) = ResponseInputItem(message = message)

        /** An output message from the model. */
        @JvmStatic
        fun ofResponseOutputMessage(responseOutputMessage: ResponseOutputMessage) =
            ResponseInputItem(responseOutputMessage = responseOutputMessage)

        /**
         * 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.
         */
        @JvmStatic
        fun ofFileSearchCall(fileSearchCall: ResponseFileSearchToolCall) =
            ResponseInputItem(fileSearchCall = fileSearchCall)

        /**
         * 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.
         */
        @JvmStatic
        fun ofComputerCall(computerCall: ResponseComputerToolCall) =
            ResponseInputItem(computerCall = computerCall)

        /** The output of a computer tool call. */
        @JvmStatic
        fun ofComputerCallOutput(computerCallOutput: ComputerCallOutput) =
            ResponseInputItem(computerCallOutput = computerCallOutput)

        /**
         * 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.
         */
        @JvmStatic
        fun ofWebSearchCall(webSearchCall: ResponseFunctionWebSearch) =
            ResponseInputItem(webSearchCall = webSearchCall)

        /**
         * A tool call to run a function. See the
         * [function calling guide](https://platform.openai.com/docs/guides/function-calling) for
         * more information.
         */
        @JvmStatic
        fun ofFunctionCall(functionCall: ResponseFunctionToolCall) =
            ResponseInputItem(functionCall = functionCall)

        /** The output of a function tool call. */
        @JvmStatic
        fun ofFunctionCallOutput(functionCallOutput: FunctionCallOutput) =
            ResponseInputItem(functionCallOutput = functionCallOutput)

        @JvmStatic
        fun ofToolSearchCall(toolSearchCall: ToolSearchCall) =
            ResponseInputItem(toolSearchCall = toolSearchCall)

        @JvmStatic
        fun ofToolSearchOutput(toolSearchOutput: ResponseToolSearchOutputItemParam) =
            ResponseInputItem(toolSearchOutput = toolSearchOutput)

        @JvmStatic
        fun ofAdditionalTools(additionalTools: AdditionalTools) =
            ResponseInputItem(additionalTools = additionalTools)

        /**
         * 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](https://platform.openai.com/docs/guides/conversation-state).
         */
        @JvmStatic
        fun ofReasoning(reasoning: ResponseReasoningItem) = ResponseInputItem(reasoning = reasoning)

        /**
         * A compaction item generated by the
         * [`v1/responses/compact` API](https://platform.openai.com/docs/api-reference/responses/compact).
         */
        @JvmStatic
        fun ofCompaction(compaction: ResponseCompactionItemParam) =
            ResponseInputItem(compaction = compaction)

        /** An image generation request made by the model. */
        @JvmStatic
        fun ofImageGenerationCall(imageGenerationCall: ImageGenerationCall) =
            ResponseInputItem(imageGenerationCall = imageGenerationCall)

        /** A tool call to run code. */
        @JvmStatic
        fun ofCodeInterpreterCall(codeInterpreterCall: ResponseCodeInterpreterToolCall) =
            ResponseInputItem(codeInterpreterCall = codeInterpreterCall)

        /** A tool call to run a command on the local shell. */
        @JvmStatic
        fun ofLocalShellCall(localShellCall: LocalShellCall) =
            ResponseInputItem(localShellCall = localShellCall)

        /** The output of a local shell tool call. */
        @JvmStatic
        fun ofLocalShellCallOutput(localShellCallOutput: LocalShellCallOutput) =
            ResponseInputItem(localShellCallOutput = localShellCallOutput)

        /** A tool representing a request to execute one or more shell commands. */
        @JvmStatic fun ofShellCall(shellCall: ShellCall) = ResponseInputItem(shellCall = shellCall)

        /** The streamed output items emitted by a shell tool call. */
        @JvmStatic
        fun ofShellCallOutput(shellCallOutput: ShellCallOutput) =
            ResponseInputItem(shellCallOutput = shellCallOutput)

        /**
         * A tool call representing a request to create, delete, or update files using diff patches.
         */
        @JvmStatic
        fun ofApplyPatchCall(applyPatchCall: ApplyPatchCall) =
            ResponseInputItem(applyPatchCall = applyPatchCall)

        /** The streamed output emitted by an apply patch tool call. */
        @JvmStatic
        fun ofApplyPatchCallOutput(applyPatchCallOutput: ApplyPatchCallOutput) =
            ResponseInputItem(applyPatchCallOutput = applyPatchCallOutput)

        /** A list of tools available on an MCP server. */
        @JvmStatic
        fun ofMcpListTools(mcpListTools: McpListTools) =
            ResponseInputItem(mcpListTools = mcpListTools)

        /** A request for human approval of a tool invocation. */
        @JvmStatic
        fun ofMcpApprovalRequest(mcpApprovalRequest: McpApprovalRequest) =
            ResponseInputItem(mcpApprovalRequest = mcpApprovalRequest)

        /** A response to an MCP approval request. */
        @JvmStatic
        fun ofMcpApprovalResponse(mcpApprovalResponse: McpApprovalResponse) =
            ResponseInputItem(mcpApprovalResponse = mcpApprovalResponse)

        /** An invocation of a tool on an MCP server. */
        @JvmStatic fun ofMcpCall(mcpCall: McpCall) = ResponseInputItem(mcpCall = mcpCall)

        /** The output of a custom tool call from your code, being sent back to the model. */
        @JvmStatic
        fun ofCustomToolCallOutput(customToolCallOutput: ResponseCustomToolCallOutput) =
            ResponseInputItem(customToolCallOutput = customToolCallOutput)

        /** A call to a custom tool created by the model. */
        @JvmStatic
        fun ofCustomToolCall(customToolCall: ResponseCustomToolCall) =
            ResponseInputItem(customToolCall = customToolCall)

        /** Compacts the current context. Must be the final input item. */
        @JvmStatic
        fun ofCompactionTrigger() =
            ResponseInputItem(
                compactionTrigger = JsonValue.from(mapOf("type" to "compaction_trigger"))
            )

        /** An internal identifier for an item to reference. */
        @JvmStatic
        fun ofItemReference(itemReference: ItemReference) =
            ResponseInputItem(itemReference = itemReference)
    }

    /**
     * An interface that defines how to map each variant of [ResponseInputItem] to a value of type
     * [T].
     */
    interface Visitor<out T> {

        /**
         * 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.
         */
        fun visitEasyInputMessage(easyInputMessage: EasyInputMessage): T

        /**
         * 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.
         */
        fun visitMessage(message: Message): T

        /** An output message from the model. */
        fun visitResponseOutputMessage(responseOutputMessage: ResponseOutputMessage): T

        /**
         * 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.
         */
        fun visitFileSearchCall(fileSearchCall: ResponseFileSearchToolCall): T

        /**
         * 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.
         */
        fun visitComputerCall(computerCall: ResponseComputerToolCall): T

        /** The output of a computer tool call. */
        fun visitComputerCallOutput(computerCallOutput: ComputerCallOutput): T

        /**
         * 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.
         */
        fun visitWebSearchCall(webSearchCall: ResponseFunctionWebSearch): T

        /**
         * A tool call to run a function. See the
         * [function calling guide](https://platform.openai.com/docs/guides/function-calling) for
         * more information.
         */
        fun visitFunctionCall(functionCall: ResponseFunctionToolCall): T

        /** The output of a function tool call. */
        fun visitFunctionCallOutput(functionCallOutput: FunctionCallOutput): T

        fun visitToolSearchCall(toolSearchCall: ToolSearchCall): T

        fun visitToolSearchOutput(toolSearchOutput: ResponseToolSearchOutputItemParam): T

        fun visitAdditionalTools(additionalTools: AdditionalTools): T

        /**
         * 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](https://platform.openai.com/docs/guides/conversation-state).
         */
        fun visitReasoning(reasoning: ResponseReasoningItem): T

        /**
         * A compaction item generated by the
         * [`v1/responses/compact` API](https://platform.openai.com/docs/api-reference/responses/compact).
         */
        fun visitCompaction(compaction: ResponseCompactionItemParam): T

        /** An image generation request made by the model. */
        fun visitImageGenerationCall(imageGenerationCall: ImageGenerationCall): T

        /** A tool call to run code. */
        fun visitCodeInterpreterCall(codeInterpreterCall: ResponseCodeInterpreterToolCall): T

        /** A tool call to run a command on the local shell. */
        fun visitLocalShellCall(localShellCall: LocalShellCall): T

        /** The output of a local shell tool call. */
        fun visitLocalShellCallOutput(localShellCallOutput: LocalShellCallOutput): T

        /** A tool representing a request to execute one or more shell commands. */
        fun visitShellCall(shellCall: ShellCall): T

        /** The streamed output items emitted by a shell tool call. */
        fun visitShellCallOutput(shellCallOutput: ShellCallOutput): T

        /**
         * A tool call representing a request to create, delete, or update files using diff patches.
         */
        fun visitApplyPatchCall(applyPatchCall: ApplyPatchCall): T

        /** The streamed output emitted by an apply patch tool call. */
        fun visitApplyPatchCallOutput(applyPatchCallOutput: ApplyPatchCallOutput): T

        /** A list of tools available on an MCP server. */
        fun visitMcpListTools(mcpListTools: McpListTools): T

        /** A request for human approval of a tool invocation. */
        fun visitMcpApprovalRequest(mcpApprovalRequest: McpApprovalRequest): T

        /** A response to an MCP approval request. */
        fun visitMcpApprovalResponse(mcpApprovalResponse: McpApprovalResponse): T

        /** An invocation of a tool on an MCP server. */
        fun visitMcpCall(mcpCall: McpCall): T

        /** The output of a custom tool call from your code, being sent back to the model. */
        fun visitCustomToolCallOutput(customToolCallOutput: ResponseCustomToolCallOutput): T

        /** A call to a custom tool created by the model. */
        fun visitCustomToolCall(customToolCall: ResponseCustomToolCall): T

        /** Compacts the current context. Must be the final input item. */
        fun visitCompactionTrigger(compactionTrigger: JsonValue): T

        /** An internal identifier for an item to reference. */
        fun visitItemReference(itemReference: ItemReference): T

        /**
         * Maps an unknown variant of [ResponseInputItem] to a value of type [T].
         *
         * An instance of [ResponseInputItem] can contain an unknown variant if it was deserialized
         * from data that doesn't match any known variant. For example, if the SDK is on an older
         * version than the API, then the API may respond with new variants that the SDK is unaware
         * of.
         *
         * @throws OpenAIInvalidDataException in the default implementation.
         */
        fun unknown(json: JsonValue?): T {
            throw OpenAIInvalidDataException("Unknown ResponseInputItem: $json")
        }
    }

    internal class Deserializer : BaseDeserializer<ResponseInputItem>(ResponseInputItem::class) {

        override fun ObjectCodec.deserialize(node: JsonNode): ResponseInputItem {
            val json = JsonValue.fromJsonNode(node)
            val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull()

            when (type) {
                "message" -> {
                    val bestMatches =
                        sequenceOf(
                                tryDeserialize(node, jacksonTypeRef<EasyInputMessage>())?.let {
                                    ResponseInputItem(easyInputMessage = it, _json = json)
                                },
                                tryDeserialize(node, jacksonTypeRef<Message>())?.let {
                                    ResponseInputItem(message = it, _json = json)
                                },
                                tryDeserialize(node, jacksonTypeRef<ResponseOutputMessage>())?.let {
                                    ResponseInputItem(responseOutputMessage = it, _json = json)
                                },
                            )
                            .filterNotNull()
                            .allMaxBy { it.validity() }
                            .toList()
                    return when (bestMatches.size) {
                        // This can happen if what we're deserializing is completely incompatible
                        // with all the possible variants (e.g. deserializing from boolean).
                        0 -> ResponseInputItem(_json = json)
                        1 -> bestMatches.single()
                        // If there's more than one match with the highest validity, then use the
                        // first completely valid match, or simply the first match if none are
                        // completely valid.
                        else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first()
                    }
                }
                "file_search_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseFileSearchToolCall>())?.let {
                        ResponseInputItem(fileSearchCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "computer_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseComputerToolCall>())?.let {
                        ResponseInputItem(computerCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "computer_call_output" -> {
                    return tryDeserialize(node, jacksonTypeRef<ComputerCallOutput>())?.let {
                        ResponseInputItem(computerCallOutput = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "web_search_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseFunctionWebSearch>())?.let {
                        ResponseInputItem(webSearchCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "function_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseFunctionToolCall>())?.let {
                        ResponseInputItem(functionCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "function_call_output" -> {
                    return tryDeserialize(node, jacksonTypeRef<FunctionCallOutput>())?.let {
                        ResponseInputItem(functionCallOutput = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "tool_search_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ToolSearchCall>())?.let {
                        ResponseInputItem(toolSearchCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "tool_search_output" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseToolSearchOutputItemParam>())
                        ?.let { ResponseInputItem(toolSearchOutput = it, _json = json) }
                        ?: ResponseInputItem(_json = json)
                }
                "additional_tools" -> {
                    return tryDeserialize(node, jacksonTypeRef<AdditionalTools>())?.let {
                        ResponseInputItem(additionalTools = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "reasoning" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseReasoningItem>())?.let {
                        ResponseInputItem(reasoning = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "compaction" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseCompactionItemParam>())
                        ?.let { ResponseInputItem(compaction = it, _json = json) }
                        ?: ResponseInputItem(_json = json)
                }
                "image_generation_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ImageGenerationCall>())?.let {
                        ResponseInputItem(imageGenerationCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "code_interpreter_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseCodeInterpreterToolCall>())
                        ?.let { ResponseInputItem(codeInterpreterCall = it, _json = json) }
                        ?: ResponseInputItem(_json = json)
                }
                "local_shell_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<LocalShellCall>())?.let {
                        ResponseInputItem(localShellCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "local_shell_call_output" -> {
                    return tryDeserialize(node, jacksonTypeRef<LocalShellCallOutput>())?.let {
                        ResponseInputItem(localShellCallOutput = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "shell_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ShellCall>())?.let {
                        ResponseInputItem(shellCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "shell_call_output" -> {
                    return tryDeserialize(node, jacksonTypeRef<ShellCallOutput>())?.let {
                        ResponseInputItem(shellCallOutput = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "apply_patch_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ApplyPatchCall>())?.let {
                        ResponseInputItem(applyPatchCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "apply_patch_call_output" -> {
                    return tryDeserialize(node, jacksonTypeRef<ApplyPatchCallOutput>())?.let {
                        ResponseInputItem(applyPatchCallOutput = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "mcp_list_tools" -> {
                    return tryDeserialize(node, jacksonTypeRef<McpListTools>())?.let {
                        ResponseInputItem(mcpListTools = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "mcp_approval_request" -> {
                    return tryDeserialize(node, jacksonTypeRef<McpApprovalRequest>())?.let {
                        ResponseInputItem(mcpApprovalRequest = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "mcp_approval_response" -> {
                    return tryDeserialize(node, jacksonTypeRef<McpApprovalResponse>())?.let {
                        ResponseInputItem(mcpApprovalResponse = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "mcp_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<McpCall>())?.let {
                        ResponseInputItem(mcpCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "custom_tool_call_output" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseCustomToolCallOutput>())
                        ?.let { ResponseInputItem(customToolCallOutput = it, _json = json) }
                        ?: ResponseInputItem(_json = json)
                }
                "custom_tool_call" -> {
                    return tryDeserialize(node, jacksonTypeRef<ResponseCustomToolCall>())?.let {
                        ResponseInputItem(customToolCall = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
                "compaction_trigger" -> {
                    return tryDeserialize(node, jacksonTypeRef<JsonValue>())
                        ?.let { ResponseInputItem(compactionTrigger = it, _json = json) }
                        ?.takeIf { it.isValid() } ?: ResponseInputItem(_json = json)
                }
                "item_reference" -> {
                    return tryDeserialize(node, jacksonTypeRef<ItemReference>())?.let {
                        ResponseInputItem(itemReference = it, _json = json)
                    } ?: ResponseInputItem(_json = json)
                }
            }

            return ResponseInputItem(_json = json)
        }
    }

    internal class Serializer : BaseSerializer<ResponseInputItem>(ResponseInputItem::class) {

        override fun serialize(
            value: ResponseInputItem,
            generator: JsonGenerator,
            provider: SerializerProvider,
        ) {
            when {
                value.easyInputMessage != null -> generator.writeObject(value.easyInputMessage)
                value.message != null -> generator.writeObject(value.message)
                value.responseOutputMessage != null ->
                    generator.writeObject(value.responseOutputMessage)
                value.fileSearchCall != null -> generator.writeObject(value.fileSearchCall)
                value.computerCall != null -> generator.writeObject(value.computerCall)
                value.computerCallOutput != null -> generator.writeObject(value.computerCallOutput)
                value.webSearchCall != null -> generator.writeObject(value.webSearchCall)
                value.functionCall != null -> generator.writeObject(value.functionCall)
                value.functionCallOutput != null -> generator.writeObject(value.functionCallOutput)
                value.toolSearchCall != null -> generator.writeObject(value.toolSearchCall)
                value.toolSearchOutput != null -> generator.writeObject(value.toolSearchOutput)
                value.additionalTools != null -> generator.writeObject(value.additionalTools)
                value.reasoning != null -> generator.writeObject(value.reasoning)
                value.compaction != null -> generator.writeObject(value.compaction)
                value.imageGenerationCall != null ->
                    generator.writeObject(value.imageGenerationCall)
                value.codeInterpreterCall != null ->
                    generator.writeObject(value.codeInterpreterCall)
                value.localShellCall != null -> generator.writeObject(value.localShellCall)
                value.localShellCallOutput != null ->
                    generator.writeObject(value.localShellCallOutput)
                value.shellCall != null -> generator.writeObject(value.shellCall)
                value.shellCallOutput != null -> generator.writeObject(value.shellCallOutput)
                value.applyPatchCall != null -> generator.writeObject(value.applyPatchCall)
                value.applyPatchCallOutput != null ->
                    generator.writeObject(value.applyPatchCallOutput)
                value.mcpListTools != null -> generator.writeObject(value.mcpListTools)
                value.mcpApprovalRequest != null -> generator.writeObject(value.mcpApprovalRequest)
                value.mcpApprovalResponse != null ->
                    generator.writeObject(value.mcpApprovalResponse)
                value.mcpCall != null -> generator.writeObject(value.mcpCall)
                value.customToolCallOutput != null ->
                    generator.writeObject(value.customToolCallOutput)
                value.customToolCall != null -> generator.writeObject(value.customToolCall)
                value.compactionTrigger != null -> generator.writeObject(value.compactionTrigger)
                value.itemReference != null -> generator.writeObject(value.itemReference)
                value._json != null -> generator.writeObject(value._json)
                else -> throw IllegalStateException("Invalid ResponseInputItem")
            }
        }
    }

    /**
     * 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.
     */
    class Message
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val content: JsonField<List<ResponseInputContent>>,
        private val role: JsonField<Role>,
        private val status: JsonField<Status>,
        private val type: JsonField<Type>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("content")
            @ExcludeMissing
            content: JsonField<List<ResponseInputContent>> = JsonMissing.of(),
            @JsonProperty("role") @ExcludeMissing role: JsonField<Role> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonField<Type> = JsonMissing.of(),
        ) : this(content, role, status, type, mutableMapOf())

        /**
         * A list of one or many input items to the model, containing different content types.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun content(): List<ResponseInputContent> = content.getRequired("content")

        /**
         * The role of the message input. One of `user`, `system`, or `developer`.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun role(): Role = role.getRequired("role")

        /**
         * The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when
         * items are returned via API.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun status(): Optional<Status> = status.getOptional("status")

        /**
         * The type of the message input. Always set to `message`.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun type(): Optional<Type> = type.getOptional("type")

        /**
         * Returns the raw JSON value of [content].
         *
         * Unlike [content], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("content")
        @ExcludeMissing
        fun _content(): JsonField<List<ResponseInputContent>> = content

        /**
         * Returns the raw JSON value of [role].
         *
         * Unlike [role], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("role") @ExcludeMissing fun _role(): JsonField<Role> = role

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        /**
         * Returns the raw JSON value of [type].
         *
         * Unlike [type], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonField<Type> = type

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [Message].
             *
             * The following fields are required:
             * ```java
             * .content()
             * .role()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [Message]. */
        class Builder internal constructor() {

            private var content: JsonField<MutableList<ResponseInputContent>>? = null
            private var role: JsonField<Role>? = null
            private var status: JsonField<Status> = JsonMissing.of()
            private var type: JsonField<Type> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(message: Message) = apply {
                content = message.content.map { it.toMutableList() }
                role = message.role
                status = message.status
                type = message.type
                additionalProperties = message.additionalProperties.toMutableMap()
            }

            /**
             * A list of one or many input items to the model, containing different content types.
             */
            fun content(content: List<ResponseInputContent>) = content(JsonField.of(content))

            /**
             * Sets [Builder.content] to an arbitrary JSON value.
             *
             * You should usually call [Builder.content] with a well-typed
             * `List<ResponseInputContent>` value instead. This method is primarily for setting the
             * field to an undocumented or not yet supported value.
             */
            fun content(content: JsonField<List<ResponseInputContent>>) = apply {
                this.content = content.map { it.toMutableList() }
            }

            /**
             * Adds a single [ResponseInputContent] to [Builder.content].
             *
             * @throws IllegalStateException if the field was previously set to a non-list.
             */
            fun addContent(content: ResponseInputContent) = apply {
                this.content =
                    (this.content ?: JsonField.of(mutableListOf())).also {
                        checkKnown("content", it).add(content)
                    }
            }

            /**
             * Alias for calling [addContent] with `ResponseInputContent.ofInputText(inputText)`.
             */
            fun addContent(inputText: ResponseInputText) =
                addContent(ResponseInputContent.ofInputText(inputText))

            /**
             * Alias for calling [addContent] with the following:
             * ```java
             * ResponseInputText.builder()
             *     .text(text)
             *     .build()
             * ```
             */
            fun addInputTextContent(text: String) =
                addContent(ResponseInputText.builder().text(text).build())

            /**
             * Alias for calling [addContent] with `ResponseInputContent.ofInputImage(inputImage)`.
             */
            fun addContent(inputImage: ResponseInputImage) =
                addContent(ResponseInputContent.ofInputImage(inputImage))

            /**
             * Alias for calling [addContent] with the following:
             * ```java
             * ResponseInputImage.builder()
             *     .detail(detail)
             *     .build()
             * ```
             */
            fun addInputImageContent(detail: ResponseInputImage.Detail) =
                addContent(ResponseInputImage.builder().detail(detail).build())

            /**
             * Alias for calling [addContent] with `ResponseInputContent.ofInputFile(inputFile)`.
             */
            fun addContent(inputFile: ResponseInputFile) =
                addContent(ResponseInputContent.ofInputFile(inputFile))

            /** The role of the message input. One of `user`, `system`, or `developer`. */
            fun role(role: Role) = role(JsonField.of(role))

            /**
             * Sets [Builder.role] to an arbitrary JSON value.
             *
             * You should usually call [Builder.role] with a well-typed [Role] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun role(role: JsonField<Role>) = apply { this.role = role }

            /**
             * The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated
             * when items are returned via API.
             */
            fun status(status: Status) = status(JsonField.of(status))

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            /** The type of the message input. Always set to `message`. */
            fun type(type: Type) = type(JsonField.of(type))

            /**
             * Sets [Builder.type] to an arbitrary JSON value.
             *
             * You should usually call [Builder.type] with a well-typed [Type] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun type(type: JsonField<Type>) = apply { this.type = type }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [Message].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .content()
             * .role()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): Message =
                Message(
                    checkRequired("content", content).map { it.toImmutable() },
                    checkRequired("role", role),
                    status,
                    type,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): Message = apply {
            if (validated) {
                return@apply
            }

            content().forEach { it.validate() }
            role().validate()
            status().ifPresent { it.validate() }
            type().ifPresent { it.validate() }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (content.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) +
                (role.asKnown().getOrNull()?.validity() ?: 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0) +
                (type.asKnown().getOrNull()?.validity() ?: 0)

        /** The role of the message input. One of `user`, `system`, or `developer`. */
        class Role @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val USER = of("user")

                @JvmField val SYSTEM = of("system")

                @JvmField val DEVELOPER = of("developer")

                @JvmStatic fun of(value: String) = Role(JsonField.of(value))
            }

            /** An enum containing [Role]'s known values. */
            enum class Known {
                USER,
                SYSTEM,
                DEVELOPER,
            }

            /**
             * An enum containing [Role]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Role] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                USER,
                SYSTEM,
                DEVELOPER,
                /** An enum member indicating that [Role] was instantiated with an unknown value. */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    USER -> Value.USER
                    SYSTEM -> Value.SYSTEM
                    DEVELOPER -> Value.DEVELOPER
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    USER -> Known.USER
                    SYSTEM -> Known.SYSTEM
                    DEVELOPER -> Known.DEVELOPER
                    else -> throw OpenAIInvalidDataException("Unknown Role: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Role = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Role && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        /**
         * The status of item. One of `in_progress`, `completed`, or `incomplete`. Populated when
         * items are returned via API.
         */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val INCOMPLETE = of("incomplete")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    INCOMPLETE -> Value.INCOMPLETE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    INCOMPLETE -> Known.INCOMPLETE
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        /** The type of the message input. Always set to `message`. */
        class Type @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val MESSAGE = of("message")

                @JvmStatic fun of(value: String) = Type(JsonField.of(value))
            }

            /** An enum containing [Type]'s known values. */
            enum class Known {
                MESSAGE
            }

            /**
             * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Type] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                MESSAGE,
                /** An enum member indicating that [Type] was instantiated with an unknown value. */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    MESSAGE -> Value.MESSAGE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    MESSAGE -> Known.MESSAGE
                    else -> throw OpenAIInvalidDataException("Unknown Type: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Type = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Type && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is Message &&
                content == other.content &&
                role == other.role &&
                status == other.status &&
                type == other.type &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(content, role, status, type, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "Message{content=$content, role=$role, status=$status, type=$type, additionalProperties=$additionalProperties}"
    }

    /** The output of a computer tool call. */
    class ComputerCallOutput
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val callId: JsonField<String>,
        private val output: JsonField<ResponseComputerToolCallOutputScreenshot>,
        private val type: JsonValue,
        private val id: JsonField<String>,
        private val acknowledgedSafetyChecks: JsonField<List<AcknowledgedSafetyCheck>>,
        private val status: JsonField<Status>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("output")
            @ExcludeMissing
            output: JsonField<ResponseComputerToolCallOutputScreenshot> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("acknowledged_safety_checks")
            @ExcludeMissing
            acknowledgedSafetyChecks: JsonField<List<AcknowledgedSafetyCheck>> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
        ) : this(callId, output, type, id, acknowledgedSafetyChecks, status, mutableMapOf())

        /**
         * The ID of the computer tool call that produced the output.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun callId(): String = callId.getRequired("call_id")

        /**
         * A computer screenshot image used with the computer use tool.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun output(): ResponseComputerToolCallOutputScreenshot = output.getRequired("output")

        /**
         * The type of the computer tool call output. Always `computer_call_output`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("computer_call_output")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The ID of the computer tool call output.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun id(): Optional<String> = id.getOptional("id")

        /**
         * The safety checks reported by the API that have been acknowledged by the developer.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun acknowledgedSafetyChecks(): Optional<List<AcknowledgedSafetyCheck>> =
            acknowledgedSafetyChecks.getOptional("acknowledged_safety_checks")

        /**
         * The status of the message input. One of `in_progress`, `completed`, or `incomplete`.
         * Populated when input items are returned via API.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun status(): Optional<Status> = status.getOptional("status")

        /**
         * Returns the raw JSON value of [callId].
         *
         * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField<String> = callId

        /**
         * Returns the raw JSON value of [output].
         *
         * Unlike [output], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("output")
        @ExcludeMissing
        fun _output(): JsonField<ResponseComputerToolCallOutputScreenshot> = output

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [acknowledgedSafetyChecks].
         *
         * Unlike [acknowledgedSafetyChecks], this method doesn't throw if the JSON field has an
         * unexpected type.
         */
        @JsonProperty("acknowledged_safety_checks")
        @ExcludeMissing
        fun _acknowledgedSafetyChecks(): JsonField<List<AcknowledgedSafetyCheck>> =
            acknowledgedSafetyChecks

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [ComputerCallOutput].
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .output()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [ComputerCallOutput]. */
        class Builder internal constructor() {

            private var callId: JsonField<String>? = null
            private var output: JsonField<ResponseComputerToolCallOutputScreenshot>? = null
            private var type: JsonValue = JsonValue.from("computer_call_output")
            private var id: JsonField<String> = JsonMissing.of()
            private var acknowledgedSafetyChecks: JsonField<MutableList<AcknowledgedSafetyCheck>>? =
                null
            private var status: JsonField<Status> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(computerCallOutput: ComputerCallOutput) = apply {
                callId = computerCallOutput.callId
                output = computerCallOutput.output
                type = computerCallOutput.type
                id = computerCallOutput.id
                acknowledgedSafetyChecks =
                    computerCallOutput.acknowledgedSafetyChecks.map { it.toMutableList() }
                status = computerCallOutput.status
                additionalProperties = computerCallOutput.additionalProperties.toMutableMap()
            }

            /** The ID of the computer tool call that produced the output. */
            fun callId(callId: String) = callId(JsonField.of(callId))

            /**
             * Sets [Builder.callId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.callId] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun callId(callId: JsonField<String>) = apply { this.callId = callId }

            /** A computer screenshot image used with the computer use tool. */
            fun output(output: ResponseComputerToolCallOutputScreenshot) =
                output(JsonField.of(output))

            /**
             * Sets [Builder.output] to an arbitrary JSON value.
             *
             * You should usually call [Builder.output] with a well-typed
             * [ResponseComputerToolCallOutputScreenshot] value instead. This method is primarily
             * for setting the field to an undocumented or not yet supported value.
             */
            fun output(output: JsonField<ResponseComputerToolCallOutputScreenshot>) = apply {
                this.output = output
            }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("computer_call_output")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /** The ID of the computer tool call output. */
            fun id(id: String?) = id(JsonField.ofNullable(id))

            /** Alias for calling [Builder.id] with `id.orElse(null)`. */
            fun id(id: Optional<String>) = id(id.getOrNull())

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /**
             * The safety checks reported by the API that have been acknowledged by the developer.
             */
            fun acknowledgedSafetyChecks(acknowledgedSafetyChecks: List<AcknowledgedSafetyCheck>?) =
                acknowledgedSafetyChecks(JsonField.ofNullable(acknowledgedSafetyChecks))

            /**
             * Alias for calling [Builder.acknowledgedSafetyChecks] with
             * `acknowledgedSafetyChecks.orElse(null)`.
             */
            fun acknowledgedSafetyChecks(
                acknowledgedSafetyChecks: Optional<List<AcknowledgedSafetyCheck>>
            ) = acknowledgedSafetyChecks(acknowledgedSafetyChecks.getOrNull())

            /**
             * Sets [Builder.acknowledgedSafetyChecks] to an arbitrary JSON value.
             *
             * You should usually call [Builder.acknowledgedSafetyChecks] with a well-typed
             * `List<AcknowledgedSafetyCheck>` value instead. This method is primarily for setting
             * the field to an undocumented or not yet supported value.
             */
            fun acknowledgedSafetyChecks(
                acknowledgedSafetyChecks: JsonField<List<AcknowledgedSafetyCheck>>
            ) = apply {
                this.acknowledgedSafetyChecks = acknowledgedSafetyChecks.map { it.toMutableList() }
            }

            /**
             * Adds a single [AcknowledgedSafetyCheck] to [acknowledgedSafetyChecks].
             *
             * @throws IllegalStateException if the field was previously set to a non-list.
             */
            fun addAcknowledgedSafetyCheck(acknowledgedSafetyCheck: AcknowledgedSafetyCheck) =
                apply {
                    acknowledgedSafetyChecks =
                        (acknowledgedSafetyChecks ?: JsonField.of(mutableListOf())).also {
                            checkKnown("acknowledgedSafetyChecks", it).add(acknowledgedSafetyCheck)
                        }
                }

            /**
             * The status of the message input. One of `in_progress`, `completed`, or `incomplete`.
             * Populated when input items are returned via API.
             */
            fun status(status: Status?) = status(JsonField.ofNullable(status))

            /** Alias for calling [Builder.status] with `status.orElse(null)`. */
            fun status(status: Optional<Status>) = status(status.getOrNull())

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [ComputerCallOutput].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .output()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): ComputerCallOutput =
                ComputerCallOutput(
                    checkRequired("callId", callId),
                    checkRequired("output", output),
                    type,
                    id,
                    (acknowledgedSafetyChecks ?: JsonMissing.of()).map { it.toImmutable() },
                    status,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): ComputerCallOutput = apply {
            if (validated) {
                return@apply
            }

            callId()
            output().validate()
            _type().let {
                if (it != JsonValue.from("computer_call_output")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            id()
            acknowledgedSafetyChecks().ifPresent { it.forEach { it.validate() } }
            status().ifPresent { it.validate() }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (callId.asKnown().isPresent) 1 else 0) +
                (output.asKnown().getOrNull()?.validity() ?: 0) +
                type.let { if (it == JsonValue.from("computer_call_output")) 1 else 0 } +
                (if (id.asKnown().isPresent) 1 else 0) +
                (acknowledgedSafetyChecks.asKnown().getOrNull()?.sumOf { it.validity().toInt() }
                    ?: 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0)

        /** A pending safety check for the computer call. */
        class AcknowledgedSafetyCheck
        @JsonCreator(mode = JsonCreator.Mode.DISABLED)
        private constructor(
            private val id: JsonField<String>,
            private val code: JsonField<String>,
            private val message: JsonField<String>,
            private val additionalProperties: MutableMap<String, JsonValue>,
        ) {

            @JsonCreator
            private constructor(
                @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
                @JsonProperty("code") @ExcludeMissing code: JsonField<String> = JsonMissing.of(),
                @JsonProperty("message")
                @ExcludeMissing
                message: JsonField<String> = JsonMissing.of(),
            ) : this(id, code, message, mutableMapOf())

            /**
             * The ID of the pending safety check.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
             *   unexpectedly missing or null (e.g. if the server responded with an unexpected
             *   value).
             */
            fun id(): String = id.getRequired("id")

            /**
             * The type of the pending safety check.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if
             *   the server responded with an unexpected value).
             */
            fun code(): Optional<String> = code.getOptional("code")

            /**
             * Details about the pending safety check.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if
             *   the server responded with an unexpected value).
             */
            fun message(): Optional<String> = message.getOptional("message")

            /**
             * Returns the raw JSON value of [id].
             *
             * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
             */
            @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

            /**
             * Returns the raw JSON value of [code].
             *
             * Unlike [code], this method doesn't throw if the JSON field has an unexpected type.
             */
            @JsonProperty("code") @ExcludeMissing fun _code(): JsonField<String> = code

            /**
             * Returns the raw JSON value of [message].
             *
             * Unlike [message], this method doesn't throw if the JSON field has an unexpected type.
             */
            @JsonProperty("message") @ExcludeMissing fun _message(): JsonField<String> = message

            @JsonAnySetter
            private fun putAdditionalProperty(key: String, value: JsonValue) {
                additionalProperties.put(key, value)
            }

            @JsonAnyGetter
            @ExcludeMissing
            fun _additionalProperties(): Map<String, JsonValue> =
                Collections.unmodifiableMap(additionalProperties)

            fun toBuilder() = Builder().from(this)

            companion object {

                /**
                 * Returns a mutable builder for constructing an instance of
                 * [AcknowledgedSafetyCheck].
                 *
                 * The following fields are required:
                 * ```java
                 * .id()
                 * ```
                 */
                @JvmStatic fun builder() = Builder()
            }

            /** A builder for [AcknowledgedSafetyCheck]. */
            class Builder internal constructor() {

                private var id: JsonField<String>? = null
                private var code: JsonField<String> = JsonMissing.of()
                private var message: JsonField<String> = JsonMissing.of()
                private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                @JvmSynthetic
                internal fun from(acknowledgedSafetyCheck: AcknowledgedSafetyCheck) = apply {
                    id = acknowledgedSafetyCheck.id
                    code = acknowledgedSafetyCheck.code
                    message = acknowledgedSafetyCheck.message
                    additionalProperties =
                        acknowledgedSafetyCheck.additionalProperties.toMutableMap()
                }

                /** The ID of the pending safety check. */
                fun id(id: String) = id(JsonField.of(id))

                /**
                 * Sets [Builder.id] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.id] with a well-typed [String] value instead.
                 * This method is primarily for setting the field to an undocumented or not yet
                 * supported value.
                 */
                fun id(id: JsonField<String>) = apply { this.id = id }

                /** The type of the pending safety check. */
                fun code(code: String?) = code(JsonField.ofNullable(code))

                /** Alias for calling [Builder.code] with `code.orElse(null)`. */
                fun code(code: Optional<String>) = code(code.getOrNull())

                /**
                 * Sets [Builder.code] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.code] with a well-typed [String] value instead.
                 * This method is primarily for setting the field to an undocumented or not yet
                 * supported value.
                 */
                fun code(code: JsonField<String>) = apply { this.code = code }

                /** Details about the pending safety check. */
                fun message(message: String?) = message(JsonField.ofNullable(message))

                /** Alias for calling [Builder.message] with `message.orElse(null)`. */
                fun message(message: Optional<String>) = message(message.getOrNull())

                /**
                 * Sets [Builder.message] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.message] with a well-typed [String] value
                 * instead. This method is primarily for setting the field to an undocumented or not
                 * yet supported value.
                 */
                fun message(message: JsonField<String>) = apply { this.message = message }

                fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                    this.additionalProperties.clear()
                    putAllAdditionalProperties(additionalProperties)
                }

                fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                    additionalProperties.put(key, value)
                }

                fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) =
                    apply {
                        this.additionalProperties.putAll(additionalProperties)
                    }

                fun removeAdditionalProperty(key: String) = apply {
                    additionalProperties.remove(key)
                }

                fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                    keys.forEach(::removeAdditionalProperty)
                }

                /**
                 * Returns an immutable instance of [AcknowledgedSafetyCheck].
                 *
                 * Further updates to this [Builder] will not mutate the returned instance.
                 *
                 * The following fields are required:
                 * ```java
                 * .id()
                 * ```
                 *
                 * @throws IllegalStateException if any required field is unset.
                 */
                fun build(): AcknowledgedSafetyCheck =
                    AcknowledgedSafetyCheck(
                        checkRequired("id", id),
                        code,
                        message,
                        additionalProperties.toMutableMap(),
                    )
            }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): AcknowledgedSafetyCheck = apply {
                if (validated) {
                    return@apply
                }

                id()
                code()
                message()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic
            internal fun validity(): Int =
                (if (id.asKnown().isPresent) 1 else 0) +
                    (if (code.asKnown().isPresent) 1 else 0) +
                    (if (message.asKnown().isPresent) 1 else 0)

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is AcknowledgedSafetyCheck &&
                    id == other.id &&
                    code == other.code &&
                    message == other.message &&
                    additionalProperties == other.additionalProperties
            }

            private val hashCode: Int by lazy {
                Objects.hash(id, code, message, additionalProperties)
            }

            override fun hashCode(): Int = hashCode

            override fun toString() =
                "AcknowledgedSafetyCheck{id=$id, code=$code, message=$message, additionalProperties=$additionalProperties}"
        }

        /**
         * The status of the message input. One of `in_progress`, `completed`, or `incomplete`.
         * Populated when input items are returned via API.
         */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val INCOMPLETE = of("incomplete")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    INCOMPLETE -> Value.INCOMPLETE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    INCOMPLETE -> Known.INCOMPLETE
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is ComputerCallOutput &&
                callId == other.callId &&
                output == other.output &&
                type == other.type &&
                id == other.id &&
                acknowledgedSafetyChecks == other.acknowledgedSafetyChecks &&
                status == other.status &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(
                callId,
                output,
                type,
                id,
                acknowledgedSafetyChecks,
                status,
                additionalProperties,
            )
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "ComputerCallOutput{callId=$callId, output=$output, type=$type, id=$id, acknowledgedSafetyChecks=$acknowledgedSafetyChecks, status=$status, additionalProperties=$additionalProperties}"
    }

    /** The output of a function tool call. */
    class FunctionCallOutput
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val callId: JsonField<String>,
        private val output: JsonField<Output>,
        private val type: JsonValue,
        private val id: JsonField<String>,
        private val status: JsonField<Status>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("output") @ExcludeMissing output: JsonField<Output> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
        ) : this(callId, output, type, id, status, mutableMapOf())

        /**
         * The unique ID of the function tool call generated by the model.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun callId(): String = callId.getRequired("call_id")

        /**
         * Text, image, or file output of the function tool call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun output(): Output = output.getRequired("output")

        /**
         * The type of the function tool call output. Always `function_call_output`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("function_call_output")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The unique ID of the function tool call output. Populated when this item is returned via
         * API.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun id(): Optional<String> = id.getOptional("id")

        /**
         * The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated
         * when items are returned via API.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun status(): Optional<Status> = status.getOptional("status")

        /**
         * Returns the raw JSON value of [callId].
         *
         * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField<String> = callId

        /**
         * Returns the raw JSON value of [output].
         *
         * Unlike [output], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("output") @ExcludeMissing fun _output(): JsonField<Output> = output

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [FunctionCallOutput].
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .output()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [FunctionCallOutput]. */
        class Builder internal constructor() {

            private var callId: JsonField<String>? = null
            private var output: JsonField<Output>? = null
            private var type: JsonValue = JsonValue.from("function_call_output")
            private var id: JsonField<String> = JsonMissing.of()
            private var status: JsonField<Status> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(functionCallOutput: FunctionCallOutput) = apply {
                callId = functionCallOutput.callId
                output = functionCallOutput.output
                type = functionCallOutput.type
                id = functionCallOutput.id
                status = functionCallOutput.status
                additionalProperties = functionCallOutput.additionalProperties.toMutableMap()
            }

            /** The unique ID of the function tool call generated by the model. */
            fun callId(callId: String) = callId(JsonField.of(callId))

            /**
             * Sets [Builder.callId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.callId] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun callId(callId: JsonField<String>) = apply { this.callId = callId }

            /** Text, image, or file output of the function tool call. */
            fun output(output: Output) = output(JsonField.of(output))

            /**
             * Sets [Builder.output] to an arbitrary JSON value.
             *
             * You should usually call [Builder.output] with a well-typed [Output] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun output(output: JsonField<Output>) = apply { this.output = output }

            /** Alias for calling [output] with `Output.ofString(string)`. */
            fun output(string: String) = output(Output.ofString(string))

            /**
             * Sets the output to text representing the JSON serialized form of a given object. This
             * is useful when passing data that is the result of a function call.
             *
             * @see output
             */
            fun outputAsJson(functionResult: Any) = apply { output(toJsonString(functionResult)) }

            /**
             * Alias for calling [output] with
             * `Output.ofResponseFunctionCallOutputItemList(responseFunctionCallOutputItemList)`.
             */
            fun outputOfResponseFunctionCallOutputItemList(
                responseFunctionCallOutputItemList: List<ResponseFunctionCallOutputItem>
            ) =
                output(
                    Output.ofResponseFunctionCallOutputItemList(responseFunctionCallOutputItemList)
                )

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("function_call_output")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /**
             * The unique ID of the function tool call output. Populated when this item is returned
             * via API.
             */
            fun id(id: String?) = id(JsonField.ofNullable(id))

            /** Alias for calling [Builder.id] with `id.orElse(null)`. */
            fun id(id: Optional<String>) = id(id.getOrNull())

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /**
             * The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated
             * when items are returned via API.
             */
            fun status(status: Status?) = status(JsonField.ofNullable(status))

            /** Alias for calling [Builder.status] with `status.orElse(null)`. */
            fun status(status: Optional<Status>) = status(status.getOrNull())

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [FunctionCallOutput].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .output()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): FunctionCallOutput =
                FunctionCallOutput(
                    checkRequired("callId", callId),
                    checkRequired("output", output),
                    type,
                    id,
                    status,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): FunctionCallOutput = apply {
            if (validated) {
                return@apply
            }

            callId()
            output().validate()
            _type().let {
                if (it != JsonValue.from("function_call_output")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            id()
            status().ifPresent { it.validate() }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (callId.asKnown().isPresent) 1 else 0) +
                (output.asKnown().getOrNull()?.validity() ?: 0) +
                type.let { if (it == JsonValue.from("function_call_output")) 1 else 0 } +
                (if (id.asKnown().isPresent) 1 else 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0)

        /** Text, image, or file output of the function tool call. */
        @JsonDeserialize(using = Output.Deserializer::class)
        @JsonSerialize(using = Output.Serializer::class)
        class Output
        private constructor(
            private val string: String? = null,
            private val responseFunctionCallOutputItemList: List<ResponseFunctionCallOutputItem>? =
                null,
            private val _json: JsonValue? = null,
        ) {

            /** A JSON string of the output of the function tool call. */
            fun string(): Optional<String> = Optional.ofNullable(string)

            /** An array of content outputs (text, image, file) for the function tool call. */
            fun responseFunctionCallOutputItemList():
                Optional<List<ResponseFunctionCallOutputItem>> =
                Optional.ofNullable(responseFunctionCallOutputItemList)

            fun isString(): Boolean = string != null

            fun isResponseFunctionCallOutputItemList(): Boolean =
                responseFunctionCallOutputItemList != null

            /** A JSON string of the output of the function tool call. */
            fun asString(): String = string.getOrThrow("string")

            /** An array of content outputs (text, image, file) for the function tool call. */
            fun asResponseFunctionCallOutputItemList(): List<ResponseFunctionCallOutputItem> =
                responseFunctionCallOutputItemList.getOrThrow("responseFunctionCallOutputItemList")

            fun _json(): Optional<JsonValue> = Optional.ofNullable(_json)

            /**
             * Maps this instance's current variant to a value of type [T] using the given
             * [visitor].
             *
             * Note that this method is _not_ forwards compatible with new variants from the API,
             * unless [visitor] overrides [Visitor.unknown]. To handle variants not known to this
             * version of the SDK gracefully, consider overriding [Visitor.unknown]:
             * ```java
             * import com.openai.core.JsonValue;
             * import java.util.Optional;
             *
             * Optional<String> result = output.accept(new Output.Visitor<Optional<String>>() {
             *     @Override
             *     public Optional<String> visitString(String string) {
             *         return Optional.of(string.toString());
             *     }
             *
             *     // ...
             *
             *     @Override
             *     public Optional<String> unknown(JsonValue json) {
             *         // Or inspect the `json`.
             *         return Optional.empty();
             *     }
             * });
             * ```
             *
             * @throws OpenAIInvalidDataException if [Visitor.unknown] is not overridden in
             *   [visitor] and the current variant is unknown.
             */
            fun <T> accept(visitor: Visitor<T>): T =
                when {
                    string != null -> visitor.visitString(string)
                    responseFunctionCallOutputItemList != null ->
                        visitor.visitResponseFunctionCallOutputItemList(
                            responseFunctionCallOutputItemList
                        )
                    else -> visitor.unknown(_json)
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Output = apply {
                if (validated) {
                    return@apply
                }

                accept(
                    object : Visitor<Unit> {
                        override fun visitString(string: String) {}

                        override fun visitResponseFunctionCallOutputItemList(
                            responseFunctionCallOutputItemList: List<ResponseFunctionCallOutputItem>
                        ) {
                            responseFunctionCallOutputItemList.forEach { it.validate() }
                        }
                    }
                )
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic
            internal fun validity(): Int =
                accept(
                    object : Visitor<Int> {
                        override fun visitString(string: String) = 1

                        override fun visitResponseFunctionCallOutputItemList(
                            responseFunctionCallOutputItemList: List<ResponseFunctionCallOutputItem>
                        ) = responseFunctionCallOutputItemList.sumOf { it.validity().toInt() }

                        override fun unknown(json: JsonValue?) = 0
                    }
                )

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Output &&
                    string == other.string &&
                    responseFunctionCallOutputItemList == other.responseFunctionCallOutputItemList
            }

            override fun hashCode(): Int = Objects.hash(string, responseFunctionCallOutputItemList)

            override fun toString(): String =
                when {
                    string != null -> "Output{string=$string}"
                    responseFunctionCallOutputItemList != null ->
                        "Output{responseFunctionCallOutputItemList=$responseFunctionCallOutputItemList}"
                    _json != null -> "Output{_unknown=$_json}"
                    else -> throw IllegalStateException("Invalid Output")
                }

            companion object {

                /** A JSON string of the output of the function tool call. */
                @JvmStatic fun ofString(string: String) = Output(string = string)

                /** An array of content outputs (text, image, file) for the function tool call. */
                @JvmStatic
                fun ofResponseFunctionCallOutputItemList(
                    responseFunctionCallOutputItemList: List<ResponseFunctionCallOutputItem>
                ) =
                    Output(
                        responseFunctionCallOutputItemList =
                            responseFunctionCallOutputItemList.toImmutable()
                    )
            }

            /**
             * An interface that defines how to map each variant of [Output] to a value of type [T].
             */
            interface Visitor<out T> {

                /** A JSON string of the output of the function tool call. */
                fun visitString(string: String): T

                /** An array of content outputs (text, image, file) for the function tool call. */
                fun visitResponseFunctionCallOutputItemList(
                    responseFunctionCallOutputItemList: List<ResponseFunctionCallOutputItem>
                ): T

                /**
                 * Maps an unknown variant of [Output] to a value of type [T].
                 *
                 * An instance of [Output] can contain an unknown variant if it was deserialized
                 * from data that doesn't match any known variant. For example, if the SDK is on an
                 * older version than the API, then the API may respond with new variants that the
                 * SDK is unaware of.
                 *
                 * @throws OpenAIInvalidDataException in the default implementation.
                 */
                fun unknown(json: JsonValue?): T {
                    throw OpenAIInvalidDataException("Unknown Output: $json")
                }
            }

            internal class Deserializer : BaseDeserializer<Output>(Output::class) {

                override fun ObjectCodec.deserialize(node: JsonNode): Output {
                    val json = JsonValue.fromJsonNode(node)

                    val bestMatches =
                        sequenceOf(
                                tryDeserialize(node, jacksonTypeRef<String>())?.let {
                                    Output(string = it, _json = json)
                                },
                                tryDeserialize(
                                        node,
                                        jacksonTypeRef<List<ResponseFunctionCallOutputItem>>(),
                                    )
                                    ?.let {
                                        Output(
                                            responseFunctionCallOutputItemList = it,
                                            _json = json,
                                        )
                                    },
                            )
                            .filterNotNull()
                            .allMaxBy { it.validity() }
                            .toList()
                    return when (bestMatches.size) {
                        // This can happen if what we're deserializing is completely incompatible
                        // with all the possible variants (e.g. deserializing from boolean).
                        0 -> Output(_json = json)
                        1 -> bestMatches.single()
                        // If there's more than one match with the highest validity, then use the
                        // first completely valid match, or simply the first match if none are
                        // completely valid.
                        else -> bestMatches.firstOrNull { it.isValid() } ?: bestMatches.first()
                    }
                }
            }

            internal class Serializer : BaseSerializer<Output>(Output::class) {

                override fun serialize(
                    value: Output,
                    generator: JsonGenerator,
                    provider: SerializerProvider,
                ) {
                    when {
                        value.string != null -> generator.writeObject(value.string)
                        value.responseFunctionCallOutputItemList != null ->
                            generator.writeObject(value.responseFunctionCallOutputItemList)
                        value._json != null -> generator.writeObject(value._json)
                        else -> throw IllegalStateException("Invalid Output")
                    }
                }
            }
        }

        /**
         * The status of the item. One of `in_progress`, `completed`, or `incomplete`. Populated
         * when items are returned via API.
         */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val INCOMPLETE = of("incomplete")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    INCOMPLETE -> Value.INCOMPLETE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    INCOMPLETE -> Known.INCOMPLETE
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is FunctionCallOutput &&
                callId == other.callId &&
                output == other.output &&
                type == other.type &&
                id == other.id &&
                status == other.status &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(callId, output, type, id, status, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "FunctionCallOutput{callId=$callId, output=$output, type=$type, id=$id, status=$status, additionalProperties=$additionalProperties}"
    }

    class ToolSearchCall
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val arguments: JsonValue,
        private val type: JsonValue,
        private val id: JsonField<String>,
        private val callId: JsonField<String>,
        private val execution: JsonField<Execution>,
        private val status: JsonField<Status>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("arguments") @ExcludeMissing arguments: JsonValue = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("execution")
            @ExcludeMissing
            execution: JsonField<Execution> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
        ) : this(arguments, type, id, callId, execution, status, mutableMapOf())

        /**
         * The arguments supplied to the tool search call.
         *
         * This arbitrary value can be deserialized into a custom type using the `convert` method:
         * ```java
         * MyClass myObject = toolSearchCall.arguments().convert(MyClass.class);
         * ```
         */
        @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonValue = arguments

        /**
         * The item type. Always `tool_search_call`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("tool_search_call")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The unique ID of this tool search call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun id(): Optional<String> = id.getOptional("id")

        /**
         * The unique ID of the tool search call generated by the model.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun callId(): Optional<String> = callId.getOptional("call_id")

        /**
         * Whether tool search was executed by the server or by the client.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun execution(): Optional<Execution> = execution.getOptional("execution")

        /**
         * The status of the tool search call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun status(): Optional<Status> = status.getOptional("status")

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [callId].
         *
         * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField<String> = callId

        /**
         * Returns the raw JSON value of [execution].
         *
         * Unlike [execution], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("execution")
        @ExcludeMissing
        fun _execution(): JsonField<Execution> = execution

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [ToolSearchCall].
             *
             * The following fields are required:
             * ```java
             * .arguments()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [ToolSearchCall]. */
        class Builder internal constructor() {

            private var arguments: JsonValue? = null
            private var type: JsonValue = JsonValue.from("tool_search_call")
            private var id: JsonField<String> = JsonMissing.of()
            private var callId: JsonField<String> = JsonMissing.of()
            private var execution: JsonField<Execution> = JsonMissing.of()
            private var status: JsonField<Status> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(toolSearchCall: ToolSearchCall) = apply {
                arguments = toolSearchCall.arguments
                type = toolSearchCall.type
                id = toolSearchCall.id
                callId = toolSearchCall.callId
                execution = toolSearchCall.execution
                status = toolSearchCall.status
                additionalProperties = toolSearchCall.additionalProperties.toMutableMap()
            }

            /** The arguments supplied to the tool search call. */
            fun arguments(arguments: JsonValue) = apply { this.arguments = arguments }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("tool_search_call")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /** The unique ID of this tool search call. */
            fun id(id: String?) = id(JsonField.ofNullable(id))

            /** Alias for calling [Builder.id] with `id.orElse(null)`. */
            fun id(id: Optional<String>) = id(id.getOrNull())

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** The unique ID of the tool search call generated by the model. */
            fun callId(callId: String?) = callId(JsonField.ofNullable(callId))

            /** Alias for calling [Builder.callId] with `callId.orElse(null)`. */
            fun callId(callId: Optional<String>) = callId(callId.getOrNull())

            /**
             * Sets [Builder.callId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.callId] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun callId(callId: JsonField<String>) = apply { this.callId = callId }

            /** Whether tool search was executed by the server or by the client. */
            fun execution(execution: Execution) = execution(JsonField.of(execution))

            /**
             * Sets [Builder.execution] to an arbitrary JSON value.
             *
             * You should usually call [Builder.execution] with a well-typed [Execution] value
             * instead. This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun execution(execution: JsonField<Execution>) = apply { this.execution = execution }

            /** The status of the tool search call. */
            fun status(status: Status?) = status(JsonField.ofNullable(status))

            /** Alias for calling [Builder.status] with `status.orElse(null)`. */
            fun status(status: Optional<Status>) = status(status.getOrNull())

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [ToolSearchCall].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .arguments()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): ToolSearchCall =
                ToolSearchCall(
                    checkRequired("arguments", arguments),
                    type,
                    id,
                    callId,
                    execution,
                    status,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): ToolSearchCall = apply {
            if (validated) {
                return@apply
            }

            _type().let {
                if (it != JsonValue.from("tool_search_call")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            id()
            callId()
            execution().ifPresent { it.validate() }
            status().ifPresent { it.validate() }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            type.let { if (it == JsonValue.from("tool_search_call")) 1 else 0 } +
                (if (id.asKnown().isPresent) 1 else 0) +
                (if (callId.asKnown().isPresent) 1 else 0) +
                (execution.asKnown().getOrNull()?.validity() ?: 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0)

        /** Whether tool search was executed by the server or by the client. */
        class Execution @JsonCreator private constructor(private val value: JsonField<String>) :
            Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val SERVER = of("server")

                @JvmField val CLIENT = of("client")

                @JvmStatic fun of(value: String) = Execution(JsonField.of(value))
            }

            /** An enum containing [Execution]'s known values. */
            enum class Known {
                SERVER,
                CLIENT,
            }

            /**
             * An enum containing [Execution]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Execution] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                SERVER,
                CLIENT,
                /**
                 * An enum member indicating that [Execution] was instantiated with an unknown
                 * value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    SERVER -> Value.SERVER
                    CLIENT -> Value.CLIENT
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    SERVER -> Known.SERVER
                    CLIENT -> Known.CLIENT
                    else -> throw OpenAIInvalidDataException("Unknown Execution: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Execution = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Execution && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        /** The status of the tool search call. */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val INCOMPLETE = of("incomplete")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    INCOMPLETE -> Value.INCOMPLETE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    INCOMPLETE -> Known.INCOMPLETE
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is ToolSearchCall &&
                arguments == other.arguments &&
                type == other.type &&
                id == other.id &&
                callId == other.callId &&
                execution == other.execution &&
                status == other.status &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(arguments, type, id, callId, execution, status, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "ToolSearchCall{arguments=$arguments, type=$type, id=$id, callId=$callId, execution=$execution, status=$status, additionalProperties=$additionalProperties}"
    }

    class AdditionalTools
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val role: JsonValue,
        private val tools: JsonField<List<Tool>>,
        private val type: JsonValue,
        private val id: JsonField<String>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("role") @ExcludeMissing role: JsonValue = JsonMissing.of(),
            @JsonProperty("tools") @ExcludeMissing tools: JsonField<List<Tool>> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
        ) : this(role, tools, type, id, mutableMapOf())

        /**
         * The role that provided the additional tools. Only `developer` is supported.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("developer")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role

        /**
         * A list of additional tools made available at this item.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun tools(): List<Tool> = tools.getRequired("tools")

        /**
         * The item type. Always `additional_tools`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("additional_tools")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The unique ID of this additional tools item.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun id(): Optional<String> = id.getOptional("id")

        /**
         * Returns the raw JSON value of [tools].
         *
         * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField<List<Tool>> = tools

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [AdditionalTools].
             *
             * The following fields are required:
             * ```java
             * .tools()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [AdditionalTools]. */
        class Builder internal constructor() {

            private var role: JsonValue = JsonValue.from("developer")
            private var tools: JsonField<MutableList<Tool>>? = null
            private var type: JsonValue = JsonValue.from("additional_tools")
            private var id: JsonField<String> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(additionalTools: AdditionalTools) = apply {
                role = additionalTools.role
                tools = additionalTools.tools.map { it.toMutableList() }
                type = additionalTools.type
                id = additionalTools.id
                additionalProperties = additionalTools.additionalProperties.toMutableMap()
            }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("developer")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun role(role: JsonValue) = apply { this.role = role }

            /** A list of additional tools made available at this item. */
            fun tools(tools: List<Tool>) = tools(JsonField.of(tools))

            /**
             * Sets [Builder.tools] to an arbitrary JSON value.
             *
             * You should usually call [Builder.tools] with a well-typed `List<Tool>` value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun tools(tools: JsonField<List<Tool>>) = apply {
                this.tools = tools.map { it.toMutableList() }
            }

            /**
             * Adds a single [Tool] to [tools].
             *
             * @throws IllegalStateException if the field was previously set to a non-list.
             */
            fun addTool(tool: Tool) = apply {
                tools =
                    (tools ?: JsonField.of(mutableListOf())).also {
                        checkKnown("tools", it).add(tool)
                    }
            }

            /** Alias for calling [addTool] with `Tool.ofFunction(function)`. */
            fun addTool(function: FunctionTool) = addTool(Tool.ofFunction(function))

            /** Alias for calling [addTool] with `Tool.ofFileSearch(fileSearch)`. */
            fun addTool(fileSearch: FileSearchTool) = addTool(Tool.ofFileSearch(fileSearch))

            /**
             * Alias for calling [addTool] with the following:
             * ```java
             * FileSearchTool.builder()
             *     .vectorStoreIds(vectorStoreIds)
             *     .build()
             * ```
             */
            fun addFileSearchTool(vectorStoreIds: List<String>) =
                addTool(FileSearchTool.builder().vectorStoreIds(vectorStoreIds).build())

            /** Alias for calling [addTool] with `Tool.ofComputer(computer)`. */
            fun addTool(computer: ComputerTool) = addTool(Tool.ofComputer(computer))

            /** Alias for calling [addTool] with `Tool.ofComputerUsePreview(computerUsePreview)`. */
            fun addTool(computerUsePreview: ComputerUsePreviewTool) =
                addTool(Tool.ofComputerUsePreview(computerUsePreview))

            /** Alias for calling [addTool] with `Tool.ofWebSearch(webSearch)`. */
            fun addTool(webSearch: WebSearchTool) = addTool(Tool.ofWebSearch(webSearch))

            /** Alias for calling [addTool] with `Tool.ofMcp(mcp)`. */
            fun addTool(mcp: Tool.Mcp) = addTool(Tool.ofMcp(mcp))

            /**
             * Alias for calling [addTool] with the following:
             * ```java
             * Tool.Mcp.builder()
             *     .serverLabel(serverLabel)
             *     .build()
             * ```
             */
            fun addMcpTool(serverLabel: String) =
                addTool(Tool.Mcp.builder().serverLabel(serverLabel).build())

            /** Alias for calling [addTool] with `Tool.ofCodeInterpreter(codeInterpreter)`. */
            fun addTool(codeInterpreter: Tool.CodeInterpreter) =
                addTool(Tool.ofCodeInterpreter(codeInterpreter))

            /**
             * Alias for calling [addTool] with the following:
             * ```java
             * Tool.CodeInterpreter.builder()
             *     .container(container)
             *     .build()
             * ```
             */
            fun addCodeInterpreterTool(container: Tool.CodeInterpreter.Container) =
                addTool(Tool.CodeInterpreter.builder().container(container).build())

            /**
             * Alias for calling [addCodeInterpreterTool] with
             * `Tool.CodeInterpreter.Container.ofString(string)`.
             */
            fun addCodeInterpreterTool(string: String) =
                addCodeInterpreterTool(Tool.CodeInterpreter.Container.ofString(string))

            /**
             * Alias for calling [addCodeInterpreterTool] with
             * `Tool.CodeInterpreter.Container.ofCodeInterpreterToolAuto(codeInterpreterToolAuto)`.
             */
            fun addCodeInterpreterTool(
                codeInterpreterToolAuto: Tool.CodeInterpreter.Container.CodeInterpreterToolAuto
            ) =
                addCodeInterpreterTool(
                    Tool.CodeInterpreter.Container.ofCodeInterpreterToolAuto(
                        codeInterpreterToolAuto
                    )
                )

            /** Alias for calling [addTool] with `Tool.ofImageGeneration(imageGeneration)`. */
            fun addTool(imageGeneration: Tool.ImageGeneration) =
                addTool(Tool.ofImageGeneration(imageGeneration))

            /** Alias for calling [addTool] with `Tool.ofLocalShell()`. */
            fun addToolLocalShell() = addTool(Tool.ofLocalShell())

            /** Alias for calling [addTool] with `Tool.ofShell(shell)`. */
            fun addTool(shell: FunctionShellTool) = addTool(Tool.ofShell(shell))

            /** Alias for calling [addTool] with `Tool.ofCustom(custom)`. */
            fun addTool(custom: CustomTool) = addTool(Tool.ofCustom(custom))

            /**
             * Alias for calling [addTool] with the following:
             * ```java
             * CustomTool.builder()
             *     .name(name)
             *     .build()
             * ```
             */
            fun addCustomTool(name: String) = addTool(CustomTool.builder().name(name).build())

            /** Alias for calling [addTool] with `Tool.ofNamespace(namespace)`. */
            fun addTool(namespace: NamespaceTool) = addTool(Tool.ofNamespace(namespace))

            /** Alias for calling [addTool] with `Tool.ofSearch(search)`. */
            fun addTool(search: ToolSearchTool) = addTool(Tool.ofSearch(search))

            /** Alias for calling [addTool] with `Tool.ofWebSearchPreview(webSearchPreview)`. */
            fun addTool(webSearchPreview: WebSearchPreviewTool) =
                addTool(Tool.ofWebSearchPreview(webSearchPreview))

            /** Alias for calling [addTool] with `Tool.ofApplyPatch(applyPatch)`. */
            fun addTool(applyPatch: ApplyPatchTool) = addTool(Tool.ofApplyPatch(applyPatch))

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("additional_tools")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /** The unique ID of this additional tools item. */
            fun id(id: String?) = id(JsonField.ofNullable(id))

            /** Alias for calling [Builder.id] with `id.orElse(null)`. */
            fun id(id: Optional<String>) = id(id.getOrNull())

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [AdditionalTools].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .tools()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): AdditionalTools =
                AdditionalTools(
                    role,
                    checkRequired("tools", tools).map { it.toImmutable() },
                    type,
                    id,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): AdditionalTools = apply {
            if (validated) {
                return@apply
            }

            _role().let {
                if (it != JsonValue.from("developer")) {
                    throw OpenAIInvalidDataException("'role' is invalid, received $it")
                }
            }
            tools().forEach { it.validate() }
            _type().let {
                if (it != JsonValue.from("additional_tools")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            id()
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            role.let { if (it == JsonValue.from("developer")) 1 else 0 } +
                (tools.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) +
                type.let { if (it == JsonValue.from("additional_tools")) 1 else 0 } +
                (if (id.asKnown().isPresent) 1 else 0)

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is AdditionalTools &&
                role == other.role &&
                tools == other.tools &&
                type == other.type &&
                id == other.id &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(role, tools, type, id, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "AdditionalTools{role=$role, tools=$tools, type=$type, id=$id, additionalProperties=$additionalProperties}"
    }

    /** An image generation request made by the model. */
    class ImageGenerationCall
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val id: JsonField<String>,
        private val result: JsonField<String>,
        private val status: JsonField<Status>,
        private val type: JsonValue,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("result") @ExcludeMissing result: JsonField<String> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
        ) : this(id, result, status, type, mutableMapOf())

        /**
         * The unique ID of the image generation call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun id(): String = id.getRequired("id")

        /**
         * The generated image encoded in base64.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun result(): Optional<String> = result.getOptional("result")

        /**
         * The status of the image generation call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun status(): Status = status.getRequired("status")

        /**
         * The type of the image generation call. Always `image_generation_call`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("image_generation_call")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [result].
         *
         * Unlike [result], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("result") @ExcludeMissing fun _result(): JsonField<String> = result

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [ImageGenerationCall].
             *
             * The following fields are required:
             * ```java
             * .id()
             * .result()
             * .status()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [ImageGenerationCall]. */
        class Builder internal constructor() {

            private var id: JsonField<String>? = null
            private var result: JsonField<String>? = null
            private var status: JsonField<Status>? = null
            private var type: JsonValue = JsonValue.from("image_generation_call")
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(imageGenerationCall: ImageGenerationCall) = apply {
                id = imageGenerationCall.id
                result = imageGenerationCall.result
                status = imageGenerationCall.status
                type = imageGenerationCall.type
                additionalProperties = imageGenerationCall.additionalProperties.toMutableMap()
            }

            /** The unique ID of the image generation call. */
            fun id(id: String) = id(JsonField.of(id))

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** The generated image encoded in base64. */
            fun result(result: String?) = result(JsonField.ofNullable(result))

            /** Alias for calling [Builder.result] with `result.orElse(null)`. */
            fun result(result: Optional<String>) = result(result.getOrNull())

            /**
             * Sets [Builder.result] to an arbitrary JSON value.
             *
             * You should usually call [Builder.result] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun result(result: JsonField<String>) = apply { this.result = result }

            /** The status of the image generation call. */
            fun status(status: Status) = status(JsonField.of(status))

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("image_generation_call")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [ImageGenerationCall].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .id()
             * .result()
             * .status()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): ImageGenerationCall =
                ImageGenerationCall(
                    checkRequired("id", id),
                    checkRequired("result", result),
                    checkRequired("status", status),
                    type,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): ImageGenerationCall = apply {
            if (validated) {
                return@apply
            }

            id()
            result()
            status().validate()
            _type().let {
                if (it != JsonValue.from("image_generation_call")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (id.asKnown().isPresent) 1 else 0) +
                (if (result.asKnown().isPresent) 1 else 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0) +
                type.let { if (it == JsonValue.from("image_generation_call")) 1 else 0 }

        /** The status of the image generation call. */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val GENERATING = of("generating")

                @JvmField val FAILED = of("failed")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                GENERATING,
                FAILED,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                GENERATING,
                FAILED,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    GENERATING -> Value.GENERATING
                    FAILED -> Value.FAILED
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    GENERATING -> Known.GENERATING
                    FAILED -> Known.FAILED
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is ImageGenerationCall &&
                id == other.id &&
                result == other.result &&
                status == other.status &&
                type == other.type &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(id, result, status, type, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "ImageGenerationCall{id=$id, result=$result, status=$status, type=$type, additionalProperties=$additionalProperties}"
    }

    /** A tool call to run a command on the local shell. */
    class LocalShellCall
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val id: JsonField<String>,
        private val action: JsonField<Action>,
        private val callId: JsonField<String>,
        private val status: JsonField<Status>,
        private val type: JsonValue,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("action") @ExcludeMissing action: JsonField<Action> = JsonMissing.of(),
            @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
        ) : this(id, action, callId, status, type, mutableMapOf())

        /**
         * The unique ID of the local shell call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun id(): String = id.getRequired("id")

        /**
         * Execute a shell command on the server.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun action(): Action = action.getRequired("action")

        /**
         * The unique ID of the local shell tool call generated by the model.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun callId(): String = callId.getRequired("call_id")

        /**
         * The status of the local shell call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun status(): Status = status.getRequired("status")

        /**
         * The type of the local shell call. Always `local_shell_call`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("local_shell_call")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [action].
         *
         * Unlike [action], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("action") @ExcludeMissing fun _action(): JsonField<Action> = action

        /**
         * Returns the raw JSON value of [callId].
         *
         * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField<String> = callId

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [LocalShellCall].
             *
             * The following fields are required:
             * ```java
             * .id()
             * .action()
             * .callId()
             * .status()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [LocalShellCall]. */
        class Builder internal constructor() {

            private var id: JsonField<String>? = null
            private var action: JsonField<Action>? = null
            private var callId: JsonField<String>? = null
            private var status: JsonField<Status>? = null
            private var type: JsonValue = JsonValue.from("local_shell_call")
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(localShellCall: LocalShellCall) = apply {
                id = localShellCall.id
                action = localShellCall.action
                callId = localShellCall.callId
                status = localShellCall.status
                type = localShellCall.type
                additionalProperties = localShellCall.additionalProperties.toMutableMap()
            }

            /** The unique ID of the local shell call. */
            fun id(id: String) = id(JsonField.of(id))

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** Execute a shell command on the server. */
            fun action(action: Action) = action(JsonField.of(action))

            /**
             * Sets [Builder.action] to an arbitrary JSON value.
             *
             * You should usually call [Builder.action] with a well-typed [Action] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun action(action: JsonField<Action>) = apply { this.action = action }

            /** The unique ID of the local shell tool call generated by the model. */
            fun callId(callId: String) = callId(JsonField.of(callId))

            /**
             * Sets [Builder.callId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.callId] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun callId(callId: JsonField<String>) = apply { this.callId = callId }

            /** The status of the local shell call. */
            fun status(status: Status) = status(JsonField.of(status))

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("local_shell_call")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [LocalShellCall].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .id()
             * .action()
             * .callId()
             * .status()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): LocalShellCall =
                LocalShellCall(
                    checkRequired("id", id),
                    checkRequired("action", action),
                    checkRequired("callId", callId),
                    checkRequired("status", status),
                    type,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): LocalShellCall = apply {
            if (validated) {
                return@apply
            }

            id()
            action().validate()
            callId()
            status().validate()
            _type().let {
                if (it != JsonValue.from("local_shell_call")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (id.asKnown().isPresent) 1 else 0) +
                (action.asKnown().getOrNull()?.validity() ?: 0) +
                (if (callId.asKnown().isPresent) 1 else 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0) +
                type.let { if (it == JsonValue.from("local_shell_call")) 1 else 0 }

        /** Execute a shell command on the server. */
        class Action
        @JsonCreator(mode = JsonCreator.Mode.DISABLED)
        private constructor(
            private val command: JsonField<List<String>>,
            private val env: JsonField<Env>,
            private val type: JsonValue,
            private val timeoutMs: JsonField<Long>,
            private val user: JsonField<String>,
            private val workingDirectory: JsonField<String>,
            private val additionalProperties: MutableMap<String, JsonValue>,
        ) {

            @JsonCreator
            private constructor(
                @JsonProperty("command")
                @ExcludeMissing
                command: JsonField<List<String>> = JsonMissing.of(),
                @JsonProperty("env") @ExcludeMissing env: JsonField<Env> = JsonMissing.of(),
                @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
                @JsonProperty("timeout_ms")
                @ExcludeMissing
                timeoutMs: JsonField<Long> = JsonMissing.of(),
                @JsonProperty("user") @ExcludeMissing user: JsonField<String> = JsonMissing.of(),
                @JsonProperty("working_directory")
                @ExcludeMissing
                workingDirectory: JsonField<String> = JsonMissing.of(),
            ) : this(command, env, type, timeoutMs, user, workingDirectory, mutableMapOf())

            /**
             * The command to run.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
             *   unexpectedly missing or null (e.g. if the server responded with an unexpected
             *   value).
             */
            fun command(): List<String> = command.getRequired("command")

            /**
             * Environment variables to set for the command.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
             *   unexpectedly missing or null (e.g. if the server responded with an unexpected
             *   value).
             */
            fun env(): Env = env.getRequired("env")

            /**
             * The type of the local shell action. Always `exec`.
             *
             * Expected to always return the following:
             * ```java
             * JsonValue.from("exec")
             * ```
             *
             * However, this method can be useful for debugging and logging (e.g. if the server
             * responded with an unexpected value).
             */
            @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

            /**
             * Optional timeout in milliseconds for the command.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if
             *   the server responded with an unexpected value).
             */
            fun timeoutMs(): Optional<Long> = timeoutMs.getOptional("timeout_ms")

            /**
             * Optional user to run the command as.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if
             *   the server responded with an unexpected value).
             */
            fun user(): Optional<String> = user.getOptional("user")

            /**
             * Optional working directory to run the command in.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if
             *   the server responded with an unexpected value).
             */
            fun workingDirectory(): Optional<String> =
                workingDirectory.getOptional("working_directory")

            /**
             * Returns the raw JSON value of [command].
             *
             * Unlike [command], this method doesn't throw if the JSON field has an unexpected type.
             */
            @JsonProperty("command")
            @ExcludeMissing
            fun _command(): JsonField<List<String>> = command

            /**
             * Returns the raw JSON value of [env].
             *
             * Unlike [env], this method doesn't throw if the JSON field has an unexpected type.
             */
            @JsonProperty("env") @ExcludeMissing fun _env(): JsonField<Env> = env

            /**
             * Returns the raw JSON value of [timeoutMs].
             *
             * Unlike [timeoutMs], this method doesn't throw if the JSON field has an unexpected
             * type.
             */
            @JsonProperty("timeout_ms")
            @ExcludeMissing
            fun _timeoutMs(): JsonField<Long> = timeoutMs

            /**
             * Returns the raw JSON value of [user].
             *
             * Unlike [user], this method doesn't throw if the JSON field has an unexpected type.
             */
            @JsonProperty("user") @ExcludeMissing fun _user(): JsonField<String> = user

            /**
             * Returns the raw JSON value of [workingDirectory].
             *
             * Unlike [workingDirectory], this method doesn't throw if the JSON field has an
             * unexpected type.
             */
            @JsonProperty("working_directory")
            @ExcludeMissing
            fun _workingDirectory(): JsonField<String> = workingDirectory

            @JsonAnySetter
            private fun putAdditionalProperty(key: String, value: JsonValue) {
                additionalProperties.put(key, value)
            }

            @JsonAnyGetter
            @ExcludeMissing
            fun _additionalProperties(): Map<String, JsonValue> =
                Collections.unmodifiableMap(additionalProperties)

            fun toBuilder() = Builder().from(this)

            companion object {

                /**
                 * Returns a mutable builder for constructing an instance of [Action].
                 *
                 * The following fields are required:
                 * ```java
                 * .command()
                 * .env()
                 * ```
                 */
                @JvmStatic fun builder() = Builder()
            }

            /** A builder for [Action]. */
            class Builder internal constructor() {

                private var command: JsonField<MutableList<String>>? = null
                private var env: JsonField<Env>? = null
                private var type: JsonValue = JsonValue.from("exec")
                private var timeoutMs: JsonField<Long> = JsonMissing.of()
                private var user: JsonField<String> = JsonMissing.of()
                private var workingDirectory: JsonField<String> = JsonMissing.of()
                private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                @JvmSynthetic
                internal fun from(action: Action) = apply {
                    command = action.command.map { it.toMutableList() }
                    env = action.env
                    type = action.type
                    timeoutMs = action.timeoutMs
                    user = action.user
                    workingDirectory = action.workingDirectory
                    additionalProperties = action.additionalProperties.toMutableMap()
                }

                /** The command to run. */
                fun command(command: List<String>) = command(JsonField.of(command))

                /**
                 * Sets [Builder.command] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.command] with a well-typed `List<String>` value
                 * instead. This method is primarily for setting the field to an undocumented or not
                 * yet supported value.
                 */
                fun command(command: JsonField<List<String>>) = apply {
                    this.command = command.map { it.toMutableList() }
                }

                /**
                 * Adds a single [String] to [Builder.command].
                 *
                 * @throws IllegalStateException if the field was previously set to a non-list.
                 */
                fun addCommand(command: String) = apply {
                    this.command =
                        (this.command ?: JsonField.of(mutableListOf())).also {
                            checkKnown("command", it).add(command)
                        }
                }

                /** Environment variables to set for the command. */
                fun env(env: Env) = env(JsonField.of(env))

                /**
                 * Sets [Builder.env] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.env] with a well-typed [Env] value instead. This
                 * method is primarily for setting the field to an undocumented or not yet supported
                 * value.
                 */
                fun env(env: JsonField<Env>) = apply { this.env = env }

                /**
                 * Sets the field to an arbitrary JSON value.
                 *
                 * It is usually unnecessary to call this method because the field defaults to the
                 * following:
                 * ```java
                 * JsonValue.from("exec")
                 * ```
                 *
                 * This method is primarily for setting the field to an undocumented or not yet
                 * supported value.
                 */
                fun type(type: JsonValue) = apply { this.type = type }

                /** Optional timeout in milliseconds for the command. */
                fun timeoutMs(timeoutMs: Long?) = timeoutMs(JsonField.ofNullable(timeoutMs))

                /**
                 * Alias for [Builder.timeoutMs].
                 *
                 * This unboxed primitive overload exists for backwards compatibility.
                 */
                fun timeoutMs(timeoutMs: Long) = timeoutMs(timeoutMs as Long?)

                /** Alias for calling [Builder.timeoutMs] with `timeoutMs.orElse(null)`. */
                fun timeoutMs(timeoutMs: Optional<Long>) = timeoutMs(timeoutMs.getOrNull())

                /**
                 * Sets [Builder.timeoutMs] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.timeoutMs] with a well-typed [Long] value
                 * instead. This method is primarily for setting the field to an undocumented or not
                 * yet supported value.
                 */
                fun timeoutMs(timeoutMs: JsonField<Long>) = apply { this.timeoutMs = timeoutMs }

                /** Optional user to run the command as. */
                fun user(user: String?) = user(JsonField.ofNullable(user))

                /** Alias for calling [Builder.user] with `user.orElse(null)`. */
                fun user(user: Optional<String>) = user(user.getOrNull())

                /**
                 * Sets [Builder.user] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.user] with a well-typed [String] value instead.
                 * This method is primarily for setting the field to an undocumented or not yet
                 * supported value.
                 */
                fun user(user: JsonField<String>) = apply { this.user = user }

                /** Optional working directory to run the command in. */
                fun workingDirectory(workingDirectory: String?) =
                    workingDirectory(JsonField.ofNullable(workingDirectory))

                /**
                 * Alias for calling [Builder.workingDirectory] with
                 * `workingDirectory.orElse(null)`.
                 */
                fun workingDirectory(workingDirectory: Optional<String>) =
                    workingDirectory(workingDirectory.getOrNull())

                /**
                 * Sets [Builder.workingDirectory] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.workingDirectory] with a well-typed [String]
                 * value instead. This method is primarily for setting the field to an undocumented
                 * or not yet supported value.
                 */
                fun workingDirectory(workingDirectory: JsonField<String>) = apply {
                    this.workingDirectory = workingDirectory
                }

                fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                    this.additionalProperties.clear()
                    putAllAdditionalProperties(additionalProperties)
                }

                fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                    additionalProperties.put(key, value)
                }

                fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) =
                    apply {
                        this.additionalProperties.putAll(additionalProperties)
                    }

                fun removeAdditionalProperty(key: String) = apply {
                    additionalProperties.remove(key)
                }

                fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                    keys.forEach(::removeAdditionalProperty)
                }

                /**
                 * Returns an immutable instance of [Action].
                 *
                 * Further updates to this [Builder] will not mutate the returned instance.
                 *
                 * The following fields are required:
                 * ```java
                 * .command()
                 * .env()
                 * ```
                 *
                 * @throws IllegalStateException if any required field is unset.
                 */
                fun build(): Action =
                    Action(
                        checkRequired("command", command).map { it.toImmutable() },
                        checkRequired("env", env),
                        type,
                        timeoutMs,
                        user,
                        workingDirectory,
                        additionalProperties.toMutableMap(),
                    )
            }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Action = apply {
                if (validated) {
                    return@apply
                }

                command()
                env().validate()
                _type().let {
                    if (it != JsonValue.from("exec")) {
                        throw OpenAIInvalidDataException("'type' is invalid, received $it")
                    }
                }
                timeoutMs()
                user()
                workingDirectory()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic
            internal fun validity(): Int =
                (command.asKnown().getOrNull()?.size ?: 0) +
                    (env.asKnown().getOrNull()?.validity() ?: 0) +
                    type.let { if (it == JsonValue.from("exec")) 1 else 0 } +
                    (if (timeoutMs.asKnown().isPresent) 1 else 0) +
                    (if (user.asKnown().isPresent) 1 else 0) +
                    (if (workingDirectory.asKnown().isPresent) 1 else 0)

            /** Environment variables to set for the command. */
            class Env
            @JsonCreator
            private constructor(
                @com.fasterxml.jackson.annotation.JsonValue
                private val additionalProperties: Map<String, JsonValue>
            ) {

                @JsonAnyGetter
                @ExcludeMissing
                fun _additionalProperties(): Map<String, JsonValue> = additionalProperties

                fun toBuilder() = Builder().from(this)

                companion object {

                    /** Returns a mutable builder for constructing an instance of [Env]. */
                    @JvmStatic fun builder() = Builder()
                }

                /** A builder for [Env]. */
                class Builder internal constructor() {

                    private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                    @JvmSynthetic
                    internal fun from(env: Env) = apply {
                        additionalProperties = env.additionalProperties.toMutableMap()
                    }

                    fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                        this.additionalProperties.clear()
                        putAllAdditionalProperties(additionalProperties)
                    }

                    fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                        additionalProperties.put(key, value)
                    }

                    fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) =
                        apply {
                            this.additionalProperties.putAll(additionalProperties)
                        }

                    fun removeAdditionalProperty(key: String) = apply {
                        additionalProperties.remove(key)
                    }

                    fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                        keys.forEach(::removeAdditionalProperty)
                    }

                    /**
                     * Returns an immutable instance of [Env].
                     *
                     * Further updates to this [Builder] will not mutate the returned instance.
                     */
                    fun build(): Env = Env(additionalProperties.toImmutable())
                }

                private var validated: Boolean = false

                /**
                 * Validates that the types of all values in this object match their expected types
                 * recursively.
                 *
                 * This method is _not_ forwards compatible with new types from the API for existing
                 * fields.
                 *
                 * @throws OpenAIInvalidDataException if any value type in this object doesn't match
                 *   its expected type.
                 */
                fun validate(): Env = apply {
                    if (validated) {
                        return@apply
                    }

                    validated = true
                }

                fun isValid(): Boolean =
                    try {
                        validate()
                        true
                    } catch (e: OpenAIInvalidDataException) {
                        false
                    }

                /**
                 * Returns a score indicating how many valid values are contained in this object
                 * recursively.
                 *
                 * Used for best match union deserialization.
                 */
                @JvmSynthetic
                internal fun validity(): Int =
                    additionalProperties.count { (_, value) ->
                        !value.isNull() && !value.isMissing()
                    }

                override fun equals(other: Any?): Boolean {
                    if (this === other) {
                        return true
                    }

                    return other is Env && additionalProperties == other.additionalProperties
                }

                private val hashCode: Int by lazy { Objects.hash(additionalProperties) }

                override fun hashCode(): Int = hashCode

                override fun toString() = "Env{additionalProperties=$additionalProperties}"
            }

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Action &&
                    command == other.command &&
                    env == other.env &&
                    type == other.type &&
                    timeoutMs == other.timeoutMs &&
                    user == other.user &&
                    workingDirectory == other.workingDirectory &&
                    additionalProperties == other.additionalProperties
            }

            private val hashCode: Int by lazy {
                Objects.hash(
                    command,
                    env,
                    type,
                    timeoutMs,
                    user,
                    workingDirectory,
                    additionalProperties,
                )
            }

            override fun hashCode(): Int = hashCode

            override fun toString() =
                "Action{command=$command, env=$env, type=$type, timeoutMs=$timeoutMs, user=$user, workingDirectory=$workingDirectory, additionalProperties=$additionalProperties}"
        }

        /** The status of the local shell call. */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val INCOMPLETE = of("incomplete")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    INCOMPLETE -> Value.INCOMPLETE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    INCOMPLETE -> Known.INCOMPLETE
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is LocalShellCall &&
                id == other.id &&
                action == other.action &&
                callId == other.callId &&
                status == other.status &&
                type == other.type &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(id, action, callId, status, type, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "LocalShellCall{id=$id, action=$action, callId=$callId, status=$status, type=$type, additionalProperties=$additionalProperties}"
    }

    /** The output of a local shell tool call. */
    class LocalShellCallOutput
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val id: JsonField<String>,
        private val output: JsonField<String>,
        private val type: JsonValue,
        private val status: JsonField<Status>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("output") @ExcludeMissing output: JsonField<String> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
        ) : this(id, output, type, status, mutableMapOf())

        /**
         * The unique ID of the local shell tool call generated by the model.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun id(): String = id.getRequired("id")

        /**
         * A JSON string of the output of the local shell tool call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun output(): String = output.getRequired("output")

        /**
         * The type of the local shell tool call output. Always `local_shell_call_output`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("local_shell_call_output")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The status of the item. One of `in_progress`, `completed`, or `incomplete`.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun status(): Optional<Status> = status.getOptional("status")

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [output].
         *
         * Unlike [output], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("output") @ExcludeMissing fun _output(): JsonField<String> = output

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [LocalShellCallOutput].
             *
             * The following fields are required:
             * ```java
             * .id()
             * .output()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [LocalShellCallOutput]. */
        class Builder internal constructor() {

            private var id: JsonField<String>? = null
            private var output: JsonField<String>? = null
            private var type: JsonValue = JsonValue.from("local_shell_call_output")
            private var status: JsonField<Status> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(localShellCallOutput: LocalShellCallOutput) = apply {
                id = localShellCallOutput.id
                output = localShellCallOutput.output
                type = localShellCallOutput.type
                status = localShellCallOutput.status
                additionalProperties = localShellCallOutput.additionalProperties.toMutableMap()
            }

            /** The unique ID of the local shell tool call generated by the model. */
            fun id(id: String) = id(JsonField.of(id))

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** A JSON string of the output of the local shell tool call. */
            fun output(output: String) = output(JsonField.of(output))

            /**
             * Sets [Builder.output] to an arbitrary JSON value.
             *
             * You should usually call [Builder.output] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun output(output: JsonField<String>) = apply { this.output = output }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("local_shell_call_output")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /** The status of the item. One of `in_progress`, `completed`, or `incomplete`. */
            fun status(status: Status?) = status(JsonField.ofNullable(status))

            /** Alias for calling [Builder.status] with `status.orElse(null)`. */
            fun status(status: Optional<Status>) = status(status.getOrNull())

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [LocalShellCallOutput].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .id()
             * .output()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): LocalShellCallOutput =
                LocalShellCallOutput(
                    checkRequired("id", id),
                    checkRequired("output", output),
                    type,
                    status,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): LocalShellCallOutput = apply {
            if (validated) {
                return@apply
            }

            id()
            output()
            _type().let {
                if (it != JsonValue.from("local_shell_call_output")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            status().ifPresent { it.validate() }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (id.asKnown().isPresent) 1 else 0) +
                (if (output.asKnown().isPresent) 1 else 0) +
                type.let { if (it == JsonValue.from("local_shell_call_output")) 1 else 0 } +
                (status.asKnown().getOrNull()?.validity() ?: 0)

        /** The status of the item. One of `in_progress`, `completed`, or `incomplete`. */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val INCOMPLETE = of("incomplete")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    INCOMPLETE -> Value.INCOMPLETE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    INCOMPLETE -> Known.INCOMPLETE
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is LocalShellCallOutput &&
                id == other.id &&
                output == other.output &&
                type == other.type &&
                status == other.status &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(id, output, type, status, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "LocalShellCallOutput{id=$id, output=$output, type=$type, status=$status, additionalProperties=$additionalProperties}"
    }

    /** A tool representing a request to execute one or more shell commands. */
    class ShellCall
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val action: JsonField<Action>,
        private val callId: JsonField<String>,
        private val type: JsonValue,
        private val id: JsonField<String>,
        private val environment: JsonField<Environment>,
        private val status: JsonField<Status>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("action") @ExcludeMissing action: JsonField<Action> = JsonMissing.of(),
            @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("environment")
            @ExcludeMissing
            environment: JsonField<Environment> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
        ) : this(action, callId, type, id, environment, status, mutableMapOf())

        /**
         * The shell commands and limits that describe how to run the tool call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun action(): Action = action.getRequired("action")

        /**
         * The unique ID of the shell tool call generated by the model.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun callId(): String = callId.getRequired("call_id")

        /**
         * The type of the item. Always `shell_call`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("shell_call")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The unique ID of the shell tool call. Populated when this item is returned via API.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun id(): Optional<String> = id.getOptional("id")

        /**
         * The environment to execute the shell commands in.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun environment(): Optional<Environment> = environment.getOptional("environment")

        /**
         * The status of the shell call. One of `in_progress`, `completed`, or `incomplete`.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun status(): Optional<Status> = status.getOptional("status")

        /**
         * Returns the raw JSON value of [action].
         *
         * Unlike [action], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("action") @ExcludeMissing fun _action(): JsonField<Action> = action

        /**
         * Returns the raw JSON value of [callId].
         *
         * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField<String> = callId

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [environment].
         *
         * Unlike [environment], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("environment")
        @ExcludeMissing
        fun _environment(): JsonField<Environment> = environment

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [ShellCall].
             *
             * The following fields are required:
             * ```java
             * .action()
             * .callId()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [ShellCall]. */
        class Builder internal constructor() {

            private var action: JsonField<Action>? = null
            private var callId: JsonField<String>? = null
            private var type: JsonValue = JsonValue.from("shell_call")
            private var id: JsonField<String> = JsonMissing.of()
            private var environment: JsonField<Environment> = JsonMissing.of()
            private var status: JsonField<Status> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(shellCall: ShellCall) = apply {
                action = shellCall.action
                callId = shellCall.callId
                type = shellCall.type
                id = shellCall.id
                environment = shellCall.environment
                status = shellCall.status
                additionalProperties = shellCall.additionalProperties.toMutableMap()
            }

            /** The shell commands and limits that describe how to run the tool call. */
            fun action(action: Action) = action(JsonField.of(action))

            /**
             * Sets [Builder.action] to an arbitrary JSON value.
             *
             * You should usually call [Builder.action] with a well-typed [Action] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun action(action: JsonField<Action>) = apply { this.action = action }

            /** The unique ID of the shell tool call generated by the model. */
            fun callId(callId: String) = callId(JsonField.of(callId))

            /**
             * Sets [Builder.callId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.callId] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun callId(callId: JsonField<String>) = apply { this.callId = callId }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("shell_call")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /**
             * The unique ID of the shell tool call. Populated when this item is returned via API.
             */
            fun id(id: String?) = id(JsonField.ofNullable(id))

            /** Alias for calling [Builder.id] with `id.orElse(null)`. */
            fun id(id: Optional<String>) = id(id.getOrNull())

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** The environment to execute the shell commands in. */
            fun environment(environment: Environment?) =
                environment(JsonField.ofNullable(environment))

            /** Alias for calling [Builder.environment] with `environment.orElse(null)`. */
            fun environment(environment: Optional<Environment>) =
                environment(environment.getOrNull())

            /**
             * Sets [Builder.environment] to an arbitrary JSON value.
             *
             * You should usually call [Builder.environment] with a well-typed [Environment] value
             * instead. This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun environment(environment: JsonField<Environment>) = apply {
                this.environment = environment
            }

            /** Alias for calling [environment] with `Environment.ofLocal(local)`. */
            fun environment(local: LocalEnvironment) = environment(Environment.ofLocal(local))

            /**
             * Alias for calling [environment] with
             * `Environment.ofContainerReference(containerReference)`.
             */
            fun environment(containerReference: ContainerReference) =
                environment(Environment.ofContainerReference(containerReference))

            /**
             * Alias for calling [environment] with the following:
             * ```java
             * ContainerReference.builder()
             *     .containerId(containerId)
             *     .build()
             * ```
             */
            fun containerReferenceEnvironment(containerId: String) =
                environment(ContainerReference.builder().containerId(containerId).build())

            /** The status of the shell call. One of `in_progress`, `completed`, or `incomplete`. */
            fun status(status: Status?) = status(JsonField.ofNullable(status))

            /** Alias for calling [Builder.status] with `status.orElse(null)`. */
            fun status(status: Optional<Status>) = status(status.getOrNull())

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [ShellCall].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .action()
             * .callId()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): ShellCall =
                ShellCall(
                    checkRequired("action", action),
                    checkRequired("callId", callId),
                    type,
                    id,
                    environment,
                    status,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): ShellCall = apply {
            if (validated) {
                return@apply
            }

            action().validate()
            callId()
            _type().let {
                if (it != JsonValue.from("shell_call")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            id()
            environment().ifPresent { it.validate() }
            status().ifPresent { it.validate() }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (action.asKnown().getOrNull()?.validity() ?: 0) +
                (if (callId.asKnown().isPresent) 1 else 0) +
                type.let { if (it == JsonValue.from("shell_call")) 1 else 0 } +
                (if (id.asKnown().isPresent) 1 else 0) +
                (environment.asKnown().getOrNull()?.validity() ?: 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0)

        /** The shell commands and limits that describe how to run the tool call. */
        class Action
        @JsonCreator(mode = JsonCreator.Mode.DISABLED)
        private constructor(
            private val commands: JsonField<List<String>>,
            private val maxOutputLength: JsonField<Long>,
            private val timeoutMs: JsonField<Long>,
            private val additionalProperties: MutableMap<String, JsonValue>,
        ) {

            @JsonCreator
            private constructor(
                @JsonProperty("commands")
                @ExcludeMissing
                commands: JsonField<List<String>> = JsonMissing.of(),
                @JsonProperty("max_output_length")
                @ExcludeMissing
                maxOutputLength: JsonField<Long> = JsonMissing.of(),
                @JsonProperty("timeout_ms")
                @ExcludeMissing
                timeoutMs: JsonField<Long> = JsonMissing.of(),
            ) : this(commands, maxOutputLength, timeoutMs, mutableMapOf())

            /**
             * Ordered shell commands for the execution environment to run.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
             *   unexpectedly missing or null (e.g. if the server responded with an unexpected
             *   value).
             */
            fun commands(): List<String> = commands.getRequired("commands")

            /**
             * Maximum number of UTF-8 characters to capture from combined stdout and stderr output.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if
             *   the server responded with an unexpected value).
             */
            fun maxOutputLength(): Optional<Long> = maxOutputLength.getOptional("max_output_length")

            /**
             * Maximum wall-clock time in milliseconds to allow the shell commands to run.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if
             *   the server responded with an unexpected value).
             */
            fun timeoutMs(): Optional<Long> = timeoutMs.getOptional("timeout_ms")

            /**
             * Returns the raw JSON value of [commands].
             *
             * Unlike [commands], this method doesn't throw if the JSON field has an unexpected
             * type.
             */
            @JsonProperty("commands")
            @ExcludeMissing
            fun _commands(): JsonField<List<String>> = commands

            /**
             * Returns the raw JSON value of [maxOutputLength].
             *
             * Unlike [maxOutputLength], this method doesn't throw if the JSON field has an
             * unexpected type.
             */
            @JsonProperty("max_output_length")
            @ExcludeMissing
            fun _maxOutputLength(): JsonField<Long> = maxOutputLength

            /**
             * Returns the raw JSON value of [timeoutMs].
             *
             * Unlike [timeoutMs], this method doesn't throw if the JSON field has an unexpected
             * type.
             */
            @JsonProperty("timeout_ms")
            @ExcludeMissing
            fun _timeoutMs(): JsonField<Long> = timeoutMs

            @JsonAnySetter
            private fun putAdditionalProperty(key: String, value: JsonValue) {
                additionalProperties.put(key, value)
            }

            @JsonAnyGetter
            @ExcludeMissing
            fun _additionalProperties(): Map<String, JsonValue> =
                Collections.unmodifiableMap(additionalProperties)

            fun toBuilder() = Builder().from(this)

            companion object {

                /**
                 * Returns a mutable builder for constructing an instance of [Action].
                 *
                 * The following fields are required:
                 * ```java
                 * .commands()
                 * ```
                 */
                @JvmStatic fun builder() = Builder()
            }

            /** A builder for [Action]. */
            class Builder internal constructor() {

                private var commands: JsonField<MutableList<String>>? = null
                private var maxOutputLength: JsonField<Long> = JsonMissing.of()
                private var timeoutMs: JsonField<Long> = JsonMissing.of()
                private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                @JvmSynthetic
                internal fun from(action: Action) = apply {
                    commands = action.commands.map { it.toMutableList() }
                    maxOutputLength = action.maxOutputLength
                    timeoutMs = action.timeoutMs
                    additionalProperties = action.additionalProperties.toMutableMap()
                }

                /** Ordered shell commands for the execution environment to run. */
                fun commands(commands: List<String>) = commands(JsonField.of(commands))

                /**
                 * Sets [Builder.commands] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.commands] with a well-typed `List<String>` value
                 * instead. This method is primarily for setting the field to an undocumented or not
                 * yet supported value.
                 */
                fun commands(commands: JsonField<List<String>>) = apply {
                    this.commands = commands.map { it.toMutableList() }
                }

                /**
                 * Adds a single [String] to [commands].
                 *
                 * @throws IllegalStateException if the field was previously set to a non-list.
                 */
                fun addCommand(command: String) = apply {
                    commands =
                        (commands ?: JsonField.of(mutableListOf())).also {
                            checkKnown("commands", it).add(command)
                        }
                }

                /**
                 * Maximum number of UTF-8 characters to capture from combined stdout and stderr
                 * output.
                 */
                fun maxOutputLength(maxOutputLength: Long?) =
                    maxOutputLength(JsonField.ofNullable(maxOutputLength))

                /**
                 * Alias for [Builder.maxOutputLength].
                 *
                 * This unboxed primitive overload exists for backwards compatibility.
                 */
                fun maxOutputLength(maxOutputLength: Long) =
                    maxOutputLength(maxOutputLength as Long?)

                /**
                 * Alias for calling [Builder.maxOutputLength] with `maxOutputLength.orElse(null)`.
                 */
                fun maxOutputLength(maxOutputLength: Optional<Long>) =
                    maxOutputLength(maxOutputLength.getOrNull())

                /**
                 * Sets [Builder.maxOutputLength] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.maxOutputLength] with a well-typed [Long] value
                 * instead. This method is primarily for setting the field to an undocumented or not
                 * yet supported value.
                 */
                fun maxOutputLength(maxOutputLength: JsonField<Long>) = apply {
                    this.maxOutputLength = maxOutputLength
                }

                /** Maximum wall-clock time in milliseconds to allow the shell commands to run. */
                fun timeoutMs(timeoutMs: Long?) = timeoutMs(JsonField.ofNullable(timeoutMs))

                /**
                 * Alias for [Builder.timeoutMs].
                 *
                 * This unboxed primitive overload exists for backwards compatibility.
                 */
                fun timeoutMs(timeoutMs: Long) = timeoutMs(timeoutMs as Long?)

                /** Alias for calling [Builder.timeoutMs] with `timeoutMs.orElse(null)`. */
                fun timeoutMs(timeoutMs: Optional<Long>) = timeoutMs(timeoutMs.getOrNull())

                /**
                 * Sets [Builder.timeoutMs] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.timeoutMs] with a well-typed [Long] value
                 * instead. This method is primarily for setting the field to an undocumented or not
                 * yet supported value.
                 */
                fun timeoutMs(timeoutMs: JsonField<Long>) = apply { this.timeoutMs = timeoutMs }

                fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                    this.additionalProperties.clear()
                    putAllAdditionalProperties(additionalProperties)
                }

                fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                    additionalProperties.put(key, value)
                }

                fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) =
                    apply {
                        this.additionalProperties.putAll(additionalProperties)
                    }

                fun removeAdditionalProperty(key: String) = apply {
                    additionalProperties.remove(key)
                }

                fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                    keys.forEach(::removeAdditionalProperty)
                }

                /**
                 * Returns an immutable instance of [Action].
                 *
                 * Further updates to this [Builder] will not mutate the returned instance.
                 *
                 * The following fields are required:
                 * ```java
                 * .commands()
                 * ```
                 *
                 * @throws IllegalStateException if any required field is unset.
                 */
                fun build(): Action =
                    Action(
                        checkRequired("commands", commands).map { it.toImmutable() },
                        maxOutputLength,
                        timeoutMs,
                        additionalProperties.toMutableMap(),
                    )
            }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Action = apply {
                if (validated) {
                    return@apply
                }

                commands()
                maxOutputLength()
                timeoutMs()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic
            internal fun validity(): Int =
                (commands.asKnown().getOrNull()?.size ?: 0) +
                    (if (maxOutputLength.asKnown().isPresent) 1 else 0) +
                    (if (timeoutMs.asKnown().isPresent) 1 else 0)

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Action &&
                    commands == other.commands &&
                    maxOutputLength == other.maxOutputLength &&
                    timeoutMs == other.timeoutMs &&
                    additionalProperties == other.additionalProperties
            }

            private val hashCode: Int by lazy {
                Objects.hash(commands, maxOutputLength, timeoutMs, additionalProperties)
            }

            override fun hashCode(): Int = hashCode

            override fun toString() =
                "Action{commands=$commands, maxOutputLength=$maxOutputLength, timeoutMs=$timeoutMs, additionalProperties=$additionalProperties}"
        }

        /** The environment to execute the shell commands in. */
        @JsonDeserialize(using = Environment.Deserializer::class)
        @JsonSerialize(using = Environment.Serializer::class)
        class Environment
        private constructor(
            private val local: LocalEnvironment? = null,
            private val containerReference: ContainerReference? = null,
            private val _json: JsonValue? = null,
        ) {

            fun local(): Optional<LocalEnvironment> = Optional.ofNullable(local)

            fun containerReference(): Optional<ContainerReference> =
                Optional.ofNullable(containerReference)

            fun isLocal(): Boolean = local != null

            fun isContainerReference(): Boolean = containerReference != null

            fun asLocal(): LocalEnvironment = local.getOrThrow("local")

            fun asContainerReference(): ContainerReference =
                containerReference.getOrThrow("containerReference")

            fun _json(): Optional<JsonValue> = Optional.ofNullable(_json)

            /**
             * Maps this instance's current variant to a value of type [T] using the given
             * [visitor].
             *
             * Note that this method is _not_ forwards compatible with new variants from the API,
             * unless [visitor] overrides [Visitor.unknown]. To handle variants not known to this
             * version of the SDK gracefully, consider overriding [Visitor.unknown]:
             * ```java
             * import com.openai.core.JsonValue;
             * import java.util.Optional;
             *
             * Optional<String> result = environment.accept(new Environment.Visitor<Optional<String>>() {
             *     @Override
             *     public Optional<String> visitLocal(LocalEnvironment local) {
             *         return Optional.of(local.toString());
             *     }
             *
             *     // ...
             *
             *     @Override
             *     public Optional<String> unknown(JsonValue json) {
             *         // Or inspect the `json`.
             *         return Optional.empty();
             *     }
             * });
             * ```
             *
             * @throws OpenAIInvalidDataException if [Visitor.unknown] is not overridden in
             *   [visitor] and the current variant is unknown.
             */
            fun <T> accept(visitor: Visitor<T>): T =
                when {
                    local != null -> visitor.visitLocal(local)
                    containerReference != null ->
                        visitor.visitContainerReference(containerReference)
                    else -> visitor.unknown(_json)
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Environment = apply {
                if (validated) {
                    return@apply
                }

                accept(
                    object : Visitor<Unit> {
                        override fun visitLocal(local: LocalEnvironment) {
                            local.validate()
                        }

                        override fun visitContainerReference(
                            containerReference: ContainerReference
                        ) {
                            containerReference.validate()
                        }
                    }
                )
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic
            internal fun validity(): Int =
                accept(
                    object : Visitor<Int> {
                        override fun visitLocal(local: LocalEnvironment) = local.validity()

                        override fun visitContainerReference(
                            containerReference: ContainerReference
                        ) = containerReference.validity()

                        override fun unknown(json: JsonValue?) = 0
                    }
                )

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Environment &&
                    local == other.local &&
                    containerReference == other.containerReference
            }

            override fun hashCode(): Int = Objects.hash(local, containerReference)

            override fun toString(): String =
                when {
                    local != null -> "Environment{local=$local}"
                    containerReference != null ->
                        "Environment{containerReference=$containerReference}"
                    _json != null -> "Environment{_unknown=$_json}"
                    else -> throw IllegalStateException("Invalid Environment")
                }

            companion object {

                @JvmStatic fun ofLocal(local: LocalEnvironment) = Environment(local = local)

                @JvmStatic
                fun ofContainerReference(containerReference: ContainerReference) =
                    Environment(containerReference = containerReference)
            }

            /**
             * An interface that defines how to map each variant of [Environment] to a value of type
             * [T].
             */
            interface Visitor<out T> {

                fun visitLocal(local: LocalEnvironment): T

                fun visitContainerReference(containerReference: ContainerReference): T

                /**
                 * Maps an unknown variant of [Environment] to a value of type [T].
                 *
                 * An instance of [Environment] can contain an unknown variant if it was
                 * deserialized from data that doesn't match any known variant. For example, if the
                 * SDK is on an older version than the API, then the API may respond with new
                 * variants that the SDK is unaware of.
                 *
                 * @throws OpenAIInvalidDataException in the default implementation.
                 */
                fun unknown(json: JsonValue?): T {
                    throw OpenAIInvalidDataException("Unknown Environment: $json")
                }
            }

            internal class Deserializer : BaseDeserializer<Environment>(Environment::class) {

                override fun ObjectCodec.deserialize(node: JsonNode): Environment {
                    val json = JsonValue.fromJsonNode(node)
                    val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull()

                    when (type) {
                        "local" -> {
                            return tryDeserialize(node, jacksonTypeRef<LocalEnvironment>())?.let {
                                Environment(local = it, _json = json)
                            } ?: Environment(_json = json)
                        }
                        "container_reference" -> {
                            return tryDeserialize(node, jacksonTypeRef<ContainerReference>())?.let {
                                Environment(containerReference = it, _json = json)
                            } ?: Environment(_json = json)
                        }
                    }

                    return Environment(_json = json)
                }
            }

            internal class Serializer : BaseSerializer<Environment>(Environment::class) {

                override fun serialize(
                    value: Environment,
                    generator: JsonGenerator,
                    provider: SerializerProvider,
                ) {
                    when {
                        value.local != null -> generator.writeObject(value.local)
                        value.containerReference != null ->
                            generator.writeObject(value.containerReference)
                        value._json != null -> generator.writeObject(value._json)
                        else -> throw IllegalStateException("Invalid Environment")
                    }
                }
            }
        }

        /** The status of the shell call. One of `in_progress`, `completed`, or `incomplete`. */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val INCOMPLETE = of("incomplete")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    INCOMPLETE -> Value.INCOMPLETE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    INCOMPLETE -> Known.INCOMPLETE
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is ShellCall &&
                action == other.action &&
                callId == other.callId &&
                type == other.type &&
                id == other.id &&
                environment == other.environment &&
                status == other.status &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(action, callId, type, id, environment, status, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "ShellCall{action=$action, callId=$callId, type=$type, id=$id, environment=$environment, status=$status, additionalProperties=$additionalProperties}"
    }

    /** The streamed output items emitted by a shell tool call. */
    class ShellCallOutput
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val callId: JsonField<String>,
        private val output: JsonField<List<ResponseFunctionShellCallOutputContent>>,
        private val type: JsonValue,
        private val id: JsonField<String>,
        private val maxOutputLength: JsonField<Long>,
        private val status: JsonField<Status>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("output")
            @ExcludeMissing
            output: JsonField<List<ResponseFunctionShellCallOutputContent>> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("max_output_length")
            @ExcludeMissing
            maxOutputLength: JsonField<Long> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
        ) : this(callId, output, type, id, maxOutputLength, status, mutableMapOf())

        /**
         * The unique ID of the shell tool call generated by the model.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun callId(): String = callId.getRequired("call_id")

        /**
         * Captured chunks of stdout and stderr output, along with their associated outcomes.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun output(): List<ResponseFunctionShellCallOutputContent> = output.getRequired("output")

        /**
         * The type of the item. Always `shell_call_output`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("shell_call_output")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The unique ID of the shell tool call output. Populated when this item is returned via
         * API.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun id(): Optional<String> = id.getOptional("id")

        /**
         * The maximum number of UTF-8 characters captured for this shell call's combined output.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun maxOutputLength(): Optional<Long> = maxOutputLength.getOptional("max_output_length")

        /**
         * The status of the shell call output.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun status(): Optional<Status> = status.getOptional("status")

        /**
         * Returns the raw JSON value of [callId].
         *
         * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField<String> = callId

        /**
         * Returns the raw JSON value of [output].
         *
         * Unlike [output], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("output")
        @ExcludeMissing
        fun _output(): JsonField<List<ResponseFunctionShellCallOutputContent>> = output

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [maxOutputLength].
         *
         * Unlike [maxOutputLength], this method doesn't throw if the JSON field has an unexpected
         * type.
         */
        @JsonProperty("max_output_length")
        @ExcludeMissing
        fun _maxOutputLength(): JsonField<Long> = maxOutputLength

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [ShellCallOutput].
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .output()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [ShellCallOutput]. */
        class Builder internal constructor() {

            private var callId: JsonField<String>? = null
            private var output: JsonField<MutableList<ResponseFunctionShellCallOutputContent>>? =
                null
            private var type: JsonValue = JsonValue.from("shell_call_output")
            private var id: JsonField<String> = JsonMissing.of()
            private var maxOutputLength: JsonField<Long> = JsonMissing.of()
            private var status: JsonField<Status> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(shellCallOutput: ShellCallOutput) = apply {
                callId = shellCallOutput.callId
                output = shellCallOutput.output.map { it.toMutableList() }
                type = shellCallOutput.type
                id = shellCallOutput.id
                maxOutputLength = shellCallOutput.maxOutputLength
                status = shellCallOutput.status
                additionalProperties = shellCallOutput.additionalProperties.toMutableMap()
            }

            /** The unique ID of the shell tool call generated by the model. */
            fun callId(callId: String) = callId(JsonField.of(callId))

            /**
             * Sets [Builder.callId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.callId] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun callId(callId: JsonField<String>) = apply { this.callId = callId }

            /**
             * Captured chunks of stdout and stderr output, along with their associated outcomes.
             */
            fun output(output: List<ResponseFunctionShellCallOutputContent>) =
                output(JsonField.of(output))

            /**
             * Sets [Builder.output] to an arbitrary JSON value.
             *
             * You should usually call [Builder.output] with a well-typed
             * `List<ResponseFunctionShellCallOutputContent>` value instead. This method is
             * primarily for setting the field to an undocumented or not yet supported value.
             */
            fun output(output: JsonField<List<ResponseFunctionShellCallOutputContent>>) = apply {
                this.output = output.map { it.toMutableList() }
            }

            /**
             * Adds a single [ResponseFunctionShellCallOutputContent] to [Builder.output].
             *
             * @throws IllegalStateException if the field was previously set to a non-list.
             */
            fun addOutput(output: ResponseFunctionShellCallOutputContent) = apply {
                this.output =
                    (this.output ?: JsonField.of(mutableListOf())).also {
                        checkKnown("output", it).add(output)
                    }
            }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("shell_call_output")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /**
             * The unique ID of the shell tool call output. Populated when this item is returned via
             * API.
             */
            fun id(id: String?) = id(JsonField.ofNullable(id))

            /** Alias for calling [Builder.id] with `id.orElse(null)`. */
            fun id(id: Optional<String>) = id(id.getOrNull())

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /**
             * The maximum number of UTF-8 characters captured for this shell call's combined
             * output.
             */
            fun maxOutputLength(maxOutputLength: Long?) =
                maxOutputLength(JsonField.ofNullable(maxOutputLength))

            /**
             * Alias for [Builder.maxOutputLength].
             *
             * This unboxed primitive overload exists for backwards compatibility.
             */
            fun maxOutputLength(maxOutputLength: Long) = maxOutputLength(maxOutputLength as Long?)

            /** Alias for calling [Builder.maxOutputLength] with `maxOutputLength.orElse(null)`. */
            fun maxOutputLength(maxOutputLength: Optional<Long>) =
                maxOutputLength(maxOutputLength.getOrNull())

            /**
             * Sets [Builder.maxOutputLength] to an arbitrary JSON value.
             *
             * You should usually call [Builder.maxOutputLength] with a well-typed [Long] value
             * instead. This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun maxOutputLength(maxOutputLength: JsonField<Long>) = apply {
                this.maxOutputLength = maxOutputLength
            }

            /** The status of the shell call output. */
            fun status(status: Status?) = status(JsonField.ofNullable(status))

            /** Alias for calling [Builder.status] with `status.orElse(null)`. */
            fun status(status: Optional<Status>) = status(status.getOrNull())

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [ShellCallOutput].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .output()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): ShellCallOutput =
                ShellCallOutput(
                    checkRequired("callId", callId),
                    checkRequired("output", output).map { it.toImmutable() },
                    type,
                    id,
                    maxOutputLength,
                    status,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): ShellCallOutput = apply {
            if (validated) {
                return@apply
            }

            callId()
            output().forEach { it.validate() }
            _type().let {
                if (it != JsonValue.from("shell_call_output")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            id()
            maxOutputLength()
            status().ifPresent { it.validate() }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (callId.asKnown().isPresent) 1 else 0) +
                (output.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) +
                type.let { if (it == JsonValue.from("shell_call_output")) 1 else 0 } +
                (if (id.asKnown().isPresent) 1 else 0) +
                (if (maxOutputLength.asKnown().isPresent) 1 else 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0)

        /** The status of the shell call output. */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val INCOMPLETE = of("incomplete")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    INCOMPLETE -> Value.INCOMPLETE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    INCOMPLETE -> Known.INCOMPLETE
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is ShellCallOutput &&
                callId == other.callId &&
                output == other.output &&
                type == other.type &&
                id == other.id &&
                maxOutputLength == other.maxOutputLength &&
                status == other.status &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(callId, output, type, id, maxOutputLength, status, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "ShellCallOutput{callId=$callId, output=$output, type=$type, id=$id, maxOutputLength=$maxOutputLength, status=$status, additionalProperties=$additionalProperties}"
    }

    /** A tool call representing a request to create, delete, or update files using diff patches. */
    class ApplyPatchCall
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val callId: JsonField<String>,
        private val operation: JsonField<Operation>,
        private val status: JsonField<Status>,
        private val type: JsonValue,
        private val id: JsonField<String>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("operation")
            @ExcludeMissing
            operation: JsonField<Operation> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
        ) : this(callId, operation, status, type, id, mutableMapOf())

        /**
         * The unique ID of the apply patch tool call generated by the model.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun callId(): String = callId.getRequired("call_id")

        /**
         * The specific create, delete, or update instruction for the apply_patch tool call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun operation(): Operation = operation.getRequired("operation")

        /**
         * The status of the apply patch tool call. One of `in_progress` or `completed`.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun status(): Status = status.getRequired("status")

        /**
         * The type of the item. Always `apply_patch_call`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("apply_patch_call")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The unique ID of the apply patch tool call. Populated when this item is returned via API.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun id(): Optional<String> = id.getOptional("id")

        /**
         * Returns the raw JSON value of [callId].
         *
         * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField<String> = callId

        /**
         * Returns the raw JSON value of [operation].
         *
         * Unlike [operation], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("operation")
        @ExcludeMissing
        fun _operation(): JsonField<Operation> = operation

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [ApplyPatchCall].
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .operation()
             * .status()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [ApplyPatchCall]. */
        class Builder internal constructor() {

            private var callId: JsonField<String>? = null
            private var operation: JsonField<Operation>? = null
            private var status: JsonField<Status>? = null
            private var type: JsonValue = JsonValue.from("apply_patch_call")
            private var id: JsonField<String> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(applyPatchCall: ApplyPatchCall) = apply {
                callId = applyPatchCall.callId
                operation = applyPatchCall.operation
                status = applyPatchCall.status
                type = applyPatchCall.type
                id = applyPatchCall.id
                additionalProperties = applyPatchCall.additionalProperties.toMutableMap()
            }

            /** The unique ID of the apply patch tool call generated by the model. */
            fun callId(callId: String) = callId(JsonField.of(callId))

            /**
             * Sets [Builder.callId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.callId] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun callId(callId: JsonField<String>) = apply { this.callId = callId }

            /** The specific create, delete, or update instruction for the apply_patch tool call. */
            fun operation(operation: Operation) = operation(JsonField.of(operation))

            /**
             * Sets [Builder.operation] to an arbitrary JSON value.
             *
             * You should usually call [Builder.operation] with a well-typed [Operation] value
             * instead. This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun operation(operation: JsonField<Operation>) = apply { this.operation = operation }

            /** Alias for calling [operation] with `Operation.ofCreateFile(createFile)`. */
            fun operation(createFile: Operation.CreateFile) =
                operation(Operation.ofCreateFile(createFile))

            /** Alias for calling [operation] with `Operation.ofDeleteFile(deleteFile)`. */
            fun operation(deleteFile: Operation.DeleteFile) =
                operation(Operation.ofDeleteFile(deleteFile))

            /**
             * Alias for calling [operation] with the following:
             * ```java
             * Operation.DeleteFile.builder()
             *     .path(path)
             *     .build()
             * ```
             */
            fun deleteFileOperation(path: String) =
                operation(Operation.DeleteFile.builder().path(path).build())

            /** Alias for calling [operation] with `Operation.ofUpdateFile(updateFile)`. */
            fun operation(updateFile: Operation.UpdateFile) =
                operation(Operation.ofUpdateFile(updateFile))

            /** The status of the apply patch tool call. One of `in_progress` or `completed`. */
            fun status(status: Status) = status(JsonField.of(status))

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("apply_patch_call")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /**
             * The unique ID of the apply patch tool call. Populated when this item is returned via
             * API.
             */
            fun id(id: String?) = id(JsonField.ofNullable(id))

            /** Alias for calling [Builder.id] with `id.orElse(null)`. */
            fun id(id: Optional<String>) = id(id.getOrNull())

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [ApplyPatchCall].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .operation()
             * .status()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): ApplyPatchCall =
                ApplyPatchCall(
                    checkRequired("callId", callId),
                    checkRequired("operation", operation),
                    checkRequired("status", status),
                    type,
                    id,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): ApplyPatchCall = apply {
            if (validated) {
                return@apply
            }

            callId()
            operation().validate()
            status().validate()
            _type().let {
                if (it != JsonValue.from("apply_patch_call")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            id()
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (callId.asKnown().isPresent) 1 else 0) +
                (operation.asKnown().getOrNull()?.validity() ?: 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0) +
                type.let { if (it == JsonValue.from("apply_patch_call")) 1 else 0 } +
                (if (id.asKnown().isPresent) 1 else 0)

        /** The specific create, delete, or update instruction for the apply_patch tool call. */
        @JsonDeserialize(using = Operation.Deserializer::class)
        @JsonSerialize(using = Operation.Serializer::class)
        class Operation
        private constructor(
            private val createFile: CreateFile? = null,
            private val deleteFile: DeleteFile? = null,
            private val updateFile: UpdateFile? = null,
            private val _json: JsonValue? = null,
        ) {

            /** Instruction for creating a new file via the apply_patch tool. */
            fun createFile(): Optional<CreateFile> = Optional.ofNullable(createFile)

            /** Instruction for deleting an existing file via the apply_patch tool. */
            fun deleteFile(): Optional<DeleteFile> = Optional.ofNullable(deleteFile)

            /** Instruction for updating an existing file via the apply_patch tool. */
            fun updateFile(): Optional<UpdateFile> = Optional.ofNullable(updateFile)

            fun isCreateFile(): Boolean = createFile != null

            fun isDeleteFile(): Boolean = deleteFile != null

            fun isUpdateFile(): Boolean = updateFile != null

            /** Instruction for creating a new file via the apply_patch tool. */
            fun asCreateFile(): CreateFile = createFile.getOrThrow("createFile")

            /** Instruction for deleting an existing file via the apply_patch tool. */
            fun asDeleteFile(): DeleteFile = deleteFile.getOrThrow("deleteFile")

            /** Instruction for updating an existing file via the apply_patch tool. */
            fun asUpdateFile(): UpdateFile = updateFile.getOrThrow("updateFile")

            fun _json(): Optional<JsonValue> = Optional.ofNullable(_json)

            /**
             * Maps this instance's current variant to a value of type [T] using the given
             * [visitor].
             *
             * Note that this method is _not_ forwards compatible with new variants from the API,
             * unless [visitor] overrides [Visitor.unknown]. To handle variants not known to this
             * version of the SDK gracefully, consider overriding [Visitor.unknown]:
             * ```java
             * import com.openai.core.JsonValue;
             * import java.util.Optional;
             *
             * Optional<String> result = operation.accept(new Operation.Visitor<Optional<String>>() {
             *     @Override
             *     public Optional<String> visitCreateFile(CreateFile createFile) {
             *         return Optional.of(createFile.toString());
             *     }
             *
             *     // ...
             *
             *     @Override
             *     public Optional<String> unknown(JsonValue json) {
             *         // Or inspect the `json`.
             *         return Optional.empty();
             *     }
             * });
             * ```
             *
             * @throws OpenAIInvalidDataException if [Visitor.unknown] is not overridden in
             *   [visitor] and the current variant is unknown.
             */
            fun <T> accept(visitor: Visitor<T>): T =
                when {
                    createFile != null -> visitor.visitCreateFile(createFile)
                    deleteFile != null -> visitor.visitDeleteFile(deleteFile)
                    updateFile != null -> visitor.visitUpdateFile(updateFile)
                    else -> visitor.unknown(_json)
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Operation = apply {
                if (validated) {
                    return@apply
                }

                accept(
                    object : Visitor<Unit> {
                        override fun visitCreateFile(createFile: CreateFile) {
                            createFile.validate()
                        }

                        override fun visitDeleteFile(deleteFile: DeleteFile) {
                            deleteFile.validate()
                        }

                        override fun visitUpdateFile(updateFile: UpdateFile) {
                            updateFile.validate()
                        }
                    }
                )
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic
            internal fun validity(): Int =
                accept(
                    object : Visitor<Int> {
                        override fun visitCreateFile(createFile: CreateFile) = createFile.validity()

                        override fun visitDeleteFile(deleteFile: DeleteFile) = deleteFile.validity()

                        override fun visitUpdateFile(updateFile: UpdateFile) = updateFile.validity()

                        override fun unknown(json: JsonValue?) = 0
                    }
                )

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Operation &&
                    createFile == other.createFile &&
                    deleteFile == other.deleteFile &&
                    updateFile == other.updateFile
            }

            override fun hashCode(): Int = Objects.hash(createFile, deleteFile, updateFile)

            override fun toString(): String =
                when {
                    createFile != null -> "Operation{createFile=$createFile}"
                    deleteFile != null -> "Operation{deleteFile=$deleteFile}"
                    updateFile != null -> "Operation{updateFile=$updateFile}"
                    _json != null -> "Operation{_unknown=$_json}"
                    else -> throw IllegalStateException("Invalid Operation")
                }

            companion object {

                /** Instruction for creating a new file via the apply_patch tool. */
                @JvmStatic
                fun ofCreateFile(createFile: CreateFile) = Operation(createFile = createFile)

                /** Instruction for deleting an existing file via the apply_patch tool. */
                @JvmStatic
                fun ofDeleteFile(deleteFile: DeleteFile) = Operation(deleteFile = deleteFile)

                /** Instruction for updating an existing file via the apply_patch tool. */
                @JvmStatic
                fun ofUpdateFile(updateFile: UpdateFile) = Operation(updateFile = updateFile)
            }

            /**
             * An interface that defines how to map each variant of [Operation] to a value of type
             * [T].
             */
            interface Visitor<out T> {

                /** Instruction for creating a new file via the apply_patch tool. */
                fun visitCreateFile(createFile: CreateFile): T

                /** Instruction for deleting an existing file via the apply_patch tool. */
                fun visitDeleteFile(deleteFile: DeleteFile): T

                /** Instruction for updating an existing file via the apply_patch tool. */
                fun visitUpdateFile(updateFile: UpdateFile): T

                /**
                 * Maps an unknown variant of [Operation] to a value of type [T].
                 *
                 * An instance of [Operation] can contain an unknown variant if it was deserialized
                 * from data that doesn't match any known variant. For example, if the SDK is on an
                 * older version than the API, then the API may respond with new variants that the
                 * SDK is unaware of.
                 *
                 * @throws OpenAIInvalidDataException in the default implementation.
                 */
                fun unknown(json: JsonValue?): T {
                    throw OpenAIInvalidDataException("Unknown Operation: $json")
                }
            }

            internal class Deserializer : BaseDeserializer<Operation>(Operation::class) {

                override fun ObjectCodec.deserialize(node: JsonNode): Operation {
                    val json = JsonValue.fromJsonNode(node)
                    val type = json.asObject().getOrNull()?.get("type")?.asString()?.getOrNull()

                    when (type) {
                        "create_file" -> {
                            return tryDeserialize(node, jacksonTypeRef<CreateFile>())?.let {
                                Operation(createFile = it, _json = json)
                            } ?: Operation(_json = json)
                        }
                        "delete_file" -> {
                            return tryDeserialize(node, jacksonTypeRef<DeleteFile>())?.let {
                                Operation(deleteFile = it, _json = json)
                            } ?: Operation(_json = json)
                        }
                        "update_file" -> {
                            return tryDeserialize(node, jacksonTypeRef<UpdateFile>())?.let {
                                Operation(updateFile = it, _json = json)
                            } ?: Operation(_json = json)
                        }
                    }

                    return Operation(_json = json)
                }
            }

            internal class Serializer : BaseSerializer<Operation>(Operation::class) {

                override fun serialize(
                    value: Operation,
                    generator: JsonGenerator,
                    provider: SerializerProvider,
                ) {
                    when {
                        value.createFile != null -> generator.writeObject(value.createFile)
                        value.deleteFile != null -> generator.writeObject(value.deleteFile)
                        value.updateFile != null -> generator.writeObject(value.updateFile)
                        value._json != null -> generator.writeObject(value._json)
                        else -> throw IllegalStateException("Invalid Operation")
                    }
                }
            }

            /** Instruction for creating a new file via the apply_patch tool. */
            class CreateFile
            @JsonCreator(mode = JsonCreator.Mode.DISABLED)
            private constructor(
                private val diff: JsonField<String>,
                private val path: JsonField<String>,
                private val type: JsonValue,
                private val additionalProperties: MutableMap<String, JsonValue>,
            ) {

                @JsonCreator
                private constructor(
                    @JsonProperty("diff")
                    @ExcludeMissing
                    diff: JsonField<String> = JsonMissing.of(),
                    @JsonProperty("path")
                    @ExcludeMissing
                    path: JsonField<String> = JsonMissing.of(),
                    @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
                ) : this(diff, path, type, mutableMapOf())

                /**
                 * Unified diff content to apply when creating the file.
                 *
                 * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
                 *   unexpectedly missing or null (e.g. if the server responded with an unexpected
                 *   value).
                 */
                fun diff(): String = diff.getRequired("diff")

                /**
                 * Path of the file to create relative to the workspace root.
                 *
                 * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
                 *   unexpectedly missing or null (e.g. if the server responded with an unexpected
                 *   value).
                 */
                fun path(): String = path.getRequired("path")

                /**
                 * The operation type. Always `create_file`.
                 *
                 * Expected to always return the following:
                 * ```java
                 * JsonValue.from("create_file")
                 * ```
                 *
                 * However, this method can be useful for debugging and logging (e.g. if the server
                 * responded with an unexpected value).
                 */
                @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

                /**
                 * Returns the raw JSON value of [diff].
                 *
                 * Unlike [diff], this method doesn't throw if the JSON field has an unexpected
                 * type.
                 */
                @JsonProperty("diff") @ExcludeMissing fun _diff(): JsonField<String> = diff

                /**
                 * Returns the raw JSON value of [path].
                 *
                 * Unlike [path], this method doesn't throw if the JSON field has an unexpected
                 * type.
                 */
                @JsonProperty("path") @ExcludeMissing fun _path(): JsonField<String> = path

                @JsonAnySetter
                private fun putAdditionalProperty(key: String, value: JsonValue) {
                    additionalProperties.put(key, value)
                }

                @JsonAnyGetter
                @ExcludeMissing
                fun _additionalProperties(): Map<String, JsonValue> =
                    Collections.unmodifiableMap(additionalProperties)

                fun toBuilder() = Builder().from(this)

                companion object {

                    /**
                     * Returns a mutable builder for constructing an instance of [CreateFile].
                     *
                     * The following fields are required:
                     * ```java
                     * .diff()
                     * .path()
                     * ```
                     */
                    @JvmStatic fun builder() = Builder()
                }

                /** A builder for [CreateFile]. */
                class Builder internal constructor() {

                    private var diff: JsonField<String>? = null
                    private var path: JsonField<String>? = null
                    private var type: JsonValue = JsonValue.from("create_file")
                    private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                    @JvmSynthetic
                    internal fun from(createFile: CreateFile) = apply {
                        diff = createFile.diff
                        path = createFile.path
                        type = createFile.type
                        additionalProperties = createFile.additionalProperties.toMutableMap()
                    }

                    /** Unified diff content to apply when creating the file. */
                    fun diff(diff: String) = diff(JsonField.of(diff))

                    /**
                     * Sets [Builder.diff] to an arbitrary JSON value.
                     *
                     * You should usually call [Builder.diff] with a well-typed [String] value
                     * instead. This method is primarily for setting the field to an undocumented or
                     * not yet supported value.
                     */
                    fun diff(diff: JsonField<String>) = apply { this.diff = diff }

                    /** Path of the file to create relative to the workspace root. */
                    fun path(path: String) = path(JsonField.of(path))

                    /**
                     * Sets [Builder.path] to an arbitrary JSON value.
                     *
                     * You should usually call [Builder.path] with a well-typed [String] value
                     * instead. This method is primarily for setting the field to an undocumented or
                     * not yet supported value.
                     */
                    fun path(path: JsonField<String>) = apply { this.path = path }

                    /**
                     * Sets the field to an arbitrary JSON value.
                     *
                     * It is usually unnecessary to call this method because the field defaults to
                     * the following:
                     * ```java
                     * JsonValue.from("create_file")
                     * ```
                     *
                     * This method is primarily for setting the field to an undocumented or not yet
                     * supported value.
                     */
                    fun type(type: JsonValue) = apply { this.type = type }

                    fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                        this.additionalProperties.clear()
                        putAllAdditionalProperties(additionalProperties)
                    }

                    fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                        additionalProperties.put(key, value)
                    }

                    fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) =
                        apply {
                            this.additionalProperties.putAll(additionalProperties)
                        }

                    fun removeAdditionalProperty(key: String) = apply {
                        additionalProperties.remove(key)
                    }

                    fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                        keys.forEach(::removeAdditionalProperty)
                    }

                    /**
                     * Returns an immutable instance of [CreateFile].
                     *
                     * Further updates to this [Builder] will not mutate the returned instance.
                     *
                     * The following fields are required:
                     * ```java
                     * .diff()
                     * .path()
                     * ```
                     *
                     * @throws IllegalStateException if any required field is unset.
                     */
                    fun build(): CreateFile =
                        CreateFile(
                            checkRequired("diff", diff),
                            checkRequired("path", path),
                            type,
                            additionalProperties.toMutableMap(),
                        )
                }

                private var validated: Boolean = false

                /**
                 * Validates that the types of all values in this object match their expected types
                 * recursively.
                 *
                 * This method is _not_ forwards compatible with new types from the API for existing
                 * fields.
                 *
                 * @throws OpenAIInvalidDataException if any value type in this object doesn't match
                 *   its expected type.
                 */
                fun validate(): CreateFile = apply {
                    if (validated) {
                        return@apply
                    }

                    diff()
                    path()
                    _type().let {
                        if (it != JsonValue.from("create_file")) {
                            throw OpenAIInvalidDataException("'type' is invalid, received $it")
                        }
                    }
                    validated = true
                }

                fun isValid(): Boolean =
                    try {
                        validate()
                        true
                    } catch (e: OpenAIInvalidDataException) {
                        false
                    }

                /**
                 * Returns a score indicating how many valid values are contained in this object
                 * recursively.
                 *
                 * Used for best match union deserialization.
                 */
                @JvmSynthetic
                internal fun validity(): Int =
                    (if (diff.asKnown().isPresent) 1 else 0) +
                        (if (path.asKnown().isPresent) 1 else 0) +
                        type.let { if (it == JsonValue.from("create_file")) 1 else 0 }

                override fun equals(other: Any?): Boolean {
                    if (this === other) {
                        return true
                    }

                    return other is CreateFile &&
                        diff == other.diff &&
                        path == other.path &&
                        type == other.type &&
                        additionalProperties == other.additionalProperties
                }

                private val hashCode: Int by lazy {
                    Objects.hash(diff, path, type, additionalProperties)
                }

                override fun hashCode(): Int = hashCode

                override fun toString() =
                    "CreateFile{diff=$diff, path=$path, type=$type, additionalProperties=$additionalProperties}"
            }

            /** Instruction for deleting an existing file via the apply_patch tool. */
            class DeleteFile
            @JsonCreator(mode = JsonCreator.Mode.DISABLED)
            private constructor(
                private val path: JsonField<String>,
                private val type: JsonValue,
                private val additionalProperties: MutableMap<String, JsonValue>,
            ) {

                @JsonCreator
                private constructor(
                    @JsonProperty("path")
                    @ExcludeMissing
                    path: JsonField<String> = JsonMissing.of(),
                    @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
                ) : this(path, type, mutableMapOf())

                /**
                 * Path of the file to delete relative to the workspace root.
                 *
                 * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
                 *   unexpectedly missing or null (e.g. if the server responded with an unexpected
                 *   value).
                 */
                fun path(): String = path.getRequired("path")

                /**
                 * The operation type. Always `delete_file`.
                 *
                 * Expected to always return the following:
                 * ```java
                 * JsonValue.from("delete_file")
                 * ```
                 *
                 * However, this method can be useful for debugging and logging (e.g. if the server
                 * responded with an unexpected value).
                 */
                @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

                /**
                 * Returns the raw JSON value of [path].
                 *
                 * Unlike [path], this method doesn't throw if the JSON field has an unexpected
                 * type.
                 */
                @JsonProperty("path") @ExcludeMissing fun _path(): JsonField<String> = path

                @JsonAnySetter
                private fun putAdditionalProperty(key: String, value: JsonValue) {
                    additionalProperties.put(key, value)
                }

                @JsonAnyGetter
                @ExcludeMissing
                fun _additionalProperties(): Map<String, JsonValue> =
                    Collections.unmodifiableMap(additionalProperties)

                fun toBuilder() = Builder().from(this)

                companion object {

                    /**
                     * Returns a mutable builder for constructing an instance of [DeleteFile].
                     *
                     * The following fields are required:
                     * ```java
                     * .path()
                     * ```
                     */
                    @JvmStatic fun builder() = Builder()
                }

                /** A builder for [DeleteFile]. */
                class Builder internal constructor() {

                    private var path: JsonField<String>? = null
                    private var type: JsonValue = JsonValue.from("delete_file")
                    private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                    @JvmSynthetic
                    internal fun from(deleteFile: DeleteFile) = apply {
                        path = deleteFile.path
                        type = deleteFile.type
                        additionalProperties = deleteFile.additionalProperties.toMutableMap()
                    }

                    /** Path of the file to delete relative to the workspace root. */
                    fun path(path: String) = path(JsonField.of(path))

                    /**
                     * Sets [Builder.path] to an arbitrary JSON value.
                     *
                     * You should usually call [Builder.path] with a well-typed [String] value
                     * instead. This method is primarily for setting the field to an undocumented or
                     * not yet supported value.
                     */
                    fun path(path: JsonField<String>) = apply { this.path = path }

                    /**
                     * Sets the field to an arbitrary JSON value.
                     *
                     * It is usually unnecessary to call this method because the field defaults to
                     * the following:
                     * ```java
                     * JsonValue.from("delete_file")
                     * ```
                     *
                     * This method is primarily for setting the field to an undocumented or not yet
                     * supported value.
                     */
                    fun type(type: JsonValue) = apply { this.type = type }

                    fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                        this.additionalProperties.clear()
                        putAllAdditionalProperties(additionalProperties)
                    }

                    fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                        additionalProperties.put(key, value)
                    }

                    fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) =
                        apply {
                            this.additionalProperties.putAll(additionalProperties)
                        }

                    fun removeAdditionalProperty(key: String) = apply {
                        additionalProperties.remove(key)
                    }

                    fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                        keys.forEach(::removeAdditionalProperty)
                    }

                    /**
                     * Returns an immutable instance of [DeleteFile].
                     *
                     * Further updates to this [Builder] will not mutate the returned instance.
                     *
                     * The following fields are required:
                     * ```java
                     * .path()
                     * ```
                     *
                     * @throws IllegalStateException if any required field is unset.
                     */
                    fun build(): DeleteFile =
                        DeleteFile(
                            checkRequired("path", path),
                            type,
                            additionalProperties.toMutableMap(),
                        )
                }

                private var validated: Boolean = false

                /**
                 * Validates that the types of all values in this object match their expected types
                 * recursively.
                 *
                 * This method is _not_ forwards compatible with new types from the API for existing
                 * fields.
                 *
                 * @throws OpenAIInvalidDataException if any value type in this object doesn't match
                 *   its expected type.
                 */
                fun validate(): DeleteFile = apply {
                    if (validated) {
                        return@apply
                    }

                    path()
                    _type().let {
                        if (it != JsonValue.from("delete_file")) {
                            throw OpenAIInvalidDataException("'type' is invalid, received $it")
                        }
                    }
                    validated = true
                }

                fun isValid(): Boolean =
                    try {
                        validate()
                        true
                    } catch (e: OpenAIInvalidDataException) {
                        false
                    }

                /**
                 * Returns a score indicating how many valid values are contained in this object
                 * recursively.
                 *
                 * Used for best match union deserialization.
                 */
                @JvmSynthetic
                internal fun validity(): Int =
                    (if (path.asKnown().isPresent) 1 else 0) +
                        type.let { if (it == JsonValue.from("delete_file")) 1 else 0 }

                override fun equals(other: Any?): Boolean {
                    if (this === other) {
                        return true
                    }

                    return other is DeleteFile &&
                        path == other.path &&
                        type == other.type &&
                        additionalProperties == other.additionalProperties
                }

                private val hashCode: Int by lazy { Objects.hash(path, type, additionalProperties) }

                override fun hashCode(): Int = hashCode

                override fun toString() =
                    "DeleteFile{path=$path, type=$type, additionalProperties=$additionalProperties}"
            }

            /** Instruction for updating an existing file via the apply_patch tool. */
            class UpdateFile
            @JsonCreator(mode = JsonCreator.Mode.DISABLED)
            private constructor(
                private val diff: JsonField<String>,
                private val path: JsonField<String>,
                private val type: JsonValue,
                private val additionalProperties: MutableMap<String, JsonValue>,
            ) {

                @JsonCreator
                private constructor(
                    @JsonProperty("diff")
                    @ExcludeMissing
                    diff: JsonField<String> = JsonMissing.of(),
                    @JsonProperty("path")
                    @ExcludeMissing
                    path: JsonField<String> = JsonMissing.of(),
                    @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
                ) : this(diff, path, type, mutableMapOf())

                /**
                 * Unified diff content to apply to the existing file.
                 *
                 * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
                 *   unexpectedly missing or null (e.g. if the server responded with an unexpected
                 *   value).
                 */
                fun diff(): String = diff.getRequired("diff")

                /**
                 * Path of the file to update relative to the workspace root.
                 *
                 * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
                 *   unexpectedly missing or null (e.g. if the server responded with an unexpected
                 *   value).
                 */
                fun path(): String = path.getRequired("path")

                /**
                 * The operation type. Always `update_file`.
                 *
                 * Expected to always return the following:
                 * ```java
                 * JsonValue.from("update_file")
                 * ```
                 *
                 * However, this method can be useful for debugging and logging (e.g. if the server
                 * responded with an unexpected value).
                 */
                @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

                /**
                 * Returns the raw JSON value of [diff].
                 *
                 * Unlike [diff], this method doesn't throw if the JSON field has an unexpected
                 * type.
                 */
                @JsonProperty("diff") @ExcludeMissing fun _diff(): JsonField<String> = diff

                /**
                 * Returns the raw JSON value of [path].
                 *
                 * Unlike [path], this method doesn't throw if the JSON field has an unexpected
                 * type.
                 */
                @JsonProperty("path") @ExcludeMissing fun _path(): JsonField<String> = path

                @JsonAnySetter
                private fun putAdditionalProperty(key: String, value: JsonValue) {
                    additionalProperties.put(key, value)
                }

                @JsonAnyGetter
                @ExcludeMissing
                fun _additionalProperties(): Map<String, JsonValue> =
                    Collections.unmodifiableMap(additionalProperties)

                fun toBuilder() = Builder().from(this)

                companion object {

                    /**
                     * Returns a mutable builder for constructing an instance of [UpdateFile].
                     *
                     * The following fields are required:
                     * ```java
                     * .diff()
                     * .path()
                     * ```
                     */
                    @JvmStatic fun builder() = Builder()
                }

                /** A builder for [UpdateFile]. */
                class Builder internal constructor() {

                    private var diff: JsonField<String>? = null
                    private var path: JsonField<String>? = null
                    private var type: JsonValue = JsonValue.from("update_file")
                    private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                    @JvmSynthetic
                    internal fun from(updateFile: UpdateFile) = apply {
                        diff = updateFile.diff
                        path = updateFile.path
                        type = updateFile.type
                        additionalProperties = updateFile.additionalProperties.toMutableMap()
                    }

                    /** Unified diff content to apply to the existing file. */
                    fun diff(diff: String) = diff(JsonField.of(diff))

                    /**
                     * Sets [Builder.diff] to an arbitrary JSON value.
                     *
                     * You should usually call [Builder.diff] with a well-typed [String] value
                     * instead. This method is primarily for setting the field to an undocumented or
                     * not yet supported value.
                     */
                    fun diff(diff: JsonField<String>) = apply { this.diff = diff }

                    /** Path of the file to update relative to the workspace root. */
                    fun path(path: String) = path(JsonField.of(path))

                    /**
                     * Sets [Builder.path] to an arbitrary JSON value.
                     *
                     * You should usually call [Builder.path] with a well-typed [String] value
                     * instead. This method is primarily for setting the field to an undocumented or
                     * not yet supported value.
                     */
                    fun path(path: JsonField<String>) = apply { this.path = path }

                    /**
                     * Sets the field to an arbitrary JSON value.
                     *
                     * It is usually unnecessary to call this method because the field defaults to
                     * the following:
                     * ```java
                     * JsonValue.from("update_file")
                     * ```
                     *
                     * This method is primarily for setting the field to an undocumented or not yet
                     * supported value.
                     */
                    fun type(type: JsonValue) = apply { this.type = type }

                    fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                        this.additionalProperties.clear()
                        putAllAdditionalProperties(additionalProperties)
                    }

                    fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                        additionalProperties.put(key, value)
                    }

                    fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) =
                        apply {
                            this.additionalProperties.putAll(additionalProperties)
                        }

                    fun removeAdditionalProperty(key: String) = apply {
                        additionalProperties.remove(key)
                    }

                    fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                        keys.forEach(::removeAdditionalProperty)
                    }

                    /**
                     * Returns an immutable instance of [UpdateFile].
                     *
                     * Further updates to this [Builder] will not mutate the returned instance.
                     *
                     * The following fields are required:
                     * ```java
                     * .diff()
                     * .path()
                     * ```
                     *
                     * @throws IllegalStateException if any required field is unset.
                     */
                    fun build(): UpdateFile =
                        UpdateFile(
                            checkRequired("diff", diff),
                            checkRequired("path", path),
                            type,
                            additionalProperties.toMutableMap(),
                        )
                }

                private var validated: Boolean = false

                /**
                 * Validates that the types of all values in this object match their expected types
                 * recursively.
                 *
                 * This method is _not_ forwards compatible with new types from the API for existing
                 * fields.
                 *
                 * @throws OpenAIInvalidDataException if any value type in this object doesn't match
                 *   its expected type.
                 */
                fun validate(): UpdateFile = apply {
                    if (validated) {
                        return@apply
                    }

                    diff()
                    path()
                    _type().let {
                        if (it != JsonValue.from("update_file")) {
                            throw OpenAIInvalidDataException("'type' is invalid, received $it")
                        }
                    }
                    validated = true
                }

                fun isValid(): Boolean =
                    try {
                        validate()
                        true
                    } catch (e: OpenAIInvalidDataException) {
                        false
                    }

                /**
                 * Returns a score indicating how many valid values are contained in this object
                 * recursively.
                 *
                 * Used for best match union deserialization.
                 */
                @JvmSynthetic
                internal fun validity(): Int =
                    (if (diff.asKnown().isPresent) 1 else 0) +
                        (if (path.asKnown().isPresent) 1 else 0) +
                        type.let { if (it == JsonValue.from("update_file")) 1 else 0 }

                override fun equals(other: Any?): Boolean {
                    if (this === other) {
                        return true
                    }

                    return other is UpdateFile &&
                        diff == other.diff &&
                        path == other.path &&
                        type == other.type &&
                        additionalProperties == other.additionalProperties
                }

                private val hashCode: Int by lazy {
                    Objects.hash(diff, path, type, additionalProperties)
                }

                override fun hashCode(): Int = hashCode

                override fun toString() =
                    "UpdateFile{diff=$diff, path=$path, type=$type, additionalProperties=$additionalProperties}"
            }
        }

        /** The status of the apply patch tool call. One of `in_progress` or `completed`. */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is ApplyPatchCall &&
                callId == other.callId &&
                operation == other.operation &&
                status == other.status &&
                type == other.type &&
                id == other.id &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(callId, operation, status, type, id, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "ApplyPatchCall{callId=$callId, operation=$operation, status=$status, type=$type, id=$id, additionalProperties=$additionalProperties}"
    }

    /** The streamed output emitted by an apply patch tool call. */
    class ApplyPatchCallOutput
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val callId: JsonField<String>,
        private val status: JsonField<Status>,
        private val type: JsonValue,
        private val id: JsonField<String>,
        private val output: JsonField<String>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("call_id") @ExcludeMissing callId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("output") @ExcludeMissing output: JsonField<String> = JsonMissing.of(),
        ) : this(callId, status, type, id, output, mutableMapOf())

        /**
         * The unique ID of the apply patch tool call generated by the model.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun callId(): String = callId.getRequired("call_id")

        /**
         * The status of the apply patch tool call output. One of `completed` or `failed`.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun status(): Status = status.getRequired("status")

        /**
         * The type of the item. Always `apply_patch_call_output`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("apply_patch_call_output")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The unique ID of the apply patch tool call output. Populated when this item is returned
         * via API.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun id(): Optional<String> = id.getOptional("id")

        /**
         * Optional human-readable log text from the apply patch tool (e.g., patch results or
         * errors).
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun output(): Optional<String> = output.getOptional("output")

        /**
         * Returns the raw JSON value of [callId].
         *
         * Unlike [callId], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("call_id") @ExcludeMissing fun _callId(): JsonField<String> = callId

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [output].
         *
         * Unlike [output], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("output") @ExcludeMissing fun _output(): JsonField<String> = output

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [ApplyPatchCallOutput].
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .status()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [ApplyPatchCallOutput]. */
        class Builder internal constructor() {

            private var callId: JsonField<String>? = null
            private var status: JsonField<Status>? = null
            private var type: JsonValue = JsonValue.from("apply_patch_call_output")
            private var id: JsonField<String> = JsonMissing.of()
            private var output: JsonField<String> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(applyPatchCallOutput: ApplyPatchCallOutput) = apply {
                callId = applyPatchCallOutput.callId
                status = applyPatchCallOutput.status
                type = applyPatchCallOutput.type
                id = applyPatchCallOutput.id
                output = applyPatchCallOutput.output
                additionalProperties = applyPatchCallOutput.additionalProperties.toMutableMap()
            }

            /** The unique ID of the apply patch tool call generated by the model. */
            fun callId(callId: String) = callId(JsonField.of(callId))

            /**
             * Sets [Builder.callId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.callId] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun callId(callId: JsonField<String>) = apply { this.callId = callId }

            /** The status of the apply patch tool call output. One of `completed` or `failed`. */
            fun status(status: Status) = status(JsonField.of(status))

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("apply_patch_call_output")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /**
             * The unique ID of the apply patch tool call output. Populated when this item is
             * returned via API.
             */
            fun id(id: String?) = id(JsonField.ofNullable(id))

            /** Alias for calling [Builder.id] with `id.orElse(null)`. */
            fun id(id: Optional<String>) = id(id.getOrNull())

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /**
             * Optional human-readable log text from the apply patch tool (e.g., patch results or
             * errors).
             */
            fun output(output: String?) = output(JsonField.ofNullable(output))

            /** Alias for calling [Builder.output] with `output.orElse(null)`. */
            fun output(output: Optional<String>) = output(output.getOrNull())

            /**
             * Sets [Builder.output] to an arbitrary JSON value.
             *
             * You should usually call [Builder.output] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun output(output: JsonField<String>) = apply { this.output = output }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [ApplyPatchCallOutput].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .callId()
             * .status()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): ApplyPatchCallOutput =
                ApplyPatchCallOutput(
                    checkRequired("callId", callId),
                    checkRequired("status", status),
                    type,
                    id,
                    output,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): ApplyPatchCallOutput = apply {
            if (validated) {
                return@apply
            }

            callId()
            status().validate()
            _type().let {
                if (it != JsonValue.from("apply_patch_call_output")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            id()
            output()
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (callId.asKnown().isPresent) 1 else 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0) +
                type.let { if (it == JsonValue.from("apply_patch_call_output")) 1 else 0 } +
                (if (id.asKnown().isPresent) 1 else 0) +
                (if (output.asKnown().isPresent) 1 else 0)

        /** The status of the apply patch tool call output. One of `completed` or `failed`. */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val COMPLETED = of("completed")

                @JvmField val FAILED = of("failed")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                COMPLETED,
                FAILED,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                COMPLETED,
                FAILED,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    COMPLETED -> Value.COMPLETED
                    FAILED -> Value.FAILED
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    COMPLETED -> Known.COMPLETED
                    FAILED -> Known.FAILED
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is ApplyPatchCallOutput &&
                callId == other.callId &&
                status == other.status &&
                type == other.type &&
                id == other.id &&
                output == other.output &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(callId, status, type, id, output, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "ApplyPatchCallOutput{callId=$callId, status=$status, type=$type, id=$id, output=$output, additionalProperties=$additionalProperties}"
    }

    /** A list of tools available on an MCP server. */
    class McpListTools
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val id: JsonField<String>,
        private val serverLabel: JsonField<String>,
        private val tools: JsonField<List<Tool>>,
        private val type: JsonValue,
        private val error: JsonField<String>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("server_label")
            @ExcludeMissing
            serverLabel: JsonField<String> = JsonMissing.of(),
            @JsonProperty("tools") @ExcludeMissing tools: JsonField<List<Tool>> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("error") @ExcludeMissing error: JsonField<String> = JsonMissing.of(),
        ) : this(id, serverLabel, tools, type, error, mutableMapOf())

        /**
         * The unique ID of the list.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun id(): String = id.getRequired("id")

        /**
         * The label of the MCP server.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun serverLabel(): String = serverLabel.getRequired("server_label")

        /**
         * The tools available on the server.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun tools(): List<Tool> = tools.getRequired("tools")

        /**
         * The type of the item. Always `mcp_list_tools`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("mcp_list_tools")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * Error message if the server could not list tools.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun error(): Optional<String> = error.getOptional("error")

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [serverLabel].
         *
         * Unlike [serverLabel], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("server_label")
        @ExcludeMissing
        fun _serverLabel(): JsonField<String> = serverLabel

        /**
         * Returns the raw JSON value of [tools].
         *
         * Unlike [tools], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("tools") @ExcludeMissing fun _tools(): JsonField<List<Tool>> = tools

        /**
         * Returns the raw JSON value of [error].
         *
         * Unlike [error], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("error") @ExcludeMissing fun _error(): JsonField<String> = error

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [McpListTools].
             *
             * The following fields are required:
             * ```java
             * .id()
             * .serverLabel()
             * .tools()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [McpListTools]. */
        class Builder internal constructor() {

            private var id: JsonField<String>? = null
            private var serverLabel: JsonField<String>? = null
            private var tools: JsonField<MutableList<Tool>>? = null
            private var type: JsonValue = JsonValue.from("mcp_list_tools")
            private var error: JsonField<String> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(mcpListTools: McpListTools) = apply {
                id = mcpListTools.id
                serverLabel = mcpListTools.serverLabel
                tools = mcpListTools.tools.map { it.toMutableList() }
                type = mcpListTools.type
                error = mcpListTools.error
                additionalProperties = mcpListTools.additionalProperties.toMutableMap()
            }

            /** The unique ID of the list. */
            fun id(id: String) = id(JsonField.of(id))

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** The label of the MCP server. */
            fun serverLabel(serverLabel: String) = serverLabel(JsonField.of(serverLabel))

            /**
             * Sets [Builder.serverLabel] to an arbitrary JSON value.
             *
             * You should usually call [Builder.serverLabel] with a well-typed [String] value
             * instead. This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun serverLabel(serverLabel: JsonField<String>) = apply {
                this.serverLabel = serverLabel
            }

            /** The tools available on the server. */
            fun tools(tools: List<Tool>) = tools(JsonField.of(tools))

            /**
             * Sets [Builder.tools] to an arbitrary JSON value.
             *
             * You should usually call [Builder.tools] with a well-typed `List<Tool>` value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun tools(tools: JsonField<List<Tool>>) = apply {
                this.tools = tools.map { it.toMutableList() }
            }

            /**
             * Adds a single [Tool] to [tools].
             *
             * @throws IllegalStateException if the field was previously set to a non-list.
             */
            fun addTool(tool: Tool) = apply {
                tools =
                    (tools ?: JsonField.of(mutableListOf())).also {
                        checkKnown("tools", it).add(tool)
                    }
            }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("mcp_list_tools")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /** Error message if the server could not list tools. */
            fun error(error: String?) = error(JsonField.ofNullable(error))

            /** Alias for calling [Builder.error] with `error.orElse(null)`. */
            fun error(error: Optional<String>) = error(error.getOrNull())

            /**
             * Sets [Builder.error] to an arbitrary JSON value.
             *
             * You should usually call [Builder.error] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun error(error: JsonField<String>) = apply { this.error = error }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [McpListTools].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .id()
             * .serverLabel()
             * .tools()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): McpListTools =
                McpListTools(
                    checkRequired("id", id),
                    checkRequired("serverLabel", serverLabel),
                    checkRequired("tools", tools).map { it.toImmutable() },
                    type,
                    error,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): McpListTools = apply {
            if (validated) {
                return@apply
            }

            id()
            serverLabel()
            tools().forEach { it.validate() }
            _type().let {
                if (it != JsonValue.from("mcp_list_tools")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            error()
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (id.asKnown().isPresent) 1 else 0) +
                (if (serverLabel.asKnown().isPresent) 1 else 0) +
                (tools.asKnown().getOrNull()?.sumOf { it.validity().toInt() } ?: 0) +
                type.let { if (it == JsonValue.from("mcp_list_tools")) 1 else 0 } +
                (if (error.asKnown().isPresent) 1 else 0)

        /** A tool available on an MCP server. */
        class Tool
        @JsonCreator(mode = JsonCreator.Mode.DISABLED)
        private constructor(
            private val inputSchema: JsonValue,
            private val name: JsonField<String>,
            private val annotations: JsonValue,
            private val description: JsonField<String>,
            private val additionalProperties: MutableMap<String, JsonValue>,
        ) {

            @JsonCreator
            private constructor(
                @JsonProperty("input_schema")
                @ExcludeMissing
                inputSchema: JsonValue = JsonMissing.of(),
                @JsonProperty("name") @ExcludeMissing name: JsonField<String> = JsonMissing.of(),
                @JsonProperty("annotations")
                @ExcludeMissing
                annotations: JsonValue = JsonMissing.of(),
                @JsonProperty("description")
                @ExcludeMissing
                description: JsonField<String> = JsonMissing.of(),
            ) : this(inputSchema, name, annotations, description, mutableMapOf())

            /**
             * The JSON schema describing the tool's input.
             *
             * This arbitrary value can be deserialized into a custom type using the `convert`
             * method:
             * ```java
             * MyClass myObject = tool.inputSchema().convert(MyClass.class);
             * ```
             */
            @JsonProperty("input_schema")
            @ExcludeMissing
            fun _inputSchema(): JsonValue = inputSchema

            /**
             * The name of the tool.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
             *   unexpectedly missing or null (e.g. if the server responded with an unexpected
             *   value).
             */
            fun name(): String = name.getRequired("name")

            /**
             * Additional annotations about the tool.
             *
             * This arbitrary value can be deserialized into a custom type using the `convert`
             * method:
             * ```java
             * MyClass myObject = tool.annotations().convert(MyClass.class);
             * ```
             */
            @JsonProperty("annotations") @ExcludeMissing fun _annotations(): JsonValue = annotations

            /**
             * The description of the tool.
             *
             * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if
             *   the server responded with an unexpected value).
             */
            fun description(): Optional<String> = description.getOptional("description")

            /**
             * Returns the raw JSON value of [name].
             *
             * Unlike [name], this method doesn't throw if the JSON field has an unexpected type.
             */
            @JsonProperty("name") @ExcludeMissing fun _name(): JsonField<String> = name

            /**
             * Returns the raw JSON value of [description].
             *
             * Unlike [description], this method doesn't throw if the JSON field has an unexpected
             * type.
             */
            @JsonProperty("description")
            @ExcludeMissing
            fun _description(): JsonField<String> = description

            @JsonAnySetter
            private fun putAdditionalProperty(key: String, value: JsonValue) {
                additionalProperties.put(key, value)
            }

            @JsonAnyGetter
            @ExcludeMissing
            fun _additionalProperties(): Map<String, JsonValue> =
                Collections.unmodifiableMap(additionalProperties)

            fun toBuilder() = Builder().from(this)

            companion object {

                /**
                 * Returns a mutable builder for constructing an instance of [Tool].
                 *
                 * The following fields are required:
                 * ```java
                 * .inputSchema()
                 * .name()
                 * ```
                 */
                @JvmStatic fun builder() = Builder()
            }

            /** A builder for [Tool]. */
            class Builder internal constructor() {

                private var inputSchema: JsonValue? = null
                private var name: JsonField<String>? = null
                private var annotations: JsonValue = JsonMissing.of()
                private var description: JsonField<String> = JsonMissing.of()
                private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

                @JvmSynthetic
                internal fun from(tool: Tool) = apply {
                    inputSchema = tool.inputSchema
                    name = tool.name
                    annotations = tool.annotations
                    description = tool.description
                    additionalProperties = tool.additionalProperties.toMutableMap()
                }

                /** The JSON schema describing the tool's input. */
                fun inputSchema(inputSchema: JsonValue) = apply { this.inputSchema = inputSchema }

                /** The name of the tool. */
                fun name(name: String) = name(JsonField.of(name))

                /**
                 * Sets [Builder.name] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.name] with a well-typed [String] value instead.
                 * This method is primarily for setting the field to an undocumented or not yet
                 * supported value.
                 */
                fun name(name: JsonField<String>) = apply { this.name = name }

                /** Additional annotations about the tool. */
                fun annotations(annotations: JsonValue) = apply { this.annotations = annotations }

                /** The description of the tool. */
                fun description(description: String?) =
                    description(JsonField.ofNullable(description))

                /** Alias for calling [Builder.description] with `description.orElse(null)`. */
                fun description(description: Optional<String>) =
                    description(description.getOrNull())

                /**
                 * Sets [Builder.description] to an arbitrary JSON value.
                 *
                 * You should usually call [Builder.description] with a well-typed [String] value
                 * instead. This method is primarily for setting the field to an undocumented or not
                 * yet supported value.
                 */
                fun description(description: JsonField<String>) = apply {
                    this.description = description
                }

                fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                    this.additionalProperties.clear()
                    putAllAdditionalProperties(additionalProperties)
                }

                fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                    additionalProperties.put(key, value)
                }

                fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) =
                    apply {
                        this.additionalProperties.putAll(additionalProperties)
                    }

                fun removeAdditionalProperty(key: String) = apply {
                    additionalProperties.remove(key)
                }

                fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                    keys.forEach(::removeAdditionalProperty)
                }

                /**
                 * Returns an immutable instance of [Tool].
                 *
                 * Further updates to this [Builder] will not mutate the returned instance.
                 *
                 * The following fields are required:
                 * ```java
                 * .inputSchema()
                 * .name()
                 * ```
                 *
                 * @throws IllegalStateException if any required field is unset.
                 */
                fun build(): Tool =
                    Tool(
                        checkRequired("inputSchema", inputSchema),
                        checkRequired("name", name),
                        annotations,
                        description,
                        additionalProperties.toMutableMap(),
                    )
            }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Tool = apply {
                if (validated) {
                    return@apply
                }

                name()
                description()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic
            internal fun validity(): Int =
                (if (name.asKnown().isPresent) 1 else 0) +
                    (if (description.asKnown().isPresent) 1 else 0)

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Tool &&
                    inputSchema == other.inputSchema &&
                    name == other.name &&
                    annotations == other.annotations &&
                    description == other.description &&
                    additionalProperties == other.additionalProperties
            }

            private val hashCode: Int by lazy {
                Objects.hash(inputSchema, name, annotations, description, additionalProperties)
            }

            override fun hashCode(): Int = hashCode

            override fun toString() =
                "Tool{inputSchema=$inputSchema, name=$name, annotations=$annotations, description=$description, additionalProperties=$additionalProperties}"
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is McpListTools &&
                id == other.id &&
                serverLabel == other.serverLabel &&
                tools == other.tools &&
                type == other.type &&
                error == other.error &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(id, serverLabel, tools, type, error, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "McpListTools{id=$id, serverLabel=$serverLabel, tools=$tools, type=$type, error=$error, additionalProperties=$additionalProperties}"
    }

    /** A request for human approval of a tool invocation. */
    class McpApprovalRequest
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val id: JsonField<String>,
        private val arguments: JsonField<String>,
        private val name: JsonField<String>,
        private val serverLabel: JsonField<String>,
        private val type: JsonValue,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("arguments")
            @ExcludeMissing
            arguments: JsonField<String> = JsonMissing.of(),
            @JsonProperty("name") @ExcludeMissing name: JsonField<String> = JsonMissing.of(),
            @JsonProperty("server_label")
            @ExcludeMissing
            serverLabel: JsonField<String> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
        ) : this(id, arguments, name, serverLabel, type, mutableMapOf())

        /**
         * The unique ID of the approval request.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun id(): String = id.getRequired("id")

        /**
         * A JSON string of arguments for the tool.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun arguments(): String = arguments.getRequired("arguments")

        /**
         * The name of the tool to run.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun name(): String = name.getRequired("name")

        /**
         * The label of the MCP server making the request.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun serverLabel(): String = serverLabel.getRequired("server_label")

        /**
         * The type of the item. Always `mcp_approval_request`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("mcp_approval_request")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [arguments].
         *
         * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField<String> = arguments

        /**
         * Returns the raw JSON value of [name].
         *
         * Unlike [name], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("name") @ExcludeMissing fun _name(): JsonField<String> = name

        /**
         * Returns the raw JSON value of [serverLabel].
         *
         * Unlike [serverLabel], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("server_label")
        @ExcludeMissing
        fun _serverLabel(): JsonField<String> = serverLabel

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [McpApprovalRequest].
             *
             * The following fields are required:
             * ```java
             * .id()
             * .arguments()
             * .name()
             * .serverLabel()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [McpApprovalRequest]. */
        class Builder internal constructor() {

            private var id: JsonField<String>? = null
            private var arguments: JsonField<String>? = null
            private var name: JsonField<String>? = null
            private var serverLabel: JsonField<String>? = null
            private var type: JsonValue = JsonValue.from("mcp_approval_request")
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(mcpApprovalRequest: McpApprovalRequest) = apply {
                id = mcpApprovalRequest.id
                arguments = mcpApprovalRequest.arguments
                name = mcpApprovalRequest.name
                serverLabel = mcpApprovalRequest.serverLabel
                type = mcpApprovalRequest.type
                additionalProperties = mcpApprovalRequest.additionalProperties.toMutableMap()
            }

            /** The unique ID of the approval request. */
            fun id(id: String) = id(JsonField.of(id))

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** A JSON string of arguments for the tool. */
            fun arguments(arguments: String) = arguments(JsonField.of(arguments))

            /**
             * Sets [Builder.arguments] to an arbitrary JSON value.
             *
             * You should usually call [Builder.arguments] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun arguments(arguments: JsonField<String>) = apply { this.arguments = arguments }

            /** The name of the tool to run. */
            fun name(name: String) = name(JsonField.of(name))

            /**
             * Sets [Builder.name] to an arbitrary JSON value.
             *
             * You should usually call [Builder.name] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun name(name: JsonField<String>) = apply { this.name = name }

            /** The label of the MCP server making the request. */
            fun serverLabel(serverLabel: String) = serverLabel(JsonField.of(serverLabel))

            /**
             * Sets [Builder.serverLabel] to an arbitrary JSON value.
             *
             * You should usually call [Builder.serverLabel] with a well-typed [String] value
             * instead. This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun serverLabel(serverLabel: JsonField<String>) = apply {
                this.serverLabel = serverLabel
            }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("mcp_approval_request")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [McpApprovalRequest].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .id()
             * .arguments()
             * .name()
             * .serverLabel()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): McpApprovalRequest =
                McpApprovalRequest(
                    checkRequired("id", id),
                    checkRequired("arguments", arguments),
                    checkRequired("name", name),
                    checkRequired("serverLabel", serverLabel),
                    type,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): McpApprovalRequest = apply {
            if (validated) {
                return@apply
            }

            id()
            arguments()
            name()
            serverLabel()
            _type().let {
                if (it != JsonValue.from("mcp_approval_request")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (id.asKnown().isPresent) 1 else 0) +
                (if (arguments.asKnown().isPresent) 1 else 0) +
                (if (name.asKnown().isPresent) 1 else 0) +
                (if (serverLabel.asKnown().isPresent) 1 else 0) +
                type.let { if (it == JsonValue.from("mcp_approval_request")) 1 else 0 }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is McpApprovalRequest &&
                id == other.id &&
                arguments == other.arguments &&
                name == other.name &&
                serverLabel == other.serverLabel &&
                type == other.type &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(id, arguments, name, serverLabel, type, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "McpApprovalRequest{id=$id, arguments=$arguments, name=$name, serverLabel=$serverLabel, type=$type, additionalProperties=$additionalProperties}"
    }

    /** A response to an MCP approval request. */
    class McpApprovalResponse
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val approvalRequestId: JsonField<String>,
        private val approve: JsonField<Boolean>,
        private val type: JsonValue,
        private val id: JsonField<String>,
        private val reason: JsonField<String>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("approval_request_id")
            @ExcludeMissing
            approvalRequestId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("approve") @ExcludeMissing approve: JsonField<Boolean> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("reason") @ExcludeMissing reason: JsonField<String> = JsonMissing.of(),
        ) : this(approvalRequestId, approve, type, id, reason, mutableMapOf())

        /**
         * The ID of the approval request being answered.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun approvalRequestId(): String = approvalRequestId.getRequired("approval_request_id")

        /**
         * Whether the request was approved.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun approve(): Boolean = approve.getRequired("approve")

        /**
         * The type of the item. Always `mcp_approval_response`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("mcp_approval_response")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * The unique ID of the approval response
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun id(): Optional<String> = id.getOptional("id")

        /**
         * Optional reason for the decision.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun reason(): Optional<String> = reason.getOptional("reason")

        /**
         * Returns the raw JSON value of [approvalRequestId].
         *
         * Unlike [approvalRequestId], this method doesn't throw if the JSON field has an unexpected
         * type.
         */
        @JsonProperty("approval_request_id")
        @ExcludeMissing
        fun _approvalRequestId(): JsonField<String> = approvalRequestId

        /**
         * Returns the raw JSON value of [approve].
         *
         * Unlike [approve], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("approve") @ExcludeMissing fun _approve(): JsonField<Boolean> = approve

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [reason].
         *
         * Unlike [reason], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("reason") @ExcludeMissing fun _reason(): JsonField<String> = reason

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [McpApprovalResponse].
             *
             * The following fields are required:
             * ```java
             * .approvalRequestId()
             * .approve()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [McpApprovalResponse]. */
        class Builder internal constructor() {

            private var approvalRequestId: JsonField<String>? = null
            private var approve: JsonField<Boolean>? = null
            private var type: JsonValue = JsonValue.from("mcp_approval_response")
            private var id: JsonField<String> = JsonMissing.of()
            private var reason: JsonField<String> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(mcpApprovalResponse: McpApprovalResponse) = apply {
                approvalRequestId = mcpApprovalResponse.approvalRequestId
                approve = mcpApprovalResponse.approve
                type = mcpApprovalResponse.type
                id = mcpApprovalResponse.id
                reason = mcpApprovalResponse.reason
                additionalProperties = mcpApprovalResponse.additionalProperties.toMutableMap()
            }

            /** The ID of the approval request being answered. */
            fun approvalRequestId(approvalRequestId: String) =
                approvalRequestId(JsonField.of(approvalRequestId))

            /**
             * Sets [Builder.approvalRequestId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.approvalRequestId] with a well-typed [String] value
             * instead. This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun approvalRequestId(approvalRequestId: JsonField<String>) = apply {
                this.approvalRequestId = approvalRequestId
            }

            /** Whether the request was approved. */
            fun approve(approve: Boolean) = approve(JsonField.of(approve))

            /**
             * Sets [Builder.approve] to an arbitrary JSON value.
             *
             * You should usually call [Builder.approve] with a well-typed [Boolean] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun approve(approve: JsonField<Boolean>) = apply { this.approve = approve }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("mcp_approval_response")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /** The unique ID of the approval response */
            fun id(id: String?) = id(JsonField.ofNullable(id))

            /** Alias for calling [Builder.id] with `id.orElse(null)`. */
            fun id(id: Optional<String>) = id(id.getOrNull())

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** Optional reason for the decision. */
            fun reason(reason: String?) = reason(JsonField.ofNullable(reason))

            /** Alias for calling [Builder.reason] with `reason.orElse(null)`. */
            fun reason(reason: Optional<String>) = reason(reason.getOrNull())

            /**
             * Sets [Builder.reason] to an arbitrary JSON value.
             *
             * You should usually call [Builder.reason] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun reason(reason: JsonField<String>) = apply { this.reason = reason }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [McpApprovalResponse].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .approvalRequestId()
             * .approve()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): McpApprovalResponse =
                McpApprovalResponse(
                    checkRequired("approvalRequestId", approvalRequestId),
                    checkRequired("approve", approve),
                    type,
                    id,
                    reason,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): McpApprovalResponse = apply {
            if (validated) {
                return@apply
            }

            approvalRequestId()
            approve()
            _type().let {
                if (it != JsonValue.from("mcp_approval_response")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            id()
            reason()
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (approvalRequestId.asKnown().isPresent) 1 else 0) +
                (if (approve.asKnown().isPresent) 1 else 0) +
                type.let { if (it == JsonValue.from("mcp_approval_response")) 1 else 0 } +
                (if (id.asKnown().isPresent) 1 else 0) +
                (if (reason.asKnown().isPresent) 1 else 0)

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is McpApprovalResponse &&
                approvalRequestId == other.approvalRequestId &&
                approve == other.approve &&
                type == other.type &&
                id == other.id &&
                reason == other.reason &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(approvalRequestId, approve, type, id, reason, additionalProperties)
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "McpApprovalResponse{approvalRequestId=$approvalRequestId, approve=$approve, type=$type, id=$id, reason=$reason, additionalProperties=$additionalProperties}"
    }

    /** An invocation of a tool on an MCP server. */
    class McpCall
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val id: JsonField<String>,
        private val arguments: JsonField<String>,
        private val name: JsonField<String>,
        private val serverLabel: JsonField<String>,
        private val type: JsonValue,
        private val approvalRequestId: JsonField<String>,
        private val error: JsonField<String>,
        private val output: JsonField<String>,
        private val status: JsonField<Status>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("arguments")
            @ExcludeMissing
            arguments: JsonField<String> = JsonMissing.of(),
            @JsonProperty("name") @ExcludeMissing name: JsonField<String> = JsonMissing.of(),
            @JsonProperty("server_label")
            @ExcludeMissing
            serverLabel: JsonField<String> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonValue = JsonMissing.of(),
            @JsonProperty("approval_request_id")
            @ExcludeMissing
            approvalRequestId: JsonField<String> = JsonMissing.of(),
            @JsonProperty("error") @ExcludeMissing error: JsonField<String> = JsonMissing.of(),
            @JsonProperty("output") @ExcludeMissing output: JsonField<String> = JsonMissing.of(),
            @JsonProperty("status") @ExcludeMissing status: JsonField<Status> = JsonMissing.of(),
        ) : this(
            id,
            arguments,
            name,
            serverLabel,
            type,
            approvalRequestId,
            error,
            output,
            status,
            mutableMapOf(),
        )

        /**
         * The unique ID of the tool call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun id(): String = id.getRequired("id")

        /**
         * A JSON string of the arguments passed to the tool.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun arguments(): String = arguments.getRequired("arguments")

        /**
         * The name of the tool that was run.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun name(): String = name.getRequired("name")

        /**
         * The label of the MCP server running the tool.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun serverLabel(): String = serverLabel.getRequired("server_label")

        /**
         * The type of the item. Always `mcp_call`.
         *
         * Expected to always return the following:
         * ```java
         * JsonValue.from("mcp_call")
         * ```
         *
         * However, this method can be useful for debugging and logging (e.g. if the server
         * responded with an unexpected value).
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonValue = type

        /**
         * 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.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun approvalRequestId(): Optional<String> =
            approvalRequestId.getOptional("approval_request_id")

        /**
         * The error from the tool call, if any.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun error(): Optional<String> = error.getOptional("error")

        /**
         * The output from the tool call.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun output(): Optional<String> = output.getOptional("output")

        /**
         * The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`,
         * or `failed`.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun status(): Optional<Status> = status.getOptional("status")

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [arguments].
         *
         * Unlike [arguments], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField<String> = arguments

        /**
         * Returns the raw JSON value of [name].
         *
         * Unlike [name], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("name") @ExcludeMissing fun _name(): JsonField<String> = name

        /**
         * Returns the raw JSON value of [serverLabel].
         *
         * Unlike [serverLabel], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("server_label")
        @ExcludeMissing
        fun _serverLabel(): JsonField<String> = serverLabel

        /**
         * Returns the raw JSON value of [approvalRequestId].
         *
         * Unlike [approvalRequestId], this method doesn't throw if the JSON field has an unexpected
         * type.
         */
        @JsonProperty("approval_request_id")
        @ExcludeMissing
        fun _approvalRequestId(): JsonField<String> = approvalRequestId

        /**
         * Returns the raw JSON value of [error].
         *
         * Unlike [error], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("error") @ExcludeMissing fun _error(): JsonField<String> = error

        /**
         * Returns the raw JSON value of [output].
         *
         * Unlike [output], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("output") @ExcludeMissing fun _output(): JsonField<String> = output

        /**
         * Returns the raw JSON value of [status].
         *
         * Unlike [status], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("status") @ExcludeMissing fun _status(): JsonField<Status> = status

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [McpCall].
             *
             * The following fields are required:
             * ```java
             * .id()
             * .arguments()
             * .name()
             * .serverLabel()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [McpCall]. */
        class Builder internal constructor() {

            private var id: JsonField<String>? = null
            private var arguments: JsonField<String>? = null
            private var name: JsonField<String>? = null
            private var serverLabel: JsonField<String>? = null
            private var type: JsonValue = JsonValue.from("mcp_call")
            private var approvalRequestId: JsonField<String> = JsonMissing.of()
            private var error: JsonField<String> = JsonMissing.of()
            private var output: JsonField<String> = JsonMissing.of()
            private var status: JsonField<Status> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(mcpCall: McpCall) = apply {
                id = mcpCall.id
                arguments = mcpCall.arguments
                name = mcpCall.name
                serverLabel = mcpCall.serverLabel
                type = mcpCall.type
                approvalRequestId = mcpCall.approvalRequestId
                error = mcpCall.error
                output = mcpCall.output
                status = mcpCall.status
                additionalProperties = mcpCall.additionalProperties.toMutableMap()
            }

            /** The unique ID of the tool call. */
            fun id(id: String) = id(JsonField.of(id))

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** A JSON string of the arguments passed to the tool. */
            fun arguments(arguments: String) = arguments(JsonField.of(arguments))

            /**
             * Sets [Builder.arguments] to an arbitrary JSON value.
             *
             * You should usually call [Builder.arguments] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun arguments(arguments: JsonField<String>) = apply { this.arguments = arguments }

            /** The name of the tool that was run. */
            fun name(name: String) = name(JsonField.of(name))

            /**
             * Sets [Builder.name] to an arbitrary JSON value.
             *
             * You should usually call [Builder.name] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun name(name: JsonField<String>) = apply { this.name = name }

            /** The label of the MCP server running the tool. */
            fun serverLabel(serverLabel: String) = serverLabel(JsonField.of(serverLabel))

            /**
             * Sets [Builder.serverLabel] to an arbitrary JSON value.
             *
             * You should usually call [Builder.serverLabel] with a well-typed [String] value
             * instead. This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun serverLabel(serverLabel: JsonField<String>) = apply {
                this.serverLabel = serverLabel
            }

            /**
             * Sets the field to an arbitrary JSON value.
             *
             * It is usually unnecessary to call this method because the field defaults to the
             * following:
             * ```java
             * JsonValue.from("mcp_call")
             * ```
             *
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun type(type: JsonValue) = apply { this.type = type }

            /**
             * 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.
             */
            fun approvalRequestId(approvalRequestId: String?) =
                approvalRequestId(JsonField.ofNullable(approvalRequestId))

            /**
             * Alias for calling [Builder.approvalRequestId] with `approvalRequestId.orElse(null)`.
             */
            fun approvalRequestId(approvalRequestId: Optional<String>) =
                approvalRequestId(approvalRequestId.getOrNull())

            /**
             * Sets [Builder.approvalRequestId] to an arbitrary JSON value.
             *
             * You should usually call [Builder.approvalRequestId] with a well-typed [String] value
             * instead. This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun approvalRequestId(approvalRequestId: JsonField<String>) = apply {
                this.approvalRequestId = approvalRequestId
            }

            /** The error from the tool call, if any. */
            fun error(error: String?) = error(JsonField.ofNullable(error))

            /** Alias for calling [Builder.error] with `error.orElse(null)`. */
            fun error(error: Optional<String>) = error(error.getOrNull())

            /**
             * Sets [Builder.error] to an arbitrary JSON value.
             *
             * You should usually call [Builder.error] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun error(error: JsonField<String>) = apply { this.error = error }

            /** The output from the tool call. */
            fun output(output: String?) = output(JsonField.ofNullable(output))

            /** Alias for calling [Builder.output] with `output.orElse(null)`. */
            fun output(output: Optional<String>) = output(output.getOrNull())

            /**
             * Sets [Builder.output] to an arbitrary JSON value.
             *
             * You should usually call [Builder.output] with a well-typed [String] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun output(output: JsonField<String>) = apply { this.output = output }

            /**
             * The status of the tool call. One of `in_progress`, `completed`, `incomplete`,
             * `calling`, or `failed`.
             */
            fun status(status: Status) = status(JsonField.of(status))

            /**
             * Sets [Builder.status] to an arbitrary JSON value.
             *
             * You should usually call [Builder.status] with a well-typed [Status] value instead.
             * This method is primarily for setting the field to an undocumented or not yet
             * supported value.
             */
            fun status(status: JsonField<Status>) = apply { this.status = status }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [McpCall].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .id()
             * .arguments()
             * .name()
             * .serverLabel()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): McpCall =
                McpCall(
                    checkRequired("id", id),
                    checkRequired("arguments", arguments),
                    checkRequired("name", name),
                    checkRequired("serverLabel", serverLabel),
                    type,
                    approvalRequestId,
                    error,
                    output,
                    status,
                    additionalProperties.toMutableMap(),
                )
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): McpCall = apply {
            if (validated) {
                return@apply
            }

            id()
            arguments()
            name()
            serverLabel()
            _type().let {
                if (it != JsonValue.from("mcp_call")) {
                    throw OpenAIInvalidDataException("'type' is invalid, received $it")
                }
            }
            approvalRequestId()
            error()
            output()
            status().ifPresent { it.validate() }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (id.asKnown().isPresent) 1 else 0) +
                (if (arguments.asKnown().isPresent) 1 else 0) +
                (if (name.asKnown().isPresent) 1 else 0) +
                (if (serverLabel.asKnown().isPresent) 1 else 0) +
                type.let { if (it == JsonValue.from("mcp_call")) 1 else 0 } +
                (if (approvalRequestId.asKnown().isPresent) 1 else 0) +
                (if (error.asKnown().isPresent) 1 else 0) +
                (if (output.asKnown().isPresent) 1 else 0) +
                (status.asKnown().getOrNull()?.validity() ?: 0)

        /**
         * The status of the tool call. One of `in_progress`, `completed`, `incomplete`, `calling`,
         * or `failed`.
         */
        class Status @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val IN_PROGRESS = of("in_progress")

                @JvmField val COMPLETED = of("completed")

                @JvmField val INCOMPLETE = of("incomplete")

                @JvmField val CALLING = of("calling")

                @JvmField val FAILED = of("failed")

                @JvmStatic fun of(value: String) = Status(JsonField.of(value))
            }

            /** An enum containing [Status]'s known values. */
            enum class Known {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                CALLING,
                FAILED,
            }

            /**
             * An enum containing [Status]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Status] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                IN_PROGRESS,
                COMPLETED,
                INCOMPLETE,
                CALLING,
                FAILED,
                /**
                 * An enum member indicating that [Status] was instantiated with an unknown value.
                 */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    IN_PROGRESS -> Value.IN_PROGRESS
                    COMPLETED -> Value.COMPLETED
                    INCOMPLETE -> Value.INCOMPLETE
                    CALLING -> Value.CALLING
                    FAILED -> Value.FAILED
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    IN_PROGRESS -> Known.IN_PROGRESS
                    COMPLETED -> Known.COMPLETED
                    INCOMPLETE -> Known.INCOMPLETE
                    CALLING -> Known.CALLING
                    FAILED -> Known.FAILED
                    else -> throw OpenAIInvalidDataException("Unknown Status: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Status = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Status && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is McpCall &&
                id == other.id &&
                arguments == other.arguments &&
                name == other.name &&
                serverLabel == other.serverLabel &&
                type == other.type &&
                approvalRequestId == other.approvalRequestId &&
                error == other.error &&
                output == other.output &&
                status == other.status &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy {
            Objects.hash(
                id,
                arguments,
                name,
                serverLabel,
                type,
                approvalRequestId,
                error,
                output,
                status,
                additionalProperties,
            )
        }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "McpCall{id=$id, arguments=$arguments, name=$name, serverLabel=$serverLabel, type=$type, approvalRequestId=$approvalRequestId, error=$error, output=$output, status=$status, additionalProperties=$additionalProperties}"
    }

    /** An internal identifier for an item to reference. */
    class ItemReference
    @JsonCreator(mode = JsonCreator.Mode.DISABLED)
    private constructor(
        private val id: JsonField<String>,
        private val type: JsonField<Type>,
        private val additionalProperties: MutableMap<String, JsonValue>,
    ) {

        @JsonCreator
        private constructor(
            @JsonProperty("id") @ExcludeMissing id: JsonField<String> = JsonMissing.of(),
            @JsonProperty("type") @ExcludeMissing type: JsonField<Type> = JsonMissing.of(),
        ) : this(id, type, mutableMapOf())

        /**
         * The ID of the item to reference.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type or is
         *   unexpectedly missing or null (e.g. if the server responded with an unexpected value).
         */
        fun id(): String = id.getRequired("id")

        /**
         * The type of item to reference. Always `item_reference`.
         *
         * @throws OpenAIInvalidDataException if the JSON field has an unexpected type (e.g. if the
         *   server responded with an unexpected value).
         */
        fun type(): Optional<Type> = type.getOptional("type")

        /**
         * Returns the raw JSON value of [id].
         *
         * Unlike [id], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

        /**
         * Returns the raw JSON value of [type].
         *
         * Unlike [type], this method doesn't throw if the JSON field has an unexpected type.
         */
        @JsonProperty("type") @ExcludeMissing fun _type(): JsonField<Type> = type

        @JsonAnySetter
        private fun putAdditionalProperty(key: String, value: JsonValue) {
            additionalProperties.put(key, value)
        }

        @JsonAnyGetter
        @ExcludeMissing
        fun _additionalProperties(): Map<String, JsonValue> =
            Collections.unmodifiableMap(additionalProperties)

        fun toBuilder() = Builder().from(this)

        companion object {

            /**
             * Returns a mutable builder for constructing an instance of [ItemReference].
             *
             * The following fields are required:
             * ```java
             * .id()
             * ```
             */
            @JvmStatic fun builder() = Builder()
        }

        /** A builder for [ItemReference]. */
        class Builder internal constructor() {

            private var id: JsonField<String>? = null
            private var type: JsonField<Type> = JsonMissing.of()
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(itemReference: ItemReference) = apply {
                id = itemReference.id
                type = itemReference.type
                additionalProperties = itemReference.additionalProperties.toMutableMap()
            }

            /** The ID of the item to reference. */
            fun id(id: String) = id(JsonField.of(id))

            /**
             * Sets [Builder.id] to an arbitrary JSON value.
             *
             * You should usually call [Builder.id] with a well-typed [String] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun id(id: JsonField<String>) = apply { this.id = id }

            /** The type of item to reference. Always `item_reference`. */
            fun type(type: Type?) = type(JsonField.ofNullable(type))

            /** Alias for calling [Builder.type] with `type.orElse(null)`. */
            fun type(type: Optional<Type>) = type(type.getOrNull())

            /**
             * Sets [Builder.type] to an arbitrary JSON value.
             *
             * You should usually call [Builder.type] with a well-typed [Type] value instead. This
             * method is primarily for setting the field to an undocumented or not yet supported
             * value.
             */
            fun type(type: JsonField<Type>) = apply { this.type = type }

            fun additionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.clear()
                putAllAdditionalProperties(additionalProperties)
            }

            fun putAdditionalProperty(key: String, value: JsonValue) = apply {
                additionalProperties.put(key, value)
            }

            fun putAllAdditionalProperties(additionalProperties: Map<String, JsonValue>) = apply {
                this.additionalProperties.putAll(additionalProperties)
            }

            fun removeAdditionalProperty(key: String) = apply { additionalProperties.remove(key) }

            fun removeAllAdditionalProperties(keys: Set<String>) = apply {
                keys.forEach(::removeAdditionalProperty)
            }

            /**
             * Returns an immutable instance of [ItemReference].
             *
             * Further updates to this [Builder] will not mutate the returned instance.
             *
             * The following fields are required:
             * ```java
             * .id()
             * ```
             *
             * @throws IllegalStateException if any required field is unset.
             */
            fun build(): ItemReference =
                ItemReference(checkRequired("id", id), type, additionalProperties.toMutableMap())
        }

        private var validated: Boolean = false

        /**
         * Validates that the types of all values in this object match their expected types
         * recursively.
         *
         * This method is _not_ forwards compatible with new types from the API for existing fields.
         *
         * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
         *   expected type.
         */
        fun validate(): ItemReference = apply {
            if (validated) {
                return@apply
            }

            id()
            type().ifPresent { it.validate() }
            validated = true
        }

        fun isValid(): Boolean =
            try {
                validate()
                true
            } catch (e: OpenAIInvalidDataException) {
                false
            }

        /**
         * Returns a score indicating how many valid values are contained in this object
         * recursively.
         *
         * Used for best match union deserialization.
         */
        @JvmSynthetic
        internal fun validity(): Int =
            (if (id.asKnown().isPresent) 1 else 0) + (type.asKnown().getOrNull()?.validity() ?: 0)

        /** The type of item to reference. Always `item_reference`. */
        class Type @JsonCreator private constructor(private val value: JsonField<String>) : Enum {

            /**
             * Returns this class instance's raw value.
             *
             * This is usually only useful if this instance was deserialized from data that doesn't
             * match any known member, and you want to know that value. For example, if the SDK is
             * on an older version than the API, then the API may respond with new members that the
             * SDK is unaware of.
             */
            @com.fasterxml.jackson.annotation.JsonValue fun _value(): JsonField<String> = value

            companion object {

                @JvmField val ITEM_REFERENCE = of("item_reference")

                @JvmStatic fun of(value: String) = Type(JsonField.of(value))
            }

            /** An enum containing [Type]'s known values. */
            enum class Known {
                ITEM_REFERENCE
            }

            /**
             * An enum containing [Type]'s known values, as well as an [_UNKNOWN] member.
             *
             * An instance of [Type] can contain an unknown value in a couple of cases:
             * - It was deserialized from data that doesn't match any known member. For example, if
             *   the SDK is on an older version than the API, then the API may respond with new
             *   members that the SDK is unaware of.
             * - It was constructed with an arbitrary value using the [of] method.
             */
            enum class Value {
                ITEM_REFERENCE,
                /** An enum member indicating that [Type] was instantiated with an unknown value. */
                _UNKNOWN,
            }

            /**
             * Returns an enum member corresponding to this class instance's value, or
             * [Value._UNKNOWN] if the class was instantiated with an unknown value.
             *
             * Use the [known] method instead if you're certain the value is always known or if you
             * want to throw for the unknown case.
             */
            fun value(): Value =
                when (this) {
                    ITEM_REFERENCE -> Value.ITEM_REFERENCE
                    else -> Value._UNKNOWN
                }

            /**
             * Returns an enum member corresponding to this class instance's value.
             *
             * Use the [value] method instead if you're uncertain the value is always known and
             * don't want to throw for the unknown case.
             *
             * @throws OpenAIInvalidDataException if this class instance's value is a not a known
             *   member.
             */
            fun known(): Known =
                when (this) {
                    ITEM_REFERENCE -> Known.ITEM_REFERENCE
                    else -> throw OpenAIInvalidDataException("Unknown Type: $value")
                }

            /**
             * Returns this class instance's primitive wire representation.
             *
             * This differs from the [toString] method because that method is primarily for
             * debugging and generally doesn't throw.
             *
             * @throws OpenAIInvalidDataException if this class instance's value does not have the
             *   expected primitive type.
             */
            fun asString(): String =
                _value().asString().orElseThrow {
                    OpenAIInvalidDataException("Value is not a String")
                }

            private var validated: Boolean = false

            /**
             * Validates that the types of all values in this object match their expected types
             * recursively.
             *
             * This method is _not_ forwards compatible with new types from the API for existing
             * fields.
             *
             * @throws OpenAIInvalidDataException if any value type in this object doesn't match its
             *   expected type.
             */
            fun validate(): Type = apply {
                if (validated) {
                    return@apply
                }

                known()
                validated = true
            }

            fun isValid(): Boolean =
                try {
                    validate()
                    true
                } catch (e: OpenAIInvalidDataException) {
                    false
                }

            /**
             * Returns a score indicating how many valid values are contained in this object
             * recursively.
             *
             * Used for best match union deserialization.
             */
            @JvmSynthetic internal fun validity(): Int = if (value() == Value._UNKNOWN) 0 else 1

            override fun equals(other: Any?): Boolean {
                if (this === other) {
                    return true
                }

                return other is Type && value == other.value
            }

            override fun hashCode() = value.hashCode()

            override fun toString() = value.toString()
        }

        override fun equals(other: Any?): Boolean {
            if (this === other) {
                return true
            }

            return other is ItemReference &&
                id == other.id &&
                type == other.type &&
                additionalProperties == other.additionalProperties
        }

        private val hashCode: Int by lazy { Objects.hash(id, type, additionalProperties) }

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "ItemReference{id=$id, type=$type, additionalProperties=$additionalProperties}"
    }
}
