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

import contextlib
import typing
from json.decoder import JSONDecodeError

import httpx_sse
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pagination import AsyncPager, SyncPager
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.bad_request_error import BadRequestError
from ..errors.forbidden_error import ForbiddenError
from ..errors.not_found_error import NotFoundError
from ..types.bad_request_error_body import BadRequestErrorBody
from ..types.chat import Chat
from ..types.chat_full_response import ChatFullResponse
from ..types.chat_parameters import ChatParameters
from ..types.chat_streamed_response import ChatStreamedResponse
from ..types.error import Error
from ..types.generation_parameters import GenerationParameters
from ..types.list_chat_turns_response import ListChatTurnsResponse
from ..types.list_chats_response import ListChatsResponse
from ..types.not_found_error_body import NotFoundErrorBody
from ..types.search_corpora_parameters import SearchCorporaParameters
from ..types.turn import Turn

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


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

    def list(
        self,
        *,
        limit: typing.Optional[int] = None,
        page_key: typing.Optional[str] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SyncPager[Chat]]:
        """
        Retrieve a list of previous chats in the Vectara account.

        Parameters
        ----------
        limit : typing.Optional[int]
            The maximum number of results to return in the list.

        page_key : typing.Optional[str]
            Used to retrieve the next page of chats after the limit has been reached.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        HttpResponse[SyncPager[Chat]]
            List of chats.
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "limit": limit,
                "page_key": page_key,
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListChatsResponse,
                    parse_obj_as(
                        type_=ListChatsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _has_next = False
                _get_next = None
                if _parsed_response.metadata is not None:
                    _parsed_next = _parsed_response.metadata.page_key
                    _has_next = _parsed_next is not None and _parsed_next != ""
                    _get_next = lambda: self.list(
                        limit=limit,
                        page_key=_parsed_next,
                        request_timeout=request_timeout,
                        request_timeout_millis=request_timeout_millis,
                        request_options=request_options,
                    )
                _items = _parsed_response.chats
                return HttpResponse(
                    response=_response, data=SyncPager(has_next=_has_next, items=_items, get_next=_get_next)
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    @contextlib.contextmanager
    def create_stream(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[HttpResponse[typing.Iterator[ChatStreamedResponse]]]:
        """
        Create a chat while specifying the default retrieval parameters used by the prompt.

        Parameters
        ----------
        query : str
            The chat message or question.

        search : SearchCorporaParameters

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the chat in both the chat and query history. This overrides `chat.store`.

        intelligent_query_rewriting : typing.Optional[bool]
            Indicates whether to enable intelligent query rewriting. When enabled, the platform will attempt to
            extract metadata filter and rewrite the query to improve search results.

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

        Yields
        ------
        typing.Iterator[HttpResponse[typing.Iterator[ChatStreamedResponse]]]

        """
        with self._client_wrapper.httpx_client.stream(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "chat": convert_and_respect_annotation_metadata(
                    object_=chat, annotation=ChatParameters, direction="write"
                ),
                "save_history": save_history,
                "intelligent_query_rewriting": intelligent_query_rewriting,
                "stream_response": True,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            def stream() -> HttpResponse[typing.Iterator[ChatStreamedResponse]]:
                try:
                    if 200 <= _response.status_code < 300:

                        def _iter():
                            _event_source = httpx_sse.EventSource(_response)
                            for _sse in _event_source.iter_sse():
                                if _sse.data == None:
                                    return
                                try:
                                    yield _sse.data()
                                except Exception:
                                    pass
                            return

                        return HttpResponse(response=_response, data=_iter())
                    _response.read()
                    if _response.status_code == 400:
                        raise BadRequestError(
                            typing.cast(
                                BadRequestErrorBody,
                                parse_obj_as(
                                    type_=BadRequestErrorBody,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    if _response.status_code == 403:
                        raise ForbiddenError(
                            typing.cast(
                                Error,
                                parse_obj_as(
                                    type_=Error,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    if _response.status_code == 404:
                        raise NotFoundError(
                            typing.cast(
                                NotFoundErrorBody,
                                parse_obj_as(
                                    type_=NotFoundErrorBody,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(status_code=_response.status_code, body=_response.text)
                raise ApiError(status_code=_response.status_code, body=_response_json)

            yield stream()

    def create(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ChatFullResponse]:
        """
        Create a chat while specifying the default retrieval parameters used by the prompt.

        Parameters
        ----------
        query : str
            The chat message or question.

        search : SearchCorporaParameters

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the chat in both the chat and query history. This overrides `chat.store`.

        intelligent_query_rewriting : typing.Optional[bool]
            Indicates whether to enable intelligent query rewriting. When enabled, the platform will attempt to
            extract metadata filter and rewrite the query to improve search results.

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

        Returns
        -------
        HttpResponse[ChatFullResponse]

        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "chat": convert_and_respect_annotation_metadata(
                    object_=chat, annotation=ChatParameters, direction="write"
                ),
                "save_history": save_history,
                "intelligent_query_rewriting": intelligent_query_rewriting,
                "stream_response": False,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChatFullResponse,
                    parse_obj_as(
                        type_=ChatFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get(
        self,
        chat_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Chat]:
        """
        Get a chat summary to view what started the chat, but not subsequent turns.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        HttpResponse[Chat]
            A chat.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Chat,
                    parse_obj_as(
                        type_=Chat,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def delete(
        self,
        chat_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[None]:
        """
        Delete a chat and any turns it contains permanently.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="DELETE",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def list_turns(
        self,
        chat_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ListChatTurnsResponse]:
        """
        List all turns in a chat to see all message and response pairs that make up the dialog.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        HttpResponse[ListChatTurnsResponse]
            List of turns.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ListChatTurnsResponse,
                    parse_obj_as(
                        type_=ListChatTurnsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    @contextlib.contextmanager
    def create_turns_stream(
        self,
        chat_id: str,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[HttpResponse[typing.Iterator[ChatStreamedResponse]]]:
        """
        Create a new turn in the chat. Each conversation has a series of `turn` objects, which are the sequence of message and response pairs that make up the dialog.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        query : str
            The chat message or question.

        search : SearchCorporaParameters

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the chat in both the chat and query history. This overrides `chat.store`.

        intelligent_query_rewriting : typing.Optional[bool]
            Indicates whether to enable intelligent query rewriting. When enabled, the platform will attempt to
            extract metadata filter and rewrite the query to improve search results.

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

        Yields
        ------
        typing.Iterator[HttpResponse[typing.Iterator[ChatStreamedResponse]]]

        """
        with self._client_wrapper.httpx_client.stream(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "chat": convert_and_respect_annotation_metadata(
                    object_=chat, annotation=ChatParameters, direction="write"
                ),
                "save_history": save_history,
                "intelligent_query_rewriting": intelligent_query_rewriting,
                "stream_response": True,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            def stream() -> HttpResponse[typing.Iterator[ChatStreamedResponse]]:
                try:
                    if 200 <= _response.status_code < 300:

                        def _iter():
                            _event_source = httpx_sse.EventSource(_response)
                            for _sse in _event_source.iter_sse():
                                if _sse.data == None:
                                    return
                                try:
                                    yield _sse.data()
                                except Exception:
                                    pass
                            return

                        return HttpResponse(response=_response, data=_iter())
                    _response.read()
                    if _response.status_code == 400:
                        raise BadRequestError(
                            typing.cast(
                                BadRequestErrorBody,
                                parse_obj_as(
                                    type_=BadRequestErrorBody,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    if _response.status_code == 403:
                        raise ForbiddenError(
                            typing.cast(
                                Error,
                                parse_obj_as(
                                    type_=Error,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    if _response.status_code == 404:
                        raise NotFoundError(
                            typing.cast(
                                NotFoundErrorBody,
                                parse_obj_as(
                                    type_=NotFoundErrorBody,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(status_code=_response.status_code, body=_response.text)
                raise ApiError(status_code=_response.status_code, body=_response_json)

            yield stream()

    def create_turns(
        self,
        chat_id: str,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ChatFullResponse]:
        """
        Create a new turn in the chat. Each conversation has a series of `turn` objects, which are the sequence of message and response pairs that make up the dialog.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        query : str
            The chat message or question.

        search : SearchCorporaParameters

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the chat in both the chat and query history. This overrides `chat.store`.

        intelligent_query_rewriting : typing.Optional[bool]
            Indicates whether to enable intelligent query rewriting. When enabled, the platform will attempt to
            extract metadata filter and rewrite the query to improve search results.

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

        Returns
        -------
        HttpResponse[ChatFullResponse]

        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "chat": convert_and_respect_annotation_metadata(
                    object_=chat, annotation=ChatParameters, direction="write"
                ),
                "save_history": save_history,
                "intelligent_query_rewriting": intelligent_query_rewriting,
                "stream_response": False,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChatFullResponse,
                    parse_obj_as(
                        type_=ChatFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def get_turn(
        self,
        chat_id: str,
        turn_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Turn]:
        """
        Get a specific turn from a chat, which is a message and response pair from the conversation.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        turn_id : str
            The ID of the turn.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        HttpResponse[Turn]
            The turn.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns/{jsonable_encoder(turn_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Turn,
                    parse_obj_as(
                        type_=Turn,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def delete_turn(
        self,
        chat_id: str,
        turn_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[None]:
        """
        Delete a turn from a chat. This will delete all subsequent turns in the chat.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        turn_id : str
            The ID of the turn.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        HttpResponse[None]
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns/{jsonable_encoder(turn_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="DELETE",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return HttpResponse(response=_response, data=None)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def update_turn(
        self,
        chat_id: str,
        turn_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        enabled: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Turn]:
        """
        Update a turn; used to disable or enable a chat.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        turn_id : str
            The ID of the turn.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        enabled : typing.Optional[bool]
            Indicates whether to disable a turn. It will disable this turn and all subsequent turns.
            Enabling a turn is not implemented.

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

        Returns
        -------
        HttpResponse[Turn]
            Successfully modified the turn.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns/{jsonable_encoder(turn_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="PATCH",
            json={
                "enabled": enabled,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Turn,
                    parse_obj_as(
                        type_=Turn,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

    async def list(
        self,
        *,
        limit: typing.Optional[int] = None,
        page_key: typing.Optional[str] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AsyncPager[Chat]]:
        """
        Retrieve a list of previous chats in the Vectara account.

        Parameters
        ----------
        limit : typing.Optional[int]
            The maximum number of results to return in the list.

        page_key : typing.Optional[str]
            Used to retrieve the next page of chats after the limit has been reached.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        AsyncHttpResponse[AsyncPager[Chat]]
            List of chats.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "limit": limit,
                "page_key": page_key,
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListChatsResponse,
                    parse_obj_as(
                        type_=ListChatsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                _has_next = False
                _get_next = None
                if _parsed_response.metadata is not None:
                    _parsed_next = _parsed_response.metadata.page_key
                    _has_next = _parsed_next is not None and _parsed_next != ""
                    _get_next = lambda: self.list(
                        limit=limit,
                        page_key=_parsed_next,
                        request_timeout=request_timeout,
                        request_timeout_millis=request_timeout_millis,
                        request_options=request_options,
                    )
                _items = _parsed_response.chats
                return AsyncHttpResponse(
                    response=_response, data=AsyncPager(has_next=_has_next, items=_items, get_next=_get_next)
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    @contextlib.asynccontextmanager
    async def create_stream(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[ChatStreamedResponse]]]:
        """
        Create a chat while specifying the default retrieval parameters used by the prompt.

        Parameters
        ----------
        query : str
            The chat message or question.

        search : SearchCorporaParameters

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the chat in both the chat and query history. This overrides `chat.store`.

        intelligent_query_rewriting : typing.Optional[bool]
            Indicates whether to enable intelligent query rewriting. When enabled, the platform will attempt to
            extract metadata filter and rewrite the query to improve search results.

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

        Yields
        ------
        typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[ChatStreamedResponse]]]

        """
        async with self._client_wrapper.httpx_client.stream(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "chat": convert_and_respect_annotation_metadata(
                    object_=chat, annotation=ChatParameters, direction="write"
                ),
                "save_history": save_history,
                "intelligent_query_rewriting": intelligent_query_rewriting,
                "stream_response": True,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            async def stream() -> AsyncHttpResponse[typing.AsyncIterator[ChatStreamedResponse]]:
                try:
                    if 200 <= _response.status_code < 300:

                        async def _iter():
                            _event_source = httpx_sse.EventSource(_response)
                            async for _sse in _event_source.aiter_sse():
                                if _sse.data == None:
                                    return
                                try:
                                    yield _sse.data()
                                except Exception:
                                    pass
                            return

                        return AsyncHttpResponse(response=_response, data=_iter())
                    await _response.aread()
                    if _response.status_code == 400:
                        raise BadRequestError(
                            typing.cast(
                                BadRequestErrorBody,
                                parse_obj_as(
                                    type_=BadRequestErrorBody,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    if _response.status_code == 403:
                        raise ForbiddenError(
                            typing.cast(
                                Error,
                                parse_obj_as(
                                    type_=Error,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    if _response.status_code == 404:
                        raise NotFoundError(
                            typing.cast(
                                NotFoundErrorBody,
                                parse_obj_as(
                                    type_=NotFoundErrorBody,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(status_code=_response.status_code, body=_response.text)
                raise ApiError(status_code=_response.status_code, body=_response_json)

            yield await stream()

    async def create(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ChatFullResponse]:
        """
        Create a chat while specifying the default retrieval parameters used by the prompt.

        Parameters
        ----------
        query : str
            The chat message or question.

        search : SearchCorporaParameters

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the chat in both the chat and query history. This overrides `chat.store`.

        intelligent_query_rewriting : typing.Optional[bool]
            Indicates whether to enable intelligent query rewriting. When enabled, the platform will attempt to
            extract metadata filter and rewrite the query to improve search results.

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

        Returns
        -------
        AsyncHttpResponse[ChatFullResponse]

        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "chat": convert_and_respect_annotation_metadata(
                    object_=chat, annotation=ChatParameters, direction="write"
                ),
                "save_history": save_history,
                "intelligent_query_rewriting": intelligent_query_rewriting,
                "stream_response": False,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChatFullResponse,
                    parse_obj_as(
                        type_=ChatFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get(
        self,
        chat_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Chat]:
        """
        Get a chat summary to view what started the chat, but not subsequent turns.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        AsyncHttpResponse[Chat]
            A chat.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Chat,
                    parse_obj_as(
                        type_=Chat,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def delete(
        self,
        chat_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[None]:
        """
        Delete a chat and any turns it contains permanently.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="DELETE",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def list_turns(
        self,
        chat_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ListChatTurnsResponse]:
        """
        List all turns in a chat to see all message and response pairs that make up the dialog.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        AsyncHttpResponse[ListChatTurnsResponse]
            List of turns.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ListChatTurnsResponse,
                    parse_obj_as(
                        type_=ListChatTurnsResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    @contextlib.asynccontextmanager
    async def create_turns_stream(
        self,
        chat_id: str,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[ChatStreamedResponse]]]:
        """
        Create a new turn in the chat. Each conversation has a series of `turn` objects, which are the sequence of message and response pairs that make up the dialog.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        query : str
            The chat message or question.

        search : SearchCorporaParameters

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the chat in both the chat and query history. This overrides `chat.store`.

        intelligent_query_rewriting : typing.Optional[bool]
            Indicates whether to enable intelligent query rewriting. When enabled, the platform will attempt to
            extract metadata filter and rewrite the query to improve search results.

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

        Yields
        ------
        typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[ChatStreamedResponse]]]

        """
        async with self._client_wrapper.httpx_client.stream(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "chat": convert_and_respect_annotation_metadata(
                    object_=chat, annotation=ChatParameters, direction="write"
                ),
                "save_history": save_history,
                "intelligent_query_rewriting": intelligent_query_rewriting,
                "stream_response": True,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:

            async def stream() -> AsyncHttpResponse[typing.AsyncIterator[ChatStreamedResponse]]:
                try:
                    if 200 <= _response.status_code < 300:

                        async def _iter():
                            _event_source = httpx_sse.EventSource(_response)
                            async for _sse in _event_source.aiter_sse():
                                if _sse.data == None:
                                    return
                                try:
                                    yield _sse.data()
                                except Exception:
                                    pass
                            return

                        return AsyncHttpResponse(response=_response, data=_iter())
                    await _response.aread()
                    if _response.status_code == 400:
                        raise BadRequestError(
                            typing.cast(
                                BadRequestErrorBody,
                                parse_obj_as(
                                    type_=BadRequestErrorBody,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    if _response.status_code == 403:
                        raise ForbiddenError(
                            typing.cast(
                                Error,
                                parse_obj_as(
                                    type_=Error,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    if _response.status_code == 404:
                        raise NotFoundError(
                            typing.cast(
                                NotFoundErrorBody,
                                parse_obj_as(
                                    type_=NotFoundErrorBody,  # type: ignore
                                    object_=_response.json(),
                                ),
                            )
                        )
                    _response_json = _response.json()
                except JSONDecodeError:
                    raise ApiError(status_code=_response.status_code, body=_response.text)
                raise ApiError(status_code=_response.status_code, body=_response_json)

            yield await stream()

    async def create_turns(
        self,
        chat_id: str,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ChatFullResponse]:
        """
        Create a new turn in the chat. Each conversation has a series of `turn` objects, which are the sequence of message and response pairs that make up the dialog.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        query : str
            The chat message or question.

        search : SearchCorporaParameters

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the chat in both the chat and query history. This overrides `chat.store`.

        intelligent_query_rewriting : typing.Optional[bool]
            Indicates whether to enable intelligent query rewriting. When enabled, the platform will attempt to
            extract metadata filter and rewrite the query to improve search results.

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

        Returns
        -------
        AsyncHttpResponse[ChatFullResponse]

        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "chat": convert_and_respect_annotation_metadata(
                    object_=chat, annotation=ChatParameters, direction="write"
                ),
                "save_history": save_history,
                "intelligent_query_rewriting": intelligent_query_rewriting,
                "stream_response": False,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ChatFullResponse,
                    parse_obj_as(
                        type_=ChatFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get_turn(
        self,
        chat_id: str,
        turn_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Turn]:
        """
        Get a specific turn from a chat, which is a message and response pair from the conversation.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        turn_id : str
            The ID of the turn.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        AsyncHttpResponse[Turn]
            The turn.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns/{jsonable_encoder(turn_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Turn,
                    parse_obj_as(
                        type_=Turn,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def delete_turn(
        self,
        chat_id: str,
        turn_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[None]:
        """
        Delete a turn from a chat. This will delete all subsequent turns in the chat.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        turn_id : str
            The ID of the turn.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

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

        Returns
        -------
        AsyncHttpResponse[None]
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns/{jsonable_encoder(turn_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="DELETE",
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return AsyncHttpResponse(response=_response, data=None)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def update_turn(
        self,
        chat_id: str,
        turn_id: str,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        enabled: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Turn]:
        """
        Update a turn; used to disable or enable a chat.

        Parameters
        ----------
        chat_id : str
            The ID of the chat.

        turn_id : str
            The ID of the turn.

        request_timeout : typing.Optional[int]
            The API will make a best effort to complete the request in the specified seconds or time out.

        request_timeout_millis : typing.Optional[int]
            The API will make a best effort to complete the request in the specified milliseconds or time out.

        enabled : typing.Optional[bool]
            Indicates whether to disable a turn. It will disable this turn and all subsequent turns.
            Enabling a turn is not implemented.

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

        Returns
        -------
        AsyncHttpResponse[Turn]
            Successfully modified the turn.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}/turns/{jsonable_encoder(turn_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="PATCH",
            json={
                "enabled": enabled,
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Turn,
                    parse_obj_as(
                        type_=Turn,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
