# coding: utf-8

"""
    AI Stats Gateway API

    A gateway API for accessing various AI models with OpenAI-compatible endpoints.

    The version of the OpenAPI document: 1.0.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, field_validator
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_response_format import ChatCompletionsRequestResponseFormat
from ai_stats_generated.models.chat_completions_request_tool_choice import ChatCompletionsRequestToolChoice
from ai_stats_generated.models.chat_completions_request_tools_inner import ChatCompletionsRequestToolsInner
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
    model: StrictStr
    system: Optional[StrictStr] = None
    messages: Annotated[List[ChatMessage], Field(min_length=1)]
    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
    meta: Optional[StrictBool] = False
    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)]]] = 1
    tools: Optional[List[ChatCompletionsRequestToolsInner]] = None
    max_tool_calls: Optional[Annotated[int, Field(strict=True, ge=1)]] = None
    parallel_tool_calls: Optional[StrictBool] = True
    tool_choice: Optional[ChatCompletionsRequestToolChoice] = None
    top_k: Optional[Annotated[int, Field(strict=True, ge=1)]] = None
    logprobs: Optional[StrictBool] = False
    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
    response_format: Optional[ChatCompletionsRequestResponseFormat] = None
    usage: Optional[StrictBool] = None
    user_id: Optional[StrictStr] = None
    service_tier: Optional[StrictStr] = 'standard'
    __properties: ClassVar[List[str]] = ["model", "system", "messages", "reasoning", "frequency_penalty", "logit_bias", "max_output_tokens", "meta", "presence_penalty", "seed", "stream", "temperature", "tools", "max_tool_calls", "parallel_tool_calls", "tool_choice", "top_k", "logprobs", "top_logprobs", "top_p", "response_format", "usage", "user_id", "service_tier"]

    @field_validator('service_tier')
    def service_tier_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['flex', 'standard', 'priority']):
            raise ValueError("must be one of enum values ('flex', 'standard', 'priority')")
        return value

    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.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        # 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 reasoning
        if self.reasoning:
            _dict['reasoning'] = self.reasoning.to_dict()
        # override the default output from pydantic by calling `to_dict()` of each item in tools (list)
        _items = []
        if self.tools:
            for _item_tools in self.tools:
                if _item_tools:
                    _items.append(_item_tools.to_dict())
            _dict['tools'] = _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()
        # override the default output from pydantic by calling `to_dict()` of response_format
        if self.response_format:
            _dict['response_format'] = self.response_format.to_dict()
        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({
            "model": obj.get("model"),
            "system": obj.get("system"),
            "messages": [ChatMessage.from_dict(_item) for _item in obj["messages"]] if obj.get("messages") is not None else None,
            "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"),
            "meta": obj.get("meta") if obj.get("meta") is not None else False,
            "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") if obj.get("temperature") is not None else 1,
            "tools": [ChatCompletionsRequestToolsInner.from_dict(_item) for _item in obj["tools"]] if obj.get("tools") is not None else None,
            "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,
            "top_k": obj.get("top_k"),
            "logprobs": obj.get("logprobs") if obj.get("logprobs") is not None else False,
            "top_logprobs": obj.get("top_logprobs"),
            "top_p": obj.get("top_p"),
            "response_format": ChatCompletionsRequestResponseFormat.from_dict(obj["response_format"]) if obj.get("response_format") is not None else None,
            "usage": obj.get("usage"),
            "user_id": obj.get("user_id"),
            "service_tier": obj.get("service_tier") if obj.get("service_tier") is not None else 'standard'
        })
        return _obj


