"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""

from __future__ import annotations
from .anthropiccachecontroldirective import (
    AnthropicCacheControlDirective,
    AnthropicCacheControlDirectiveTypedDict,
)
from .anthropicdocumentblockparam import (
    AnthropicDocumentBlockParam,
    AnthropicDocumentBlockParamTypedDict,
)
from .anthropicimageblockparam import (
    AnthropicImageBlockParam,
    AnthropicImageBlockParamTypedDict,
)
from .anthropicsearchresultblockparam import (
    AnthropicSearchResultBlockParam,
    AnthropicSearchResultBlockParamTypedDict,
)
from .anthropictextblockparam import (
    AnthropicTextBlockParam,
    AnthropicTextBlockParamTypedDict,
)
from .anthropicwebsearchresultblockparam import (
    AnthropicWebSearchResultBlockParam,
    AnthropicWebSearchResultBlockParamTypedDict,
)
from .messagesadvisortoolresultblock import (
    MessagesAdvisorToolResultBlock,
    MessagesAdvisorToolResultBlockTypedDict,
)
from openrouter.types import (
    BaseModel,
    Nullable,
    OptionalNullable,
    UNSET,
    UNSET_SENTINEL,
    UnrecognizedStr,
)
from openrouter.utils import get_discriminator, validate_open_enum
from pydantic import Discriminator, Tag, model_serializer
from pydantic.functional_validators import PlainValidator
from typing import Any, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict


MessagesMessageParamTypeCompaction = Literal["compaction",]


class ContentCompactionTypedDict(TypedDict):
    content: Nullable[str]
    type: MessagesMessageParamTypeCompaction
    cache_control: NotRequired[AnthropicCacheControlDirectiveTypedDict]
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""


class ContentCompaction(BaseModel):
    content: Nullable[str]

    type: MessagesMessageParamTypeCompaction

    cache_control: Optional[AnthropicCacheControlDirective] = None
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["cache_control"]
        nullable_fields = ["content"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


ErrorCode = Union[
    Literal[
        "invalid_tool_input",
        "unavailable",
        "max_uses_exceeded",
        "too_many_requests",
        "query_too_long",
    ],
    UnrecognizedStr,
]


TypeWebSearchToolResultError = Literal["web_search_tool_result_error",]


class ContentWebSearchToolResultErrorTypedDict(TypedDict):
    error_code: ErrorCode
    type: TypeWebSearchToolResultError


class ContentWebSearchToolResultError(BaseModel):
    error_code: Annotated[ErrorCode, PlainValidator(validate_open_enum(False))]

    type: TypeWebSearchToolResultError


MessagesMessageParamContentUnion3TypedDict = TypeAliasType(
    "MessagesMessageParamContentUnion3TypedDict",
    Union[
        ContentWebSearchToolResultErrorTypedDict,
        List[AnthropicWebSearchResultBlockParamTypedDict],
    ],
)


MessagesMessageParamContentUnion3 = TypeAliasType(
    "MessagesMessageParamContentUnion3",
    Union[ContentWebSearchToolResultError, List[AnthropicWebSearchResultBlockParam]],
)


TypeWebSearchToolResult = Literal["web_search_tool_result",]


class ContentWebSearchToolResultTypedDict(TypedDict):
    content: MessagesMessageParamContentUnion3TypedDict
    tool_use_id: str
    type: TypeWebSearchToolResult
    cache_control: NotRequired[AnthropicCacheControlDirectiveTypedDict]
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""


class ContentWebSearchToolResult(BaseModel):
    content: MessagesMessageParamContentUnion3

    tool_use_id: str

    type: TypeWebSearchToolResult

    cache_control: Optional[AnthropicCacheControlDirective] = None
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""


TypeServerToolUse = Literal["server_tool_use",]


class ContentServerToolUseTypedDict(TypedDict):
    id: str
    name: str
    type: TypeServerToolUse
    cache_control: NotRequired[AnthropicCacheControlDirectiveTypedDict]
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""
    input: NotRequired[Nullable[Any]]


class ContentServerToolUse(BaseModel):
    id: str

    name: str

    type: TypeServerToolUse

    cache_control: Optional[AnthropicCacheControlDirective] = None
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""

    input: OptionalNullable[Any] = UNSET

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["cache_control", "input"]
        nullable_fields = ["input"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


TypeRedactedThinking = Literal["redacted_thinking",]


class ContentRedactedThinkingTypedDict(TypedDict):
    data: str
    type: TypeRedactedThinking


class ContentRedactedThinking(BaseModel):
    data: str

    type: TypeRedactedThinking


TypeThinking = Literal["thinking",]


class ContentThinkingTypedDict(TypedDict):
    signature: str
    thinking: str
    type: TypeThinking


class ContentThinking(BaseModel):
    signature: str

    thinking: str

    type: TypeThinking


TypeToolReference = Literal["tool_reference",]


class ContentToolReferenceTypedDict(TypedDict):
    tool_name: str
    type: TypeToolReference


class ContentToolReference(BaseModel):
    tool_name: str

    type: TypeToolReference


MessagesMessageParamContentUnion1TypedDict = TypeAliasType(
    "MessagesMessageParamContentUnion1TypedDict",
    Union[
        ContentToolReferenceTypedDict,
        AnthropicImageBlockParamTypedDict,
        AnthropicTextBlockParamTypedDict,
        AnthropicSearchResultBlockParamTypedDict,
        AnthropicDocumentBlockParamTypedDict,
    ],
)


MessagesMessageParamContentUnion1 = Annotated[
    Union[
        Annotated[AnthropicTextBlockParam, Tag("text")],
        Annotated[AnthropicImageBlockParam, Tag("image")],
        Annotated[ContentToolReference, Tag("tool_reference")],
        Annotated[AnthropicSearchResultBlockParam, Tag("search_result")],
        Annotated[AnthropicDocumentBlockParam, Tag("document")],
    ],
    Discriminator(lambda m: get_discriminator(m, "type", "type")),
]


MessagesMessageParamContentUnion2TypedDict = TypeAliasType(
    "MessagesMessageParamContentUnion2TypedDict",
    Union[str, List[MessagesMessageParamContentUnion1TypedDict]],
)


MessagesMessageParamContentUnion2 = TypeAliasType(
    "MessagesMessageParamContentUnion2",
    Union[str, List[MessagesMessageParamContentUnion1]],
)


TypeToolResult = Literal["tool_result",]


class ContentToolResultTypedDict(TypedDict):
    tool_use_id: str
    type: TypeToolResult
    cache_control: NotRequired[AnthropicCacheControlDirectiveTypedDict]
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""
    content: NotRequired[MessagesMessageParamContentUnion2TypedDict]
    is_error: NotRequired[bool]


class ContentToolResult(BaseModel):
    tool_use_id: str

    type: TypeToolResult

    cache_control: Optional[AnthropicCacheControlDirective] = None
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""

    content: Optional[MessagesMessageParamContentUnion2] = None

    is_error: Optional[bool] = None


TypeToolUse = Literal["tool_use",]


class ContentToolUseTypedDict(TypedDict):
    id: str
    name: str
    type: TypeToolUse
    cache_control: NotRequired[AnthropicCacheControlDirectiveTypedDict]
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""
    input: NotRequired[Nullable[Any]]


class ContentToolUse(BaseModel):
    id: str

    name: str

    type: TypeToolUse

    cache_control: Optional[AnthropicCacheControlDirective] = None
    r"""Enable automatic prompt caching. When set at the top level, the system automatically applies cache breakpoints to the last cacheable block in the request. Currently supported for Anthropic Claude models."""

    input: OptionalNullable[Any] = UNSET

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["cache_control", "input"]
        nullable_fields = ["input"]
        null_default_fields = []

        serialized = handler(self)

        m = {}

        for n, f in type(self).model_fields.items():
            k = f.alias or n
            val = serialized.get(k)
            serialized.pop(k, None)

            optional_nullable = k in optional_fields and k in nullable_fields
            is_set = (
                self.__pydantic_fields_set__.intersection({n})
                or k in null_default_fields
            )  # pylint: disable=no-member

            if val is not None and val != UNSET_SENTINEL:
                m[k] = val
            elif val != UNSET_SENTINEL and (
                not k in optional_fields or (optional_nullable and is_set)
            ):
                m[k] = val

        return m


MessagesMessageParamContentUnion4TypedDict = TypeAliasType(
    "MessagesMessageParamContentUnion4TypedDict",
    Union[
        ContentRedactedThinkingTypedDict,
        AnthropicImageBlockParamTypedDict,
        ContentThinkingTypedDict,
        ContentCompactionTypedDict,
        MessagesAdvisorToolResultBlockTypedDict,
        AnthropicTextBlockParamTypedDict,
        ContentWebSearchToolResultTypedDict,
        ContentToolUseTypedDict,
        ContentToolResultTypedDict,
        ContentServerToolUseTypedDict,
        AnthropicDocumentBlockParamTypedDict,
        AnthropicSearchResultBlockParamTypedDict,
    ],
)


MessagesMessageParamContentUnion4 = Annotated[
    Union[
        Annotated[AnthropicTextBlockParam, Tag("text")],
        Annotated[AnthropicImageBlockParam, Tag("image")],
        Annotated[AnthropicDocumentBlockParam, Tag("document")],
        Annotated[ContentToolUse, Tag("tool_use")],
        Annotated[ContentToolResult, Tag("tool_result")],
        Annotated[ContentThinking, Tag("thinking")],
        Annotated[ContentRedactedThinking, Tag("redacted_thinking")],
        Annotated[ContentServerToolUse, Tag("server_tool_use")],
        Annotated[ContentWebSearchToolResult, Tag("web_search_tool_result")],
        Annotated[AnthropicSearchResultBlockParam, Tag("search_result")],
        Annotated[ContentCompaction, Tag("compaction")],
        Annotated[MessagesAdvisorToolResultBlock, Tag("advisor_tool_result")],
    ],
    Discriminator(lambda m: get_discriminator(m, "type", "type")),
]


MessagesMessageParamContentUnion5TypedDict = TypeAliasType(
    "MessagesMessageParamContentUnion5TypedDict",
    Union[str, List[MessagesMessageParamContentUnion4TypedDict]],
)


MessagesMessageParamContentUnion5 = TypeAliasType(
    "MessagesMessageParamContentUnion5",
    Union[str, List[MessagesMessageParamContentUnion4]],
)


MessagesMessageParamRole = Union[
    Literal[
        "user",
        "assistant",
        "system",
    ],
    UnrecognizedStr,
]


class MessagesMessageParamTypedDict(TypedDict):
    r"""Anthropic message with OpenRouter extensions"""

    content: MessagesMessageParamContentUnion5TypedDict
    role: MessagesMessageParamRole


class MessagesMessageParam(BaseModel):
    r"""Anthropic message with OpenRouter extensions"""

    content: MessagesMessageParamContentUnion5

    role: Annotated[MessagesMessageParamRole, PlainValidator(validate_open_enum(False))]
