# This file was auto-generated by Fern from our API Definition.

import typing
from json.decoder import JSONDecodeError

from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..core.unchecked_base_model import construct_type
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.chat_completion import ChatCompletion
from ..types.http_validation_error import HttpValidationError
from .types.chat_completion_request_messages_item import ChatCompletionRequestMessagesItem
from .types.chat_completion_request_stop import ChatCompletionRequestStop

# this is used as the default value for optional parameters
OMIT = typing.cast(typing.Any, ...)


class RawChatClient:
    def __init__(self, *, client_wrapper: SyncClientWrapper):
        self._client_wrapper = client_wrapper

    def create_chat_completion(
        self,
        *,
        model: str,
        messages: typing.Sequence[ChatCompletionRequestMessagesItem],
        temperature: typing.Optional[float] = OMIT,
        top_p: typing.Optional[float] = OMIT,
        n: typing.Optional[int] = OMIT,
        stream: typing.Optional[bool] = OMIT,
        stop: typing.Optional[ChatCompletionRequestStop] = OMIT,
        max_tokens: typing.Optional[int] = OMIT,
        presence_penalty: typing.Optional[float] = OMIT,
        frequency_penalty: typing.Optional[float] = OMIT,
        user: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ChatCompletion]:
        """
        Create a chat completion using a Letta agent (OpenAI-compatible).

        This endpoint provides full OpenAI API compatibility. The agent is selected based on:
        - The 'model' parameter in the request (should contain an agent ID in format 'agent-...')

        When streaming is enabled (stream=true), the response will be Server-Sent Events
        with ChatCompletionChunk objects.

        Parameters
        ----------
        model : str
            ID of the model to use

        messages : typing.Sequence[ChatCompletionRequestMessagesItem]
            Messages comprising the conversation so far

        temperature : typing.Optional[float]
            Sampling temperature

        top_p : typing.Optional[float]
            Nucleus sampling parameter

        n : typing.Optional[int]
            Number of chat completion choices to generate

        stream : typing.Optional[bool]
            Whether to stream back partial progress

        stop : typing.Optional[ChatCompletionRequestStop]
            Sequences where the API will stop generating

        max_tokens : typing.Optional[int]
            Maximum number of tokens to generate

        presence_penalty : typing.Optional[float]
            Presence penalty

        frequency_penalty : typing.Optional[float]
            Frequency penalty

        user : typing.Optional[str]
            A unique identifier representing your end-user

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        HttpResponse[ChatCompletion]
            Successful response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/chat/completions",
            method="POST",
            json={
                "model": model,
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[ChatCompletionRequestMessagesItem], direction="write"
                ),
                "temperature": temperature,
                "top_p": top_p,
                "n": n,
                "stream": stream,
                "stop": convert_and_respect_annotation_metadata(
                    object_=stop, annotation=ChatCompletionRequestStop, direction="write"
                ),
                "max_tokens": max_tokens,
                "presence_penalty": presence_penalty,
                "frequency_penalty": frequency_penalty,
                "user": user,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChatCompletion,
                    construct_type(
                        type_=ChatCompletion,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


class AsyncRawChatClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def create_chat_completion(
        self,
        *,
        model: str,
        messages: typing.Sequence[ChatCompletionRequestMessagesItem],
        temperature: typing.Optional[float] = OMIT,
        top_p: typing.Optional[float] = OMIT,
        n: typing.Optional[int] = OMIT,
        stream: typing.Optional[bool] = OMIT,
        stop: typing.Optional[ChatCompletionRequestStop] = OMIT,
        max_tokens: typing.Optional[int] = OMIT,
        presence_penalty: typing.Optional[float] = OMIT,
        frequency_penalty: typing.Optional[float] = OMIT,
        user: typing.Optional[str] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ChatCompletion]:
        """
        Create a chat completion using a Letta agent (OpenAI-compatible).

        This endpoint provides full OpenAI API compatibility. The agent is selected based on:
        - The 'model' parameter in the request (should contain an agent ID in format 'agent-...')

        When streaming is enabled (stream=true), the response will be Server-Sent Events
        with ChatCompletionChunk objects.

        Parameters
        ----------
        model : str
            ID of the model to use

        messages : typing.Sequence[ChatCompletionRequestMessagesItem]
            Messages comprising the conversation so far

        temperature : typing.Optional[float]
            Sampling temperature

        top_p : typing.Optional[float]
            Nucleus sampling parameter

        n : typing.Optional[int]
            Number of chat completion choices to generate

        stream : typing.Optional[bool]
            Whether to stream back partial progress

        stop : typing.Optional[ChatCompletionRequestStop]
            Sequences where the API will stop generating

        max_tokens : typing.Optional[int]
            Maximum number of tokens to generate

        presence_penalty : typing.Optional[float]
            Presence penalty

        frequency_penalty : typing.Optional[float]
            Frequency penalty

        user : typing.Optional[str]
            A unique identifier representing your end-user

        request_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        AsyncHttpResponse[ChatCompletion]
            Successful response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/chat/completions",
            method="POST",
            json={
                "model": model,
                "messages": convert_and_respect_annotation_metadata(
                    object_=messages, annotation=typing.Sequence[ChatCompletionRequestMessagesItem], direction="write"
                ),
                "temperature": temperature,
                "top_p": top_p,
                "n": n,
                "stream": stream,
                "stop": convert_and_respect_annotation_metadata(
                    object_=stop, annotation=ChatCompletionRequestStop, direction="write"
                ),
                "max_tokens": max_tokens,
                "presence_penalty": presence_penalty,
                "frequency_penalty": frequency_penalty,
                "user": user,
            },
            headers={
                "content-type": "application/json",
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChatCompletion,
                    construct_type(
                        type_=ChatCompletion,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
