// File generated from our OpenAPI spec by Stainless.

package com.openai.models

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.ExcludeMissing
import com.openai.core.JsonField
import com.openai.core.JsonMissing
import com.openai.core.JsonValue
import com.openai.core.NoAutoDetect
import com.openai.core.checkRequired
import com.openai.core.getOrThrow
import com.openai.core.immutableEmptyMap
import com.openai.core.toImmutable
import com.openai.errors.OpenAIInvalidDataException
import java.util.Objects
import java.util.Optional
import kotlin.jvm.optionals.getOrNull

/** Messages sent by the model in response to user messages. */
@NoAutoDetect
class ChatCompletionAssistantMessageParam
@JsonCreator
private constructor(
    @JsonProperty("role") @ExcludeMissing private val role: JsonValue = JsonMissing.of(),
    @JsonProperty("audio") @ExcludeMissing private val audio: JsonField<Audio> = JsonMissing.of(),
    @JsonProperty("content")
    @ExcludeMissing
    private val content: JsonField<Content> = JsonMissing.of(),
    @JsonProperty("function_call")
    @ExcludeMissing
    private val functionCall: JsonField<FunctionCall> = JsonMissing.of(),
    @JsonProperty("name") @ExcludeMissing private val name: JsonField<String> = JsonMissing.of(),
    @JsonProperty("refusal")
    @ExcludeMissing
    private val refusal: JsonField<String> = JsonMissing.of(),
    @JsonProperty("tool_calls")
    @ExcludeMissing
    private val toolCalls: JsonField<List<ChatCompletionMessageToolCall>> = JsonMissing.of(),
    @JsonAnySetter private val additionalProperties: Map<String, JsonValue> = immutableEmptyMap(),
) {

    /** The role of the messages author, in this case `assistant`. */
    @JsonProperty("role") @ExcludeMissing fun _role(): JsonValue = role

    /**
     * Data about a previous audio response from the model.
     * [Learn more](https://platform.openai.com/docs/guides/audio).
     */
    fun audio(): Optional<Audio> = Optional.ofNullable(audio.getNullable("audio"))

    /**
     * The contents of the assistant message. Required unless `tool_calls` or `function_call` is
     * specified.
     */
    fun content(): Optional<Content> = Optional.ofNullable(content.getNullable("content"))

    /**
     * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be
     * called, as generated by the model.
     */
    @Deprecated("deprecated")
    fun functionCall(): Optional<FunctionCall> =
        Optional.ofNullable(functionCall.getNullable("function_call"))

    /**
     * An optional name for the participant. Provides the model information to differentiate between
     * participants of the same role.
     */
    fun name(): Optional<String> = Optional.ofNullable(name.getNullable("name"))

    /** The refusal message by the assistant. */
    fun refusal(): Optional<String> = Optional.ofNullable(refusal.getNullable("refusal"))

    /** The tool calls generated by the model, such as function calls. */
    fun toolCalls(): Optional<List<ChatCompletionMessageToolCall>> =
        Optional.ofNullable(toolCalls.getNullable("tool_calls"))

    /**
     * Data about a previous audio response from the model.
     * [Learn more](https://platform.openai.com/docs/guides/audio).
     */
    @JsonProperty("audio") @ExcludeMissing fun _audio(): JsonField<Audio> = audio

    /**
     * The contents of the assistant message. Required unless `tool_calls` or `function_call` is
     * specified.
     */
    @JsonProperty("content") @ExcludeMissing fun _content(): JsonField<Content> = content

    /**
     * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be
     * called, as generated by the model.
     */
    @Deprecated("deprecated")
    @JsonProperty("function_call")
    @ExcludeMissing
    fun _functionCall(): JsonField<FunctionCall> = functionCall

    /**
     * An optional name for the participant. Provides the model information to differentiate between
     * participants of the same role.
     */
    @JsonProperty("name") @ExcludeMissing fun _name(): JsonField<String> = name

    /** The refusal message by the assistant. */
    @JsonProperty("refusal") @ExcludeMissing fun _refusal(): JsonField<String> = refusal

    /** The tool calls generated by the model, such as function calls. */
    @JsonProperty("tool_calls")
    @ExcludeMissing
    fun _toolCalls(): JsonField<List<ChatCompletionMessageToolCall>> = toolCalls

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

    private var validated: Boolean = false

    fun validate(): ChatCompletionAssistantMessageParam = apply {
        if (validated) {
            return@apply
        }

        _role().let {
            if (it != JsonValue.from("assistant")) {
                throw OpenAIInvalidDataException("'role' is invalid, received $it")
            }
        }
        audio().ifPresent { it.validate() }
        content().ifPresent { it.validate() }
        functionCall().ifPresent { it.validate() }
        name()
        refusal()
        toolCalls().ifPresent { it.forEach { it.validate() } }
        validated = true
    }

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

    companion object {

        @JvmStatic fun builder() = Builder()
    }

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

        private var role: JsonValue = JsonValue.from("assistant")
        private var audio: JsonField<Audio> = JsonMissing.of()
        private var content: JsonField<Content> = JsonMissing.of()
        private var functionCall: JsonField<FunctionCall> = JsonMissing.of()
        private var name: JsonField<String> = JsonMissing.of()
        private var refusal: JsonField<String> = JsonMissing.of()
        private var toolCalls: JsonField<MutableList<ChatCompletionMessageToolCall>>? = null
        private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

        @JvmSynthetic
        internal fun from(
            chatCompletionAssistantMessageParam: ChatCompletionAssistantMessageParam
        ) = apply {
            role = chatCompletionAssistantMessageParam.role
            audio = chatCompletionAssistantMessageParam.audio
            content = chatCompletionAssistantMessageParam.content
            functionCall = chatCompletionAssistantMessageParam.functionCall
            name = chatCompletionAssistantMessageParam.name
            refusal = chatCompletionAssistantMessageParam.refusal
            toolCalls = chatCompletionAssistantMessageParam.toolCalls.map { it.toMutableList() }
            additionalProperties =
                chatCompletionAssistantMessageParam.additionalProperties.toMutableMap()
        }

        /** The role of the messages author, in this case `assistant`. */
        fun role(role: JsonValue) = apply { this.role = role }

        /**
         * Data about a previous audio response from the model.
         * [Learn more](https://platform.openai.com/docs/guides/audio).
         */
        fun audio(audio: Audio?) = audio(JsonField.ofNullable(audio))

        /**
         * Data about a previous audio response from the model.
         * [Learn more](https://platform.openai.com/docs/guides/audio).
         */
        fun audio(audio: Optional<Audio>) = audio(audio.orElse(null))

        /**
         * Data about a previous audio response from the model.
         * [Learn more](https://platform.openai.com/docs/guides/audio).
         */
        fun audio(audio: JsonField<Audio>) = apply { this.audio = audio }

        /**
         * The contents of the assistant message. Required unless `tool_calls` or `function_call` is
         * specified.
         */
        fun content(content: Content?) = content(JsonField.ofNullable(content))

        /**
         * The contents of the assistant message. Required unless `tool_calls` or `function_call` is
         * specified.
         */
        fun content(content: Optional<Content>) = content(content.orElse(null))

        /**
         * The contents of the assistant message. Required unless `tool_calls` or `function_call` is
         * specified.
         */
        fun content(content: JsonField<Content>) = apply { this.content = content }

        /** The contents of the assistant message. */
        fun content(text: String) = content(Content.ofText(text))

        /**
         * An array of content parts with a defined type. Can be one or more of type `text`, or
         * exactly one of type `refusal`.
         */
        fun contentOfArrayOfContentParts(
            arrayOfContentParts: List<Content.ChatCompletionRequestAssistantMessageContentPart>
        ) = content(Content.ofArrayOfContentParts(arrayOfContentParts))

        /**
         * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should
         * be called, as generated by the model.
         */
        @Deprecated("deprecated")
        fun functionCall(functionCall: FunctionCall?) =
            functionCall(JsonField.ofNullable(functionCall))

        /**
         * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should
         * be called, as generated by the model.
         */
        @Deprecated("deprecated")
        fun functionCall(functionCall: Optional<FunctionCall>) =
            functionCall(functionCall.orElse(null))

        /**
         * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should
         * be called, as generated by the model.
         */
        @Deprecated("deprecated")
        fun functionCall(functionCall: JsonField<FunctionCall>) = apply {
            this.functionCall = functionCall
        }

        /**
         * An optional name for the participant. Provides the model information to differentiate
         * between participants of the same role.
         */
        fun name(name: String) = name(JsonField.of(name))

        /**
         * An optional name for the participant. Provides the model information to differentiate
         * between participants of the same role.
         */
        fun name(name: JsonField<String>) = apply { this.name = name }

        /** The refusal message by the assistant. */
        fun refusal(refusal: String?) = refusal(JsonField.ofNullable(refusal))

        /** The refusal message by the assistant. */
        fun refusal(refusal: Optional<String>) = refusal(refusal.orElse(null))

        /** The refusal message by the assistant. */
        fun refusal(refusal: JsonField<String>) = apply { this.refusal = refusal }

        /** The tool calls generated by the model, such as function calls. */
        fun toolCalls(toolCalls: List<ChatCompletionMessageToolCall>) =
            toolCalls(JsonField.of(toolCalls))

        /** The tool calls generated by the model, such as function calls. */
        fun toolCalls(toolCalls: JsonField<List<ChatCompletionMessageToolCall>>) = apply {
            this.toolCalls = toolCalls.map { it.toMutableList() }
        }

        /** The tool calls generated by the model, such as function calls. */
        fun addToolCall(toolCall: ChatCompletionMessageToolCall) = apply {
            toolCalls =
                (toolCalls ?: JsonField.of(mutableListOf())).apply {
                    asKnown()
                        .orElseThrow {
                            IllegalStateException(
                                "Field was set to non-list type: ${javaClass.simpleName}"
                            )
                        }
                        .add(toolCall)
                }
        }

        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)
        }

        fun build(): ChatCompletionAssistantMessageParam =
            ChatCompletionAssistantMessageParam(
                role,
                audio,
                content,
                functionCall,
                name,
                refusal,
                (toolCalls ?: JsonMissing.of()).map { it.toImmutable() },
                additionalProperties.toImmutable(),
            )
    }

    /**
     * Data about a previous audio response from the model.
     * [Learn more](https://platform.openai.com/docs/guides/audio).
     */
    @NoAutoDetect
    class Audio
    @JsonCreator
    private constructor(
        @JsonProperty("id") @ExcludeMissing private val id: JsonField<String> = JsonMissing.of(),
        @JsonAnySetter
        private val additionalProperties: Map<String, JsonValue> = immutableEmptyMap(),
    ) {

        /** Unique identifier for a previous audio response from the model. */
        fun id(): String = id.getRequired("id")

        /** Unique identifier for a previous audio response from the model. */
        @JsonProperty("id") @ExcludeMissing fun _id(): JsonField<String> = id

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

        private var validated: Boolean = false

        fun validate(): Audio = apply {
            if (validated) {
                return@apply
            }

            id()
            validated = true
        }

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

        companion object {

            @JvmStatic fun builder() = Builder()
        }

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

            private var id: JsonField<String>? = null
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(audio: Audio) = apply {
                id = audio.id
                additionalProperties = audio.additionalProperties.toMutableMap()
            }

            /** Unique identifier for a previous audio response from the model. */
            fun id(id: String) = id(JsonField.of(id))

            /** Unique identifier for a previous audio response from the model. */
            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)
            }

            fun build(): Audio = Audio(checkRequired("id", id), additionalProperties.toImmutable())
        }

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

            return /* spotless:off */ other is Audio && id == other.id && additionalProperties == other.additionalProperties /* spotless:on */
        }

        /* spotless:off */
        private val hashCode: Int by lazy { Objects.hash(id, additionalProperties) }
        /* spotless:on */

        override fun hashCode(): Int = hashCode

        override fun toString() = "Audio{id=$id, additionalProperties=$additionalProperties}"
    }

    /**
     * The contents of the assistant message. Required unless `tool_calls` or `function_call` is
     * specified.
     */
    @JsonDeserialize(using = Content.Deserializer::class)
    @JsonSerialize(using = Content.Serializer::class)
    class Content
    private constructor(
        private val text: String? = null,
        private val arrayOfContentParts: List<ChatCompletionRequestAssistantMessageContentPart>? =
            null,
        private val _json: JsonValue? = null,
    ) {

        /** The contents of the assistant message. */
        fun text(): Optional<String> = Optional.ofNullable(text)

        /**
         * An array of content parts with a defined type. Can be one or more of type `text`, or
         * exactly one of type `refusal`.
         */
        fun arrayOfContentParts():
            Optional<List<ChatCompletionRequestAssistantMessageContentPart>> =
            Optional.ofNullable(arrayOfContentParts)

        fun isText(): Boolean = text != null

        fun isArrayOfContentParts(): Boolean = arrayOfContentParts != null

        /** The contents of the assistant message. */
        fun asText(): String = text.getOrThrow("text")

        /**
         * An array of content parts with a defined type. Can be one or more of type `text`, or
         * exactly one of type `refusal`.
         */
        fun asArrayOfContentParts(): List<ChatCompletionRequestAssistantMessageContentPart> =
            arrayOfContentParts.getOrThrow("arrayOfContentParts")

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

        fun <T> accept(visitor: Visitor<T>): T {
            return when {
                text != null -> visitor.visitText(text)
                arrayOfContentParts != null -> visitor.visitArrayOfContentParts(arrayOfContentParts)
                else -> visitor.unknown(_json)
            }
        }

        private var validated: Boolean = false

        fun validate(): Content = apply {
            if (validated) {
                return@apply
            }

            accept(
                object : Visitor<Unit> {
                    override fun visitText(text: String) {}

                    override fun visitArrayOfContentParts(
                        arrayOfContentParts: List<ChatCompletionRequestAssistantMessageContentPart>
                    ) {
                        arrayOfContentParts.forEach { it.validate() }
                    }
                }
            )
            validated = true
        }

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

            return /* spotless:off */ other is Content && text == other.text && arrayOfContentParts == other.arrayOfContentParts /* spotless:on */
        }

        override fun hashCode(): Int = /* spotless:off */ Objects.hash(text, arrayOfContentParts) /* spotless:on */

        override fun toString(): String =
            when {
                text != null -> "Content{text=$text}"
                arrayOfContentParts != null -> "Content{arrayOfContentParts=$arrayOfContentParts}"
                _json != null -> "Content{_unknown=$_json}"
                else -> throw IllegalStateException("Invalid Content")
            }

        companion object {

            /** The contents of the assistant message. */
            @JvmStatic fun ofText(text: String) = Content(text = text)

            /**
             * An array of content parts with a defined type. Can be one or more of type `text`, or
             * exactly one of type `refusal`.
             */
            @JvmStatic
            fun ofArrayOfContentParts(
                arrayOfContentParts: List<ChatCompletionRequestAssistantMessageContentPart>
            ) = Content(arrayOfContentParts = arrayOfContentParts)
        }

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

            /** The contents of the assistant message. */
            fun visitText(text: String): T

            /**
             * An array of content parts with a defined type. Can be one or more of type `text`, or
             * exactly one of type `refusal`.
             */
            fun visitArrayOfContentParts(
                arrayOfContentParts: List<ChatCompletionRequestAssistantMessageContentPart>
            ): T

            /**
             * Maps an unknown variant of [Content] to a value of type [T].
             *
             * An instance of [Content] 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 Content: $json")
            }
        }

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

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

                tryDeserialize(node, jacksonTypeRef<String>())?.let {
                    return Content(text = it, _json = json)
                }
                tryDeserialize(
                        node,
                        jacksonTypeRef<List<ChatCompletionRequestAssistantMessageContentPart>>()
                    ) {
                        it.forEach { it.validate() }
                    }
                    ?.let {
                        return Content(arrayOfContentParts = it, _json = json)
                    }

                return Content(_json = json)
            }
        }

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

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

        /** Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation). */
        @JsonDeserialize(
            using = ChatCompletionRequestAssistantMessageContentPart.Deserializer::class
        )
        @JsonSerialize(using = ChatCompletionRequestAssistantMessageContentPart.Serializer::class)
        class ChatCompletionRequestAssistantMessageContentPart
        private constructor(
            private val text: ChatCompletionContentPartText? = null,
            private val refusal: ChatCompletionContentPartRefusal? = null,
            private val _json: JsonValue? = null,
        ) {

            /**
             * Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation).
             */
            fun text(): Optional<ChatCompletionContentPartText> = Optional.ofNullable(text)

            fun refusal(): Optional<ChatCompletionContentPartRefusal> = Optional.ofNullable(refusal)

            fun isText(): Boolean = text != null

            fun isRefusal(): Boolean = refusal != null

            /**
             * Learn about [text inputs](https://platform.openai.com/docs/guides/text-generation).
             */
            fun asText(): ChatCompletionContentPartText = text.getOrThrow("text")

            fun asRefusal(): ChatCompletionContentPartRefusal = refusal.getOrThrow("refusal")

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

            fun <T> accept(visitor: Visitor<T>): T {
                return when {
                    text != null -> visitor.visitText(text)
                    refusal != null -> visitor.visitRefusal(refusal)
                    else -> visitor.unknown(_json)
                }
            }

            private var validated: Boolean = false

            fun validate(): ChatCompletionRequestAssistantMessageContentPart = apply {
                if (validated) {
                    return@apply
                }

                accept(
                    object : Visitor<Unit> {
                        override fun visitText(text: ChatCompletionContentPartText) {
                            text.validate()
                        }

                        override fun visitRefusal(refusal: ChatCompletionContentPartRefusal) {
                            refusal.validate()
                        }
                    }
                )
                validated = true
            }

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

                return /* spotless:off */ other is ChatCompletionRequestAssistantMessageContentPart && text == other.text && refusal == other.refusal /* spotless:on */
            }

            override fun hashCode(): Int = /* spotless:off */ Objects.hash(text, refusal) /* spotless:on */

            override fun toString(): String =
                when {
                    text != null -> "ChatCompletionRequestAssistantMessageContentPart{text=$text}"
                    refusal != null ->
                        "ChatCompletionRequestAssistantMessageContentPart{refusal=$refusal}"
                    _json != null ->
                        "ChatCompletionRequestAssistantMessageContentPart{_unknown=$_json}"
                    else ->
                        throw IllegalStateException(
                            "Invalid ChatCompletionRequestAssistantMessageContentPart"
                        )
                }

            companion object {

                /**
                 * Learn about
                 * [text inputs](https://platform.openai.com/docs/guides/text-generation).
                 */
                @JvmStatic
                fun ofText(text: ChatCompletionContentPartText) =
                    ChatCompletionRequestAssistantMessageContentPart(text = text)

                @JvmStatic
                fun ofRefusal(refusal: ChatCompletionContentPartRefusal) =
                    ChatCompletionRequestAssistantMessageContentPart(refusal = refusal)
            }

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

                /**
                 * Learn about
                 * [text inputs](https://platform.openai.com/docs/guides/text-generation).
                 */
                fun visitText(text: ChatCompletionContentPartText): T

                fun visitRefusal(refusal: ChatCompletionContentPartRefusal): T

                /**
                 * Maps an unknown variant of [ChatCompletionRequestAssistantMessageContentPart] to
                 * a value of type [T].
                 *
                 * An instance of [ChatCompletionRequestAssistantMessageContentPart] 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 ChatCompletionRequestAssistantMessageContentPart: $json"
                    )
                }
            }

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

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

                    when (type) {
                        "text" -> {
                            tryDeserialize(node, jacksonTypeRef<ChatCompletionContentPartText>()) {
                                    it.validate()
                                }
                                ?.let {
                                    return ChatCompletionRequestAssistantMessageContentPart(
                                        text = it,
                                        _json = json
                                    )
                                }
                        }
                        "refusal" -> {
                            tryDeserialize(
                                    node,
                                    jacksonTypeRef<ChatCompletionContentPartRefusal>()
                                ) {
                                    it.validate()
                                }
                                ?.let {
                                    return ChatCompletionRequestAssistantMessageContentPart(
                                        refusal = it,
                                        _json = json
                                    )
                                }
                        }
                    }

                    return ChatCompletionRequestAssistantMessageContentPart(_json = json)
                }
            }

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

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

    /**
     * Deprecated and replaced by `tool_calls`. The name and arguments of a function that should be
     * called, as generated by the model.
     */
    @Deprecated("deprecated")
    @NoAutoDetect
    class FunctionCall
    @JsonCreator
    private constructor(
        @JsonProperty("arguments")
        @ExcludeMissing
        private val arguments: JsonField<String> = JsonMissing.of(),
        @JsonProperty("name")
        @ExcludeMissing
        private val name: JsonField<String> = JsonMissing.of(),
        @JsonAnySetter
        private val additionalProperties: Map<String, JsonValue> = immutableEmptyMap(),
    ) {

        /**
         * The arguments to call the function with, as generated by the model in JSON format. Note
         * that the model does not always generate valid JSON, and may hallucinate parameters not
         * defined by your function schema. Validate the arguments in your code before calling your
         * function.
         */
        fun arguments(): String = arguments.getRequired("arguments")

        /** The name of the function to call. */
        fun name(): String = name.getRequired("name")

        /**
         * The arguments to call the function with, as generated by the model in JSON format. Note
         * that the model does not always generate valid JSON, and may hallucinate parameters not
         * defined by your function schema. Validate the arguments in your code before calling your
         * function.
         */
        @JsonProperty("arguments") @ExcludeMissing fun _arguments(): JsonField<String> = arguments

        /** The name of the function to call. */
        @JsonProperty("name") @ExcludeMissing fun _name(): JsonField<String> = name

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

        private var validated: Boolean = false

        fun validate(): FunctionCall = apply {
            if (validated) {
                return@apply
            }

            arguments()
            name()
            validated = true
        }

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

        companion object {

            @JvmStatic fun builder() = Builder()
        }

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

            private var arguments: JsonField<String>? = null
            private var name: JsonField<String>? = null
            private var additionalProperties: MutableMap<String, JsonValue> = mutableMapOf()

            @JvmSynthetic
            internal fun from(functionCall: FunctionCall) = apply {
                arguments = functionCall.arguments
                name = functionCall.name
                additionalProperties = functionCall.additionalProperties.toMutableMap()
            }

            /**
             * The arguments to call the function with, as generated by the model in JSON format.
             * Note that the model does not always generate valid JSON, and may hallucinate
             * parameters not defined by your function schema. Validate the arguments in your code
             * before calling your function.
             */
            fun arguments(arguments: String) = arguments(JsonField.of(arguments))

            /**
             * The arguments to call the function with, as generated by the model in JSON format.
             * Note that the model does not always generate valid JSON, and may hallucinate
             * parameters not defined by your function schema. Validate the arguments in your code
             * before calling your function.
             */
            fun arguments(arguments: JsonField<String>) = apply { this.arguments = arguments }

            /** The name of the function to call. */
            fun name(name: String) = name(JsonField.of(name))

            /** The name of the function to call. */
            fun name(name: JsonField<String>) = apply { this.name = name }

            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)
            }

            fun build(): FunctionCall =
                FunctionCall(
                    checkRequired("arguments", arguments),
                    checkRequired("name", name),
                    additionalProperties.toImmutable(),
                )
        }

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

            return /* spotless:off */ other is FunctionCall && arguments == other.arguments && name == other.name && additionalProperties == other.additionalProperties /* spotless:on */
        }

        /* spotless:off */
        private val hashCode: Int by lazy { Objects.hash(arguments, name, additionalProperties) }
        /* spotless:on */

        override fun hashCode(): Int = hashCode

        override fun toString() =
            "FunctionCall{arguments=$arguments, name=$name, additionalProperties=$additionalProperties}"
    }

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

        return /* spotless:off */ other is ChatCompletionAssistantMessageParam && role == other.role && audio == other.audio && content == other.content && functionCall == other.functionCall && name == other.name && refusal == other.refusal && toolCalls == other.toolCalls && additionalProperties == other.additionalProperties /* spotless:on */
    }

    /* spotless:off */
    private val hashCode: Int by lazy { Objects.hash(role, audio, content, functionCall, name, refusal, toolCalls, additionalProperties) }
    /* spotless:on */

    override fun hashCode(): Int = hashCode

    override fun toString() =
        "ChatCompletionAssistantMessageParam{role=$role, audio=$audio, content=$content, functionCall=$functionCall, name=$name, refusal=$refusal, toolCalls=$toolCalls, additionalProperties=$additionalProperties}"
}
