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

from __future__ import annotations
from .applypatchservertool import ApplyPatchServerTool, ApplyPatchServerToolTypedDict
from .baseinputs_union import BaseInputsUnion, BaseInputsUnionTypedDict
from .basereasoningconfig import BaseReasoningConfig, BaseReasoningConfigTypedDict
from .codeinterpreterservertool import (
    CodeInterpreterServerTool,
    CodeInterpreterServerToolTypedDict,
)
from .codexlocalshelltool import CodexLocalShellTool, CodexLocalShellToolTypedDict
from .computeruseservertool import ComputerUseServerTool, ComputerUseServerToolTypedDict
from .customtool import CustomTool, CustomToolTypedDict
from .filesearchservertool import FileSearchServerTool, FileSearchServerToolTypedDict
from .imagegenerationservertool import (
    ImageGenerationServerTool,
    ImageGenerationServerToolTypedDict,
)
from .incompletedetails import IncompleteDetails, IncompleteDetailsTypedDict
from .legacy_websearchservertool import (
    LegacyWebSearchServerTool,
    LegacyWebSearchServerToolTypedDict,
)
from .mcpservertool import McpServerTool, McpServerToolTypedDict
from .openairesponsesresponsestatus import OpenAIResponsesResponseStatus
from .openairesponsestoolchoice_union import (
    OpenAIResponsesToolChoiceUnion,
    OpenAIResponsesToolChoiceUnionTypedDict,
)
from .openroutermetadata import OpenRouterMetadata, OpenRouterMetadataTypedDict
from .outputitems import OutputItems, OutputItemsTypedDict
from .preview_20250311_websearchservertool import (
    Preview20250311WebSearchServerTool,
    Preview20250311WebSearchServerToolTypedDict,
)
from .preview_websearchservertool import (
    PreviewWebSearchServerTool,
    PreviewWebSearchServerToolTypedDict,
)
from .responseserrorfield import ResponsesErrorField, ResponsesErrorFieldTypedDict
from .shellservertool import ShellServerTool, ShellServerToolTypedDict
from .storedprompttemplate import StoredPromptTemplate, StoredPromptTemplateTypedDict
from .textextendedconfig import TextExtendedConfig, TextExtendedConfigTypedDict
from .truncation import Truncation
from .usage import Usage, UsageTypedDict
from .websearchservertool import WebSearchServerTool, WebSearchServerToolTypedDict
from openrouter.types import (
    BaseModel,
    Nullable,
    OptionalNullable,
    UNSET,
    UNSET_SENTINEL,
)
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, Dict, List, Literal, Optional, Union
from typing_extensions import Annotated, NotRequired, TypeAliasType, TypedDict


OpenResponsesResultObject = Literal["response",]


OpenResponsesResultType = Literal["function",]


class OpenResponsesResultToolFunctionTypedDict(TypedDict):
    r"""Function tool definition"""

    name: str
    parameters: Nullable[Dict[str, Nullable[Any]]]
    type: OpenResponsesResultType
    description: NotRequired[Nullable[str]]
    strict: NotRequired[Nullable[bool]]


class OpenResponsesResultToolFunction(BaseModel):
    r"""Function tool definition"""

    name: str

    parameters: Nullable[Dict[str, Nullable[Any]]]

    type: OpenResponsesResultType

    description: OptionalNullable[str] = UNSET

    strict: OptionalNullable[bool] = UNSET

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = ["description", "strict"]
        nullable_fields = ["description", "parameters", "strict"]
        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


OpenResponsesResultToolUnionTypedDict = TypeAliasType(
    "OpenResponsesResultToolUnionTypedDict",
    Union[
        CodexLocalShellToolTypedDict,
        ApplyPatchServerToolTypedDict,
        ShellServerToolTypedDict,
        CodeInterpreterServerToolTypedDict,
        CustomToolTypedDict,
        ComputerUseServerToolTypedDict,
        OpenResponsesResultToolFunctionTypedDict,
        FileSearchServerToolTypedDict,
        LegacyWebSearchServerToolTypedDict,
        WebSearchServerToolTypedDict,
        Preview20250311WebSearchServerToolTypedDict,
        PreviewWebSearchServerToolTypedDict,
        McpServerToolTypedDict,
        ImageGenerationServerToolTypedDict,
    ],
)


OpenResponsesResultToolUnion = Annotated[
    Union[
        Annotated[OpenResponsesResultToolFunction, Tag("function")],
        Annotated[PreviewWebSearchServerTool, Tag("web_search_preview")],
        Annotated[
            Preview20250311WebSearchServerTool, Tag("web_search_preview_2025_03_11")
        ],
        Annotated[LegacyWebSearchServerTool, Tag("web_search")],
        Annotated[WebSearchServerTool, Tag("web_search_2025_08_26")],
        Annotated[FileSearchServerTool, Tag("file_search")],
        Annotated[ComputerUseServerTool, Tag("computer_use_preview")],
        Annotated[CodeInterpreterServerTool, Tag("code_interpreter")],
        Annotated[McpServerTool, Tag("mcp")],
        Annotated[ImageGenerationServerTool, Tag("image_generation")],
        Annotated[CodexLocalShellTool, Tag("local_shell")],
        Annotated[ShellServerTool, Tag("shell")],
        Annotated[ApplyPatchServerTool, Tag("apply_patch")],
        Annotated[CustomTool, Tag("custom")],
    ],
    Discriminator(lambda m: get_discriminator(m, "type", "type")),
]


class OpenResponsesResultTypedDict(TypedDict):
    r"""Complete non-streaming response from the Responses API"""

    completed_at: Nullable[int]
    created_at: int
    error: Nullable[ResponsesErrorFieldTypedDict]
    r"""Error information returned from the API"""
    frequency_penalty: Nullable[float]
    id: str
    incomplete_details: Nullable[IncompleteDetailsTypedDict]
    instructions: Nullable[BaseInputsUnionTypedDict]
    metadata: Nullable[Dict[str, str]]
    r"""Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed."""
    model: str
    object: OpenResponsesResultObject
    output: List[OutputItemsTypedDict]
    parallel_tool_calls: bool
    presence_penalty: Nullable[float]
    status: OpenAIResponsesResponseStatus
    temperature: Nullable[float]
    tool_choice: OpenAIResponsesToolChoiceUnionTypedDict
    tools: List[OpenResponsesResultToolUnionTypedDict]
    top_p: Nullable[float]
    background: NotRequired[Nullable[bool]]
    max_output_tokens: NotRequired[Nullable[int]]
    max_tool_calls: NotRequired[Nullable[int]]
    output_text: NotRequired[str]
    previous_response_id: NotRequired[Nullable[str]]
    prompt: NotRequired[Nullable[StoredPromptTemplateTypedDict]]
    prompt_cache_key: NotRequired[Nullable[str]]
    reasoning: NotRequired[Nullable[BaseReasoningConfigTypedDict]]
    safety_identifier: NotRequired[Nullable[str]]
    service_tier: NotRequired[Nullable[str]]
    store: NotRequired[bool]
    text: NotRequired[TextExtendedConfigTypedDict]
    r"""Text output configuration including format and verbosity"""
    top_logprobs: NotRequired[int]
    truncation: NotRequired[Nullable[Truncation]]
    usage: NotRequired[Nullable[UsageTypedDict]]
    r"""Token usage information for the response"""
    user: NotRequired[Nullable[str]]
    openrouter_metadata: NotRequired[OpenRouterMetadataTypedDict]


class OpenResponsesResult(BaseModel):
    r"""Complete non-streaming response from the Responses API"""

    completed_at: Nullable[int]

    created_at: int

    error: Nullable[ResponsesErrorField]
    r"""Error information returned from the API"""

    frequency_penalty: Nullable[float]

    id: str

    incomplete_details: Nullable[IncompleteDetails]

    instructions: Nullable[BaseInputsUnion]

    metadata: Nullable[Dict[str, str]]
    r"""Metadata key-value pairs for the request. Keys must be ≤64 characters and cannot contain brackets. Values must be ≤512 characters. Maximum 16 pairs allowed."""

    model: str

    object: OpenResponsesResultObject

    output: List[OutputItems]

    parallel_tool_calls: bool

    presence_penalty: Nullable[float]

    status: Annotated[
        OpenAIResponsesResponseStatus, PlainValidator(validate_open_enum(False))
    ]

    temperature: Nullable[float]

    tool_choice: OpenAIResponsesToolChoiceUnion

    tools: List[OpenResponsesResultToolUnion]

    top_p: Nullable[float]

    background: OptionalNullable[bool] = UNSET

    max_output_tokens: OptionalNullable[int] = UNSET

    max_tool_calls: OptionalNullable[int] = UNSET

    output_text: Optional[str] = None

    previous_response_id: OptionalNullable[str] = UNSET

    prompt: OptionalNullable[StoredPromptTemplate] = UNSET

    prompt_cache_key: OptionalNullable[str] = UNSET

    reasoning: OptionalNullable[BaseReasoningConfig] = UNSET

    safety_identifier: OptionalNullable[str] = UNSET

    service_tier: OptionalNullable[str] = UNSET

    store: Optional[bool] = None

    text: Optional[TextExtendedConfig] = None
    r"""Text output configuration including format and verbosity"""

    top_logprobs: Optional[int] = None

    truncation: Annotated[
        OptionalNullable[Truncation], PlainValidator(validate_open_enum(False))
    ] = UNSET

    usage: OptionalNullable[Usage] = UNSET
    r"""Token usage information for the response"""

    user: OptionalNullable[str] = UNSET

    openrouter_metadata: Optional[OpenRouterMetadata] = None

    @model_serializer(mode="wrap")
    def serialize_model(self, handler):
        optional_fields = [
            "background",
            "max_output_tokens",
            "max_tool_calls",
            "output_text",
            "previous_response_id",
            "prompt",
            "prompt_cache_key",
            "reasoning",
            "safety_identifier",
            "service_tier",
            "store",
            "text",
            "top_logprobs",
            "truncation",
            "usage",
            "user",
            "openrouter_metadata",
        ]
        nullable_fields = [
            "background",
            "completed_at",
            "error",
            "frequency_penalty",
            "incomplete_details",
            "instructions",
            "max_output_tokens",
            "max_tool_calls",
            "metadata",
            "presence_penalty",
            "previous_response_id",
            "prompt",
            "prompt_cache_key",
            "reasoning",
            "safety_identifier",
            "service_tier",
            "temperature",
            "top_p",
            "truncation",
            "usage",
            "user",
        ]
        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
