# coding: utf-8

"""
    AI Stats Gateway API

    Programmatic access to the AI Stats AI Gateway. All endpoints forward requests to the best available provider for the specified model, and return normalised responses with clear structured metadata.

    The version of the OpenAPI document: 0.1.0
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from pydantic import BaseModel, ConfigDict, Field, StrictBool, StrictFloat, StrictInt, StrictStr
from typing import Any, ClassVar, Dict, List, Optional, Union
from typing_extensions import Annotated
from ai_stats_generated.models.chat_completions_request_reasoning import ChatCompletionsRequestReasoning
from ai_stats_generated.models.chat_completions_request_tool_choice import ChatCompletionsRequestToolChoice
from ai_stats_generated.models.chat_message import ChatMessage
from typing import Optional, Set
from typing_extensions import Self

class ChatCompletionsRequest(BaseModel):
    """
    ChatCompletionsRequest
    """ # noqa: E501
    reasoning: Optional[ChatCompletionsRequestReasoning] = None
    frequency_penalty: Optional[Union[Annotated[float, Field(le=2, strict=True, ge=-2)], Annotated[int, Field(le=2, strict=True, ge=-2)]]] = None
    logit_bias: Optional[Dict[str, Union[StrictFloat, StrictInt]]] = None
    max_output_tokens: Optional[Annotated[int, Field(strict=True, ge=1)]] = None
    max_completions_tokens: Optional[Annotated[int, Field(strict=True, ge=1)]] = None
    meta: Optional[StrictBool] = Field(default=False, description="Include gateway metadata in the response.")
    model: StrictStr
    messages: Annotated[List[ChatMessage], Field(min_length=1)]
    presence_penalty: Optional[Union[Annotated[float, Field(le=2, strict=True, ge=-2)], Annotated[int, Field(le=2, strict=True, ge=-2)]]] = None
    seed: Optional[Annotated[int, Field(le=9223372036854776000, strict=True, ge=-9223372036854776000)]] = None
    stream: Optional[StrictBool] = False
    temperature: Optional[Union[Annotated[float, Field(le=2, strict=True, ge=0)], Annotated[int, Field(le=2, strict=True, ge=0)]]] = None
    tools: Optional[List[Dict[str, Any]]] = None
    max_tool_calls: Optional[Annotated[int, Field(strict=True, ge=1)]] = None
    parallel_tool_calls: Optional[StrictBool] = True
    tool_choice: Optional[ChatCompletionsRequestToolChoice] = None
    logprobs: Optional[StrictBool] = None
    top_logprobs: Optional[Annotated[int, Field(le=20, strict=True, ge=0)]] = None
    top_p: Optional[Union[Annotated[float, Field(le=1, strict=True, ge=0)], Annotated[int, Field(le=1, strict=True, ge=0)]]] = None
    usage: Optional[StrictBool] = Field(default=True, description="Include token usage details in the response.")
    additional_properties: Dict[str, Any] = {}
    __properties: ClassVar[List[str]] = ["reasoning", "frequency_penalty", "logit_bias", "max_output_tokens", "max_completions_tokens", "meta", "model", "messages", "presence_penalty", "seed", "stream", "temperature", "tools", "max_tool_calls", "parallel_tool_calls", "tool_choice", "logprobs", "top_logprobs", "top_p", "usage"]

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of ChatCompletionsRequest from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        * Fields in `self.additional_properties` are added to the output dict.
        """
        excluded_fields: Set[str] = set([
            "additional_properties",
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # override the default output from pydantic by calling `to_dict()` of reasoning
        if self.reasoning:
            _dict['reasoning'] = self.reasoning.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in messages (list)
        _items = []
        if self.messages:
            for _item_messages in self.messages:
                if _item_messages:
                    _items.append(_item_messages.to_dict())
            _dict['messages'] = _items
        # override the default output from pydantic by calling `to_dict()` of tool_choice
        if self.tool_choice:
            _dict['tool_choice'] = self.tool_choice.to_dict()
        # puts key-value pairs in additional_properties in the top level
        if self.additional_properties is not None:
            for _key, _value in self.additional_properties.items():
                _dict[_key] = _value

        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of ChatCompletionsRequest from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "reasoning": ChatCompletionsRequestReasoning.from_dict(obj["reasoning"]) if obj.get("reasoning") is not None else None,
            "frequency_penalty": obj.get("frequency_penalty"),
            "logit_bias": obj.get("logit_bias"),
            "max_output_tokens": obj.get("max_output_tokens"),
            "max_completions_tokens": obj.get("max_completions_tokens"),
            "meta": obj.get("meta") if obj.get("meta") is not None else False,
            "model": obj.get("model"),
            "messages": [ChatMessage.from_dict(_item) for _item in obj["messages"]] if obj.get("messages") is not None else None,
            "presence_penalty": obj.get("presence_penalty"),
            "seed": obj.get("seed"),
            "stream": obj.get("stream") if obj.get("stream") is not None else False,
            "temperature": obj.get("temperature"),
            "tools": obj.get("tools"),
            "max_tool_calls": obj.get("max_tool_calls"),
            "parallel_tool_calls": obj.get("parallel_tool_calls") if obj.get("parallel_tool_calls") is not None else True,
            "tool_choice": ChatCompletionsRequestToolChoice.from_dict(obj["tool_choice"]) if obj.get("tool_choice") is not None else None,
            "logprobs": obj.get("logprobs"),
            "top_logprobs": obj.get("top_logprobs"),
            "top_p": obj.get("top_p"),
            "usage": obj.get("usage") if obj.get("usage") is not None else True
        })
        # store additional fields in additional_properties
        for _key in obj.keys():
            if _key not in cls.__properties:
                _obj.additional_properties[_key] = obj.get(_key)

        return _obj


