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

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

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


class ChatsClient:
    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_options: typing.Optional[RequestOptions] = None,
    ) -> 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 the retrieve the next page of chats after the limit has been reached.

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

        Returns
        -------
        SyncPager[Chat]
            List of chats.

        Examples
        --------
        from vectara import Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        response = client.chats.list()
        for item in response:
            yield item
        # alternatively, you can paginate page-by-page
        for page in response.iter_pages():
            yield page
        """
        _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,
            },
            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_options=request_options,
                    )
                _items = _parsed_response.chats
                return 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)

    def create_stream(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

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

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


        Examples
        --------
        from vectara import (
            ChatParameters,
            CitationParameters,
            ContextConfiguration,
            CustomerSpecificReranker,
            GenerationParameters,
            KeyedSearchCorpus,
            ModelParameters,
            SearchCorporaParameters,
            Vectara,
        )

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        response = client.chats.create_stream(
            query="string",
            search=SearchCorporaParameters(
                corpora=[
                    KeyedSearchCorpus(
                        corpus_key={"key": "value"},
                        custom_dimensions={"key": "value"},
                        metadata_filter={"key": "value"},
                        lexical_interpolation={"key": "value"},
                        semantics={"key": "value"},
                    )
                ],
                offset=1,
                limit=1,
                context_configuration=ContextConfiguration(
                    characters_before=1,
                    characters_after=1,
                    sentences_before=1,
                    sentences_after=1,
                    start_tag="string",
                    end_tag="string",
                ),
                reranker=CustomerSpecificReranker(
                    reranker_id="string",
                ),
            ),
            generation=GenerationParameters(
                prompt_name="string",
                max_used_search_results=1,
                prompt_text="string",
                max_response_characters=1,
                response_language="auto",
                model_parameters=ModelParameters(
                    max_tokens=1,
                    temperature=1.1,
                    frequency_penalty=1.1,
                    presence_penalty=1.1,
                ),
                citations=CitationParameters(
                    style="none",
                    url_pattern="string",
                    text_pattern="string",
                ),
                enable_factual_consistency_score=True,
            ),
            chat=ChatParameters(
                store=True,
            ),
        )
        for chunk in response:
            yield chunk
        """
        with self._client_wrapper.httpx_client.stream(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": search,
                "generation": generation,
                "chat": chat,
                "stream_response": True,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _event_source = httpx_sse.EventSource(_response)
                    for _sse in _event_source.iter_sse():
                        try:
                            yield typing.cast(
                                ChatStreamedResponse,
                                parse_obj_as(
                                    type_=ChatStreamedResponse,  # type: ignore
                                    object_=json.loads(_sse.data),
                                ),
                            )
                        except:
                            pass
                    return
                _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)

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

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

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

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

        Returns
        -------
        ChatFullResponse


        Examples
        --------
        from vectara import SearchCorporaParameters, Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.chats.create(
            query="How can I use the Vectara platform?",
            search=SearchCorporaParameters(),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": search,
                "generation": generation,
                "chat": chat,
                "stream_response": False,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ChatFullResponse,
                    parse_obj_as(
                        type_=ChatFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            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_options: typing.Optional[RequestOptions] = None) -> 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_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Chat
            A chat.

        Examples
        --------
        from vectara import Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.chats.get(
            chat_id="chat_id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Chat,
                    parse_obj_as(
                        type_=Chat,  # 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 delete(self, chat_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None:
        """
        Delete a chat and any turns it contains permanently.

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

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

        Returns
        -------
        None

        Examples
        --------
        from vectara import Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.chats.delete(
            chat_id="chat_id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/chats/{jsonable_encoder(chat_id)}",
            base_url=self._client_wrapper.get_environment().default,
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            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_options: typing.Optional[RequestOptions] = None
    ) -> 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_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        ListChatTurnsResponse
            List of turns.

        Examples
        --------
        from vectara import Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.chats.list_turns(
            chat_id="chat_id",
        )
        """
        _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",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ListChatTurnsResponse,
                    parse_obj_as(
                        type_=ListChatTurnsResponse,  # 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 create_turn_stream(
        self,
        chat_id: str,
        *,
        query: str,
        search: SearchCorporaParameters,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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 tha make up the dialog.

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

        query : str
            The chat message or question.

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

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

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


        Examples
        --------
        from vectara import (
            ChatParameters,
            CitationParameters,
            ContextConfiguration,
            CustomerSpecificReranker,
            GenerationParameters,
            KeyedSearchCorpus,
            ModelParameters,
            SearchCorporaParameters,
            Vectara,
        )

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        response = client.chats.create_turn_stream(
            chat_id="string",
            query="string",
            search=SearchCorporaParameters(
                corpora=[
                    KeyedSearchCorpus(
                        corpus_key={"key": "value"},
                        custom_dimensions={"key": "value"},
                        metadata_filter={"key": "value"},
                        lexical_interpolation={"key": "value"},
                        semantics={"key": "value"},
                    )
                ],
                offset=1,
                limit=1,
                context_configuration=ContextConfiguration(
                    characters_before=1,
                    characters_after=1,
                    sentences_before=1,
                    sentences_after=1,
                    start_tag="string",
                    end_tag="string",
                ),
                reranker=CustomerSpecificReranker(
                    reranker_id="string",
                ),
            ),
            generation=GenerationParameters(
                prompt_name="string",
                max_used_search_results=1,
                prompt_text="string",
                max_response_characters=1,
                response_language="auto",
                model_parameters=ModelParameters(
                    max_tokens=1,
                    temperature=1.1,
                    frequency_penalty=1.1,
                    presence_penalty=1.1,
                ),
                citations=CitationParameters(
                    style="none",
                    url_pattern="string",
                    text_pattern="string",
                ),
                enable_factual_consistency_score=True,
            ),
            chat=ChatParameters(
                store=True,
            ),
        )
        for chunk in response:
            yield chunk
        """
        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": search,
                "generation": generation,
                "chat": chat,
                "stream_response": True,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _event_source = httpx_sse.EventSource(_response)
                    for _sse in _event_source.iter_sse():
                        try:
                            yield typing.cast(
                                ChatStreamedResponse,
                                parse_obj_as(
                                    type_=ChatStreamedResponse,  # type: ignore
                                    object_=json.loads(_sse.data),
                                ),
                            )
                        except:
                            pass
                    return
                _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)

    def create_turn(
        self,
        chat_id: str,
        *,
        query: str,
        search: SearchCorporaParameters,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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 tha make up the dialog.

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

        query : str
            The chat message or question.

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

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

        Returns
        -------
        ChatFullResponse


        Examples
        --------
        from vectara import SearchCorporaParameters, Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.chats.create_turn(
            chat_id="chat_id",
            query="How can I use the Vectara platform?",
            search=SearchCorporaParameters(),
        )
        """
        _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": search,
                "generation": generation,
                "chat": chat,
                "stream_response": False,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ChatFullResponse,
                    parse_obj_as(
                        type_=ChatFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            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_options: typing.Optional[RequestOptions] = None) -> 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_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Turn
            The turn.

        Examples
        --------
        from vectara import Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.chats.get_turn(
            chat_id="chat_id",
            turn_id="turn_id",
        )
        """
        _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",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Turn,
                    parse_obj_as(
                        type_=Turn,  # 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 delete_turn(
        self, chat_id: str, turn_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> 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_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        None

        Examples
        --------
        from vectara import Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.chats.delete_turn(
            chat_id="chat_id",
            turn_id="turn_id",
        )
        """
        _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",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            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,
        *,
        enabled: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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.

        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
        -------
        Turn
            Successfully modified the turn.

        Examples
        --------
        from vectara import Vectara

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.chats.update_turn(
            chat_id="chat_id",
            turn_id="turn_id",
        )
        """
        _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,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Turn,
                    parse_obj_as(
                        type_=Turn,  # 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)


class AsyncChatsClient:
    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_options: typing.Optional[RequestOptions] = None,
    ) -> 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 the retrieve the next page of chats after the limit has been reached.

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

        Returns
        -------
        AsyncPager[Chat]
            List of chats.

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            response = await client.chats.list()
            async for item in response:
                yield item
            # alternatively, you can paginate page-by-page
            async for page in response.iter_pages():
                yield page


        asyncio.run(main())
        """
        _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,
            },
            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_options=request_options,
                    )
                _items = _parsed_response.chats
                return 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)

    async def create_stream(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

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

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


        Examples
        --------
        import asyncio

        from vectara import (
            AsyncVectara,
            ChatParameters,
            CitationParameters,
            ContextConfiguration,
            CustomerSpecificReranker,
            GenerationParameters,
            KeyedSearchCorpus,
            ModelParameters,
            SearchCorporaParameters,
        )

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            response = await client.chats.create_stream(
                query="string",
                search=SearchCorporaParameters(
                    corpora=[
                        KeyedSearchCorpus(
                            corpus_key={"key": "value"},
                            custom_dimensions={"key": "value"},
                            metadata_filter={"key": "value"},
                            lexical_interpolation={"key": "value"},
                            semantics={"key": "value"},
                        )
                    ],
                    offset=1,
                    limit=1,
                    context_configuration=ContextConfiguration(
                        characters_before=1,
                        characters_after=1,
                        sentences_before=1,
                        sentences_after=1,
                        start_tag="string",
                        end_tag="string",
                    ),
                    reranker=CustomerSpecificReranker(
                        reranker_id="string",
                    ),
                ),
                generation=GenerationParameters(
                    prompt_name="string",
                    max_used_search_results=1,
                    prompt_text="string",
                    max_response_characters=1,
                    response_language="auto",
                    model_parameters=ModelParameters(
                        max_tokens=1,
                        temperature=1.1,
                        frequency_penalty=1.1,
                        presence_penalty=1.1,
                    ),
                    citations=CitationParameters(
                        style="none",
                        url_pattern="string",
                        text_pattern="string",
                    ),
                    enable_factual_consistency_score=True,
                ),
                chat=ChatParameters(
                    store=True,
                ),
            )
            async for chunk in response:
                yield chunk


        asyncio.run(main())
        """
        async with self._client_wrapper.httpx_client.stream(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": search,
                "generation": generation,
                "chat": chat,
                "stream_response": True,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _event_source = httpx_sse.EventSource(_response)
                    async for _sse in _event_source.aiter_sse():
                        try:
                            yield typing.cast(
                                ChatStreamedResponse,
                                parse_obj_as(
                                    type_=ChatStreamedResponse,  # type: ignore
                                    object_=json.loads(_sse.data),
                                ),
                            )
                        except:
                            pass
                    return
                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)

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

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

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

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

        Returns
        -------
        ChatFullResponse


        Examples
        --------
        import asyncio

        from vectara import AsyncVectara, SearchCorporaParameters

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.chats.create(
                query="How can I use the Vectara platform?",
                search=SearchCorporaParameters(),
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/chats",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": search,
                "generation": generation,
                "chat": chat,
                "stream_response": False,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ChatFullResponse,
                    parse_obj_as(
                        type_=ChatFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            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_options: typing.Optional[RequestOptions] = None) -> 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_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Chat
            A chat.

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.chats.get(
                chat_id="chat_id",
            )


        asyncio.run(main())
        """
        _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",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Chat,
                    parse_obj_as(
                        type_=Chat,  # 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 delete(self, chat_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> None:
        """
        Delete a chat and any turns it contains permanently.

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

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

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.chats.delete(
                chat_id="chat_id",
            )


        asyncio.run(main())
        """
        _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",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            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_options: typing.Optional[RequestOptions] = None
    ) -> 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_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        ListChatTurnsResponse
            List of turns.

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.chats.list_turns(
                chat_id="chat_id",
            )


        asyncio.run(main())
        """
        _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",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ListChatTurnsResponse,
                    parse_obj_as(
                        type_=ListChatTurnsResponse,  # 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 create_turn_stream(
        self,
        chat_id: str,
        *,
        query: str,
        search: SearchCorporaParameters,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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 tha make up the dialog.

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

        query : str
            The chat message or question.

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

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

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


        Examples
        --------
        import asyncio

        from vectara import (
            AsyncVectara,
            ChatParameters,
            CitationParameters,
            ContextConfiguration,
            CustomerSpecificReranker,
            GenerationParameters,
            KeyedSearchCorpus,
            ModelParameters,
            SearchCorporaParameters,
        )

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            response = await client.chats.create_turn_stream(
                chat_id="string",
                query="string",
                search=SearchCorporaParameters(
                    corpora=[
                        KeyedSearchCorpus(
                            corpus_key={"key": "value"},
                            custom_dimensions={"key": "value"},
                            metadata_filter={"key": "value"},
                            lexical_interpolation={"key": "value"},
                            semantics={"key": "value"},
                        )
                    ],
                    offset=1,
                    limit=1,
                    context_configuration=ContextConfiguration(
                        characters_before=1,
                        characters_after=1,
                        sentences_before=1,
                        sentences_after=1,
                        start_tag="string",
                        end_tag="string",
                    ),
                    reranker=CustomerSpecificReranker(
                        reranker_id="string",
                    ),
                ),
                generation=GenerationParameters(
                    prompt_name="string",
                    max_used_search_results=1,
                    prompt_text="string",
                    max_response_characters=1,
                    response_language="auto",
                    model_parameters=ModelParameters(
                        max_tokens=1,
                        temperature=1.1,
                        frequency_penalty=1.1,
                        presence_penalty=1.1,
                    ),
                    citations=CitationParameters(
                        style="none",
                        url_pattern="string",
                        text_pattern="string",
                    ),
                    enable_factual_consistency_score=True,
                ),
                chat=ChatParameters(
                    store=True,
                ),
            )
            async for chunk in response:
                yield chunk


        asyncio.run(main())
        """
        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": search,
                "generation": generation,
                "chat": chat,
                "stream_response": True,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _event_source = httpx_sse.EventSource(_response)
                    async for _sse in _event_source.aiter_sse():
                        try:
                            yield typing.cast(
                                ChatStreamedResponse,
                                parse_obj_as(
                                    type_=ChatStreamedResponse,  # type: ignore
                                    object_=json.loads(_sse.data),
                                ),
                            )
                        except:
                            pass
                    return
                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)

    async def create_turn(
        self,
        chat_id: str,
        *,
        query: str,
        search: SearchCorporaParameters,
        generation: typing.Optional[GenerationParameters] = OMIT,
        chat: typing.Optional[ChatParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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 tha make up the dialog.

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

        query : str
            The chat message or question.

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

        chat : typing.Optional[ChatParameters]

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

        Returns
        -------
        ChatFullResponse


        Examples
        --------
        import asyncio

        from vectara import AsyncVectara, SearchCorporaParameters

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.chats.create_turn(
                chat_id="chat_id",
                query="How can I use the Vectara platform?",
                search=SearchCorporaParameters(),
            )


        asyncio.run(main())
        """
        _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": search,
                "generation": generation,
                "chat": chat,
                "stream_response": False,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    ChatFullResponse,
                    parse_obj_as(
                        type_=ChatFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            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_options: typing.Optional[RequestOptions] = None
    ) -> 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_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        Turn
            The turn.

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.chats.get_turn(
                chat_id="chat_id",
                turn_id="turn_id",
            )


        asyncio.run(main())
        """
        _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",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Turn,
                    parse_obj_as(
                        type_=Turn,  # 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 delete_turn(
        self, chat_id: str, turn_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> 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_options : typing.Optional[RequestOptions]
            Request-specific configuration.

        Returns
        -------
        None

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.chats.delete_turn(
                chat_id="chat_id",
                turn_id="turn_id",
            )


        asyncio.run(main())
        """
        _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",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return
            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,
        *,
        enabled: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> 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.

        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
        -------
        Turn
            Successfully modified the turn.

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

        client = AsyncVectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )


        async def main() -> None:
            await client.chats.update_turn(
                chat_id="chat_id",
                turn_id="turn_id",
            )


        asyncio.run(main())
        """
        _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,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Turn,
                    parse_obj_as(
                        type_=Turn,  # 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)
