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

import typing
from .environment import VectaraEnvironment
import os
import httpx
from .core.api_error import ApiError
from .core.oauth_token_provider import OAuthTokenProvider
from .core.client_wrapper import SyncClientWrapper
from .corpora.client import CorporaClient
from .upload.client import UploadClient
from .documents.client import DocumentsClient
from .chats.client import ChatsClient
from .llms.client import LlmsClient
from .generation_presets.client import GenerationPresetsClient
from .encoders.client import EncodersClient
from .rerankers.client import RerankersClient
from .jobs.client import JobsClient
from .users.client import UsersClient
from .api_keys.client import ApiKeysClient
from .app_clients.client import AppClientsClient
from .auth.client import AuthClient
from .types.search_corpora_parameters import SearchCorporaParameters
from .types.generation_parameters import GenerationParameters
from .core.request_options import RequestOptions
from .types.query_streamed_response import QueryStreamedResponse
from .core.serialization import convert_and_respect_annotation_metadata
from .core.pydantic_utilities import parse_obj_as
import json
from .errors.bad_request_error import BadRequestError
from .types.bad_request_error_body import BadRequestErrorBody
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 .types.query_full_response import QueryFullResponse
from .types.chat_parameters import ChatParameters
from .types.chat_streamed_response import ChatStreamedResponse
from .types.chat_full_response import ChatFullResponse
from .core.client_wrapper import AsyncClientWrapper
from .corpora.client import AsyncCorporaClient
from .upload.client import AsyncUploadClient
from .documents.client import AsyncDocumentsClient
from .chats.client import AsyncChatsClient
from .llms.client import AsyncLlmsClient
from .generation_presets.client import AsyncGenerationPresetsClient
from .encoders.client import AsyncEncodersClient
from .rerankers.client import AsyncRerankersClient
from .jobs.client import AsyncJobsClient
from .users.client import AsyncUsersClient
from .api_keys.client import AsyncApiKeysClient
from .app_clients.client import AsyncAppClientsClient
from .auth.client import AsyncAuthClient

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


class BaseVectara:
    """
    Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.

    Parameters
    ----------
    environment : VectaraEnvironment
        The environment to use for requests from the client. from .environment import VectaraEnvironment



        Defaults to VectaraEnvironment.PRODUCTION



    api_key : typing.Optional[str]
    client_id : typing.Optional[str]
    client_secret : typing.Optional[str]
    _token_getter_override : typing.Optional[typing.Callable[[], str]]
    timeout : typing.Optional[float]
        The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced.

    follow_redirects : typing.Optional[bool]
        Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.

    httpx_client : typing.Optional[httpx.Client]
        The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.

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

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

    def __init__(
        self,
        *,
        environment: VectaraEnvironment = VectaraEnvironment.PRODUCTION,
        api_key: typing.Optional[str] = os.getenv("VECTARA_API_KEY"),
        client_id: typing.Optional[str] = os.getenv("VECTARA_CLIENT_ID"),
        client_secret: typing.Optional[str] = os.getenv("VECTARA_CLIENT_SECRET"),
        _token_getter_override: typing.Optional[typing.Callable[[], str]] = None,
        timeout: typing.Optional[float] = None,
        follow_redirects: typing.Optional[bool] = True,
        httpx_client: typing.Optional[httpx.Client] = None,
    ):
        _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
        if api_key is not None:
            self._client_wrapper = SyncClientWrapper(
                environment=environment,
                api_key=api_key,
                httpx_client=httpx_client
                if httpx_client is not None
                else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
                if follow_redirects is not None
                else httpx.Client(timeout=_defaulted_timeout),
                timeout=_defaulted_timeout,
            )            
        elif client_id is not None and client_secret is not None: 
            oauth_token_provider = OAuthTokenProvider(
                client_id=client_id,
                client_secret=client_secret,
                client_wrapper=SyncClientWrapper(
                    environment=environment,
                    api_key=api_key,
                    httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
                    if follow_redirects is not None
                    else httpx.Client(timeout=_defaulted_timeout),
                    timeout=_defaulted_timeout,
                ),
            )
            self._client_wrapper = SyncClientWrapper(
                environment=environment,
                api_key=api_key,
                token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token,
                httpx_client=httpx_client
                if httpx_client is not None
                else httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
                if follow_redirects is not None
                else httpx.Client(timeout=_defaulted_timeout),
                timeout=_defaulted_timeout,
            )
        else: 
            raise ApiError(
                body="The client must be instantiated be either passing in api_key, client_id or client_secret"
            )  
        self.corpora = CorporaClient(client_wrapper=self._client_wrapper)
        self.upload = UploadClient(client_wrapper=self._client_wrapper)
        self.documents = DocumentsClient(client_wrapper=self._client_wrapper)
        self.chats = ChatsClient(client_wrapper=self._client_wrapper)
        self.llms = LlmsClient(client_wrapper=self._client_wrapper)
        self.generation_presets = GenerationPresetsClient(client_wrapper=self._client_wrapper)
        self.encoders = EncodersClient(client_wrapper=self._client_wrapper)
        self.rerankers = RerankersClient(client_wrapper=self._client_wrapper)
        self.jobs = JobsClient(client_wrapper=self._client_wrapper)
        self.users = UsersClient(client_wrapper=self._client_wrapper)
        self.api_keys = ApiKeysClient(client_wrapper=self._client_wrapper)
        self.app_clients = AppClientsClient(client_wrapper=self._client_wrapper)
        self.auth = AuthClient(client_wrapper=self._client_wrapper)

    def query_stream(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[QueryStreamedResponse]:
        """
        Perform a multi-purpose query to retrieve relevant information from one or more corpora and generate a response using Retrieval Augmented Generation (RAG).

        - Customize your search by specifying the query text (`query`), pagination details (`offset` and `limit`), and metadata filters (`metadata_filter`) to tailor your search results. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#query-definition)
        - Leverage advanced search capabilities like reranking (`reranker`) and opt-in Retrieval Augmented Generation (RAG) (`generation`) for enhanced query performance. Generation is opt in by setting the `generation` property. By excluding the property or by setting it to null, the response
          will not include generation. [Learn more](https://docs.vectara.com/docs/learn/grounded-generation/configure-query-summarization)
        - Specify a RAG-specific LLM like Mockingbird (`mockingbird-1.0-2024-07-16`) for the `generation_preset_name`. [Learn more](https://docs.vectara.com/docs/learn/mockingbird-llm)
        - Use advanced summarization options that utilize detailed summarization parameters such as `max_response_characters`, `temperature`, and `frequency_penalty` for generating precise and relevant summaries. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#advanced-summarization-customization-options)
        - Customize citation formats in summaries using the `citations` object to include numeric, HTML, or Markdown links. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#citation-format-in-summary)

        For more detailed information, see this [Query API guide](https://docs.vectara.com/docs/api-reference/search-apis/search).

        Parameters
        ----------
        query : str
            The search query string, which is the question the user is asking.

        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]

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

        Yields
        ------
        typing.Iterator[QueryStreamedResponse]


        Examples
        --------
        from vectara import (
            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.query_stream(
            request_timeout=1,
            request_timeout_millis=1,
            query="string",
            search=SearchCorporaParameters(
                corpora=[
                    KeyedSearchCorpus(
                        custom_dimensions={"string": 1.1},
                        metadata_filter="string",
                        lexical_interpolation=1.1,
                        semantics="default",
                    )
                ],
                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",
                    reranker_name="string",
                ),
            ),
            generation=GenerationParameters(
                generation_preset_name="string",
                prompt_name="string",
                max_used_search_results=1,
                prompt_template="string",
                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,
            ),
        )
        for chunk in response:
            yield chunk
        """
        with self._client_wrapper.httpx_client.stream(
            "v2/query",
            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"
                ),
                "stream_response": True,
            },
            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,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    for _text in _response.iter_lines():
                        try:
                            if len(_text) == 0:
                                continue
                            yield typing.cast(
                                QueryStreamedResponse,
                                parse_obj_as(
                                    type_=QueryStreamedResponse,  # type: ignore
                                    object_=json.loads(_text),
                                ),
                            )
                        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 query(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryFullResponse:
        """
        Perform a multi-purpose query to retrieve relevant information from one or more corpora and generate a response using Retrieval Augmented Generation (RAG).

        - Customize your search by specifying the query text (`query`), pagination details (`offset` and `limit`), and metadata filters (`metadata_filter`) to tailor your search results. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#query-definition)
        - Leverage advanced search capabilities like reranking (`reranker`) and opt-in Retrieval Augmented Generation (RAG) (`generation`) for enhanced query performance. Generation is opt in by setting the `generation` property. By excluding the property or by setting it to null, the response
          will not include generation. [Learn more](https://docs.vectara.com/docs/learn/grounded-generation/configure-query-summarization)
        - Specify a RAG-specific LLM like Mockingbird (`mockingbird-1.0-2024-07-16`) for the `generation_preset_name`. [Learn more](https://docs.vectara.com/docs/learn/mockingbird-llm)
        - Use advanced summarization options that utilize detailed summarization parameters such as `max_response_characters`, `temperature`, and `frequency_penalty` for generating precise and relevant summaries. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#advanced-summarization-customization-options)
        - Customize citation formats in summaries using the `citations` object to include numeric, HTML, or Markdown links. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#citation-format-in-summary)

        For more detailed information, see this [Query API guide](https://docs.vectara.com/docs/api-reference/search-apis/search).

        Parameters
        ----------
        query : str
            The search query string, which is the question the user is asking.

        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]

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

        Returns
        -------
        QueryFullResponse


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

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.query(
            query="Am I allowed to bring pets to work?",
            search=SearchCorporaParameters(),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/query",
            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"
                ),
                "stream_response": False,
            },
            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,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryFullResponse,
                    parse_obj_as(
                        type_=QueryFullResponse,  # 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 chat_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,
        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

        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]

        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.chat_stream(
            request_timeout=1,
            request_timeout_millis=1,
            query="string",
            search=SearchCorporaParameters(
                corpora=[
                    KeyedSearchCorpus(
                        custom_dimensions={"string": 1.1},
                        metadata_filter="string",
                        lexical_interpolation=1.1,
                        semantics="default",
                    )
                ],
                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",
                    reranker_name="string",
                ),
            ),
            generation=GenerationParameters(
                generation_preset_name="string",
                prompt_name="string",
                max_used_search_results=1,
                prompt_template="string",
                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": 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"
                ),
                "stream_response": True,
            },
            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,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    for _text in _response.iter_lines():
                        try:
                            if len(_text) == 0:
                                continue
                            yield typing.cast(
                                ChatStreamedResponse,
                                parse_obj_as(
                                    type_=ChatStreamedResponse,  # type: ignore
                                    object_=json.loads(_text),
                                ),
                            )
                        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 chat(
        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,
        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

        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]

        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.chat(
            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": 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"
                ),
                "stream_response": False,
            },
            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,
            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)


class AsyncBaseVectara:
    """
    Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.

    Parameters
    ----------
    environment : VectaraEnvironment
        The environment to use for requests from the client. from .environment import VectaraEnvironment



        Defaults to VectaraEnvironment.PRODUCTION



    api_key : typing.Optional[str]
    client_id : typing.Optional[str]
    client_secret : typing.Optional[str]
    _token_getter_override : typing.Optional[typing.Callable[[], str]]
    timeout : typing.Optional[float]
        The timeout to be used, in seconds, for requests. By default the timeout is 60 seconds, unless a custom httpx client is used, in which case this default is not enforced.

    follow_redirects : typing.Optional[bool]
        Whether the default httpx client follows redirects or not, this is irrelevant if a custom httpx client is passed in.

    httpx_client : typing.Optional[httpx.AsyncClient]
        The httpx client to use for making requests, a preconfigured client is used by default, however this is useful should you want to pass in any custom httpx configuration.

    Examples
    --------
    from vectara import AsyncVectara

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

    def __init__(
        self,
        *,
        environment: VectaraEnvironment = VectaraEnvironment.PRODUCTION,
        api_key: typing.Optional[str] = os.getenv("VECTARA_API_KEY"),
        client_id: typing.Optional[str] = os.getenv("VECTARA_CLIENT_ID"),
        client_secret: typing.Optional[str] = os.getenv("VECTARA_CLIENT_SECRET"),
        _token_getter_override: typing.Optional[typing.Callable[[], str]] = None,
        timeout: typing.Optional[float] = None,
        follow_redirects: typing.Optional[bool] = True,
        httpx_client: typing.Optional[httpx.AsyncClient] = None,
    ):
        _defaulted_timeout = timeout if timeout is not None else 60 if httpx_client is None else None
        if api_key is not None:
            self._client_wrapper = AsyncClientWrapper(
                environment=environment,
                api_key=api_key,
                httpx_client=httpx_client
                if httpx_client is not None
                else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
                if follow_redirects is not None
                else httpx.AsyncClient(timeout=_defaulted_timeout),
                timeout=_defaulted_timeout,
            )            
        elif client_id is not None and client_secret is not None: 
            oauth_token_provider = OAuthTokenProvider(
                client_id=client_id,
                client_secret=client_secret,
                client_wrapper=SyncClientWrapper(
                    environment=environment,
                    api_key=api_key,
                    httpx_client=httpx.Client(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
                    if follow_redirects is not None
                    else httpx.Client(timeout=_defaulted_timeout),
                    timeout=_defaulted_timeout,
                ),
            )
            self._client_wrapper = AsyncClientWrapper(
                environment=environment,
                api_key=api_key,
                token=_token_getter_override if _token_getter_override is not None else oauth_token_provider.get_token,
                httpx_client=httpx_client
                if httpx_client is not None
                else httpx.AsyncClient(timeout=_defaulted_timeout, follow_redirects=follow_redirects)
                if follow_redirects is not None
                else httpx.AsyncClient(timeout=_defaulted_timeout),
                timeout=_defaulted_timeout,
            )
        else: 
            raise ApiError(
                body="The client must be instantiated be either passing in api_key, client_id or client_secret"
            )  
        self.corpora = AsyncCorporaClient(client_wrapper=self._client_wrapper)
        self.upload = AsyncUploadClient(client_wrapper=self._client_wrapper)
        self.documents = AsyncDocumentsClient(client_wrapper=self._client_wrapper)
        self.chats = AsyncChatsClient(client_wrapper=self._client_wrapper)
        self.llms = AsyncLlmsClient(client_wrapper=self._client_wrapper)
        self.generation_presets = AsyncGenerationPresetsClient(client_wrapper=self._client_wrapper)
        self.encoders = AsyncEncodersClient(client_wrapper=self._client_wrapper)
        self.rerankers = AsyncRerankersClient(client_wrapper=self._client_wrapper)
        self.jobs = AsyncJobsClient(client_wrapper=self._client_wrapper)
        self.users = AsyncUsersClient(client_wrapper=self._client_wrapper)
        self.api_keys = AsyncApiKeysClient(client_wrapper=self._client_wrapper)
        self.app_clients = AsyncAppClientsClient(client_wrapper=self._client_wrapper)
        self.auth = AsyncAuthClient(client_wrapper=self._client_wrapper)

    async def query_stream(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[QueryStreamedResponse]:
        """
        Perform a multi-purpose query to retrieve relevant information from one or more corpora and generate a response using Retrieval Augmented Generation (RAG).

        - Customize your search by specifying the query text (`query`), pagination details (`offset` and `limit`), and metadata filters (`metadata_filter`) to tailor your search results. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#query-definition)
        - Leverage advanced search capabilities like reranking (`reranker`) and opt-in Retrieval Augmented Generation (RAG) (`generation`) for enhanced query performance. Generation is opt in by setting the `generation` property. By excluding the property or by setting it to null, the response
          will not include generation. [Learn more](https://docs.vectara.com/docs/learn/grounded-generation/configure-query-summarization)
        - Specify a RAG-specific LLM like Mockingbird (`mockingbird-1.0-2024-07-16`) for the `generation_preset_name`. [Learn more](https://docs.vectara.com/docs/learn/mockingbird-llm)
        - Use advanced summarization options that utilize detailed summarization parameters such as `max_response_characters`, `temperature`, and `frequency_penalty` for generating precise and relevant summaries. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#advanced-summarization-customization-options)
        - Customize citation formats in summaries using the `citations` object to include numeric, HTML, or Markdown links. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#citation-format-in-summary)

        For more detailed information, see this [Query API guide](https://docs.vectara.com/docs/api-reference/search-apis/search).

        Parameters
        ----------
        query : str
            The search query string, which is the question the user is asking.

        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]

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

        Yields
        ------
        typing.AsyncIterator[QueryStreamedResponse]


        Examples
        --------
        import asyncio

        from vectara import (
            AsyncVectara,
            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.query_stream(
                request_timeout=1,
                request_timeout_millis=1,
                query="string",
                search=SearchCorporaParameters(
                    corpora=[
                        KeyedSearchCorpus(
                            custom_dimensions={"string": 1.1},
                            metadata_filter="string",
                            lexical_interpolation=1.1,
                            semantics="default",
                        )
                    ],
                    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",
                        reranker_name="string",
                    ),
                ),
                generation=GenerationParameters(
                    generation_preset_name="string",
                    prompt_name="string",
                    max_used_search_results=1,
                    prompt_template="string",
                    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,
                ),
            )
            async for chunk in response:
                yield chunk


        asyncio.run(main())
        """
        async with self._client_wrapper.httpx_client.stream(
            "v2/query",
            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"
                ),
                "stream_response": True,
            },
            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,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    async for _text in _response.aiter_lines():
                        try:
                            if len(_text) == 0:
                                continue
                            yield typing.cast(
                                QueryStreamedResponse,
                                parse_obj_as(
                                    type_=QueryStreamedResponse,  # type: ignore
                                    object_=json.loads(_text),
                                ),
                            )
                        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 query(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryFullResponse:
        """
        Perform a multi-purpose query to retrieve relevant information from one or more corpora and generate a response using Retrieval Augmented Generation (RAG).

        - Customize your search by specifying the query text (`query`), pagination details (`offset` and `limit`), and metadata filters (`metadata_filter`) to tailor your search results. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#query-definition)
        - Leverage advanced search capabilities like reranking (`reranker`) and opt-in Retrieval Augmented Generation (RAG) (`generation`) for enhanced query performance. Generation is opt in by setting the `generation` property. By excluding the property or by setting it to null, the response
          will not include generation. [Learn more](https://docs.vectara.com/docs/learn/grounded-generation/configure-query-summarization)
        - Specify a RAG-specific LLM like Mockingbird (`mockingbird-1.0-2024-07-16`) for the `generation_preset_name`. [Learn more](https://docs.vectara.com/docs/learn/mockingbird-llm)
        - Use advanced summarization options that utilize detailed summarization parameters such as `max_response_characters`, `temperature`, and `frequency_penalty` for generating precise and relevant summaries. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#advanced-summarization-customization-options)
        - Customize citation formats in summaries using the `citations` object to include numeric, HTML, or Markdown links. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#citation-format-in-summary)

        For more detailed information, see this [Query API guide](https://docs.vectara.com/docs/api-reference/search-apis/search).

        Parameters
        ----------
        query : str
            The search query string, which is the question the user is asking.

        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]

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

        Returns
        -------
        QueryFullResponse


        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.query(
                query="Am I allowed to bring pets to work?",
                search=SearchCorporaParameters(),
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/query",
            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"
                ),
                "stream_response": False,
            },
            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,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryFullResponse,
                    parse_obj_as(
                        type_=QueryFullResponse,  # 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 chat_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,
        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

        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]

        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.chat_stream(
                request_timeout=1,
                request_timeout_millis=1,
                query="string",
                search=SearchCorporaParameters(
                    corpora=[
                        KeyedSearchCorpus(
                            custom_dimensions={"string": 1.1},
                            metadata_filter="string",
                            lexical_interpolation=1.1,
                            semantics="default",
                        )
                    ],
                    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",
                        reranker_name="string",
                    ),
                ),
                generation=GenerationParameters(
                    generation_preset_name="string",
                    prompt_name="string",
                    max_used_search_results=1,
                    prompt_template="string",
                    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": 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"
                ),
                "stream_response": True,
            },
            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,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    async for _text in _response.aiter_lines():
                        try:
                            if len(_text) == 0:
                                continue
                            yield typing.cast(
                                ChatStreamedResponse,
                                parse_obj_as(
                                    type_=ChatStreamedResponse,  # type: ignore
                                    object_=json.loads(_text),
                                ),
                            )
                        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 chat(
        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,
        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

        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]

        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.chat(
                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": 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"
                ),
                "stream_response": False,
            },
            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,
            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)
