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

import contextlib
import typing
from json.decoder import JSONDecodeError

import httpx_sse
from ..core.api_error import ApiError
from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.http_response import AsyncHttpResponse, HttpResponse
from ..core.jsonable_encoder import jsonable_encoder
from ..core.pagination import AsyncPager, SyncPager
from ..core.pydantic_utilities import parse_obj_as
from ..core.request_options import RequestOptions
from ..core.serialization import convert_and_respect_annotation_metadata
from ..errors.bad_request_error import BadRequestError
from ..errors.conflict_error import ConflictError
from ..errors.forbidden_error import ForbiddenError
from ..errors.not_found_error import NotFoundError
from ..types.bad_request_error_body import BadRequestErrorBody
from ..types.compute_corpus_size_response import ComputeCorpusSizeResponse
from ..types.corpus import Corpus
from ..types.corpus_custom_dimension import CorpusCustomDimension
from ..types.corpus_key import CorpusKey
from ..types.error import Error
from ..types.filter_attribute import FilterAttribute
from ..types.generation_parameters import GenerationParameters
from ..types.list_corpora_response import ListCorporaResponse
from ..types.not_found_error_body import NotFoundErrorBody
from ..types.query_full_response import QueryFullResponse
from ..types.query_streamed_response import QueryStreamedResponse
from ..types.replace_filter_attributes_response import ReplaceFilterAttributesResponse
from .types.search_corpus_parameters import SearchCorpusParameters

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


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

    def list(
        self,
        *,
        limit: typing.Optional[int] = None,
        filter: typing.Optional[str] = None,
        page_key: typing.Optional[str] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[SyncPager[Corpus]]:
        """
        List corpora in the account. The returned corpus objects contain less
        detail compared to those retrieved the direct corpus retrieval operation.

        Parameters
        ----------
        limit : typing.Optional[int]
            The maximum number of corpora to return at one time.

        filter : typing.Optional[str]
            A regular expression to filter the corpora by their name or summary.

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

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

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

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

        Returns
        -------
        HttpResponse[SyncPager[Corpus]]
            List of corpora.
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/corpora",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "limit": limit,
                "filter": filter,
                "page_key": page_key,
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListCorporaResponse,
                    parse_obj_as(
                        type_=ListCorporaResponse,  # 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,
                        filter=filter,
                        page_key=_parsed_next,
                        request_timeout=request_timeout,
                        request_timeout_millis=request_timeout_millis,
                        request_options=request_options,
                    )
                _items = _parsed_response.corpora
                return HttpResponse(
                    response=_response, data=SyncPager(has_next=_has_next, items=_items, get_next=_get_next)
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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,
        *,
        key: CorpusKey,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        queries_are_answers: typing.Optional[bool] = OMIT,
        documents_are_questions: typing.Optional[bool] = OMIT,
        encoder_id: typing.Optional[str] = OMIT,
        encoder_name: typing.Optional[str] = OMIT,
        filter_attributes: typing.Optional[typing.Sequence[FilterAttribute]] = OMIT,
        custom_dimensions: typing.Optional[typing.Sequence[CorpusCustomDimension]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Corpus]:
        """
        Create a corpus, which is a container to store documents and associated metadata. Here, you
        define the unique `corpus_key` that identifies the corpus. The `corpus_key` can be custom-defined
        following your preferred naming convention, allowing you to easily manage the corpus's data and
        reference it in queries. For more information, see
        [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        key : CorpusKey

        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.

        name : typing.Optional[str]
            The name for the corpus. This value defaults to the key.

        description : typing.Optional[str]
            Description of the corpus.

        save_history : typing.Optional[bool]
            Indicates whether to save corpus queries to query history by default.

        queries_are_answers : typing.Optional[bool]
            Queries made to this corpus are considered answers, and not questions.

        documents_are_questions : typing.Optional[bool]
            Documents inside this corpus are considered questions, and not answers.

        encoder_id : typing.Optional[str]
            *Deprecated*: Use `encoder_name` instead.

        encoder_name : typing.Optional[str]
            The encoder used by the corpus, `boomerang-2023-q3`.

        filter_attributes : typing.Optional[typing.Sequence[FilterAttribute]]
            The new filter attributes of the corpus.
            If unset then the corpus will not have filter attributes.

        custom_dimensions : typing.Optional[typing.Sequence[CorpusCustomDimension]]
            A custom dimension is an additional numerical field attached to a document part. You
            can then multiply this numerical field with a query time custom dimension of the same
            name. This allows boosting (or burying) document parts for arbitrary reasons.
            This feature is only enabled for Pro and Enterprise customers.

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

        Returns
        -------
        HttpResponse[Corpus]
            The corpus has been created.
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/corpora",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "key": key,
                "name": name,
                "description": description,
                "save_history": save_history,
                "queries_are_answers": queries_are_answers,
                "documents_are_questions": documents_are_questions,
                "encoder_id": encoder_id,
                "encoder_name": encoder_name,
                "filter_attributes": convert_and_respect_annotation_metadata(
                    object_=filter_attributes, annotation=typing.Sequence[FilterAttribute], direction="write"
                ),
                "custom_dimensions": convert_and_respect_annotation_metadata(
                    object_=custom_dimensions, annotation=typing.Sequence[CorpusCustomDimension], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Corpus,
                    parse_obj_as(
                        type_=Corpus,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 409:
                raise ConflictError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Corpus]:
        """
        Get metadata about a corpus. This operation does not search the corpus contents.
        Specify the `corpus_key` to identify the corpus whose metadata you want to
        retrieve. The `corpus_key` is created when the corpus is set up, either through
        the Vectara Console UI or the Create Corpus API. For more information,
        see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to retrieve.

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

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

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

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

    def delete(
        self,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[None]:
        """
        Permanently delete a corpus and all its associated data. The `corpus_key` uniquely identifies
        the corpus. For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to delete.

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

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

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

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

    def update(
        self,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        enabled: typing.Optional[bool] = OMIT,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[Corpus]:
        """
        Enable, disable, or update the name and description of a corpus. This lets you
        manage data availability without deleting the corpus, which is useful for
        maintenance and security purposes. The `corpus_key` uniquely identifies the corpus.
        For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).
        Consider updating the name and description of a corpus dynamically to help keep your data
        aligned with changing business needs.

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to update.

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

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

        enabled : typing.Optional[bool]
            Set whether or not the corpus is enabled. If unset then the corpus will remain in the same state.

        name : typing.Optional[str]
            The name for the corpus. If unset or null, then the corpus will remain in the same state.

        description : typing.Optional[str]
            Description of the corpus. If unset or null, then the corpus will remain in the same state.

        save_history : typing.Optional[bool]
            Indicates whether to save corpus queries to query history by default.

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

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

    def reset(
        self,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[None]:
        """
        Resets a corpus, which removes all documents and data from the specified corpus,
        while keeping the corpus itself. The `corpus_key` uniquely identifies the corpus.
        For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to reset.

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

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

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

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

    def replace_filter_attributes(
        self,
        corpus_key: CorpusKey,
        *,
        filter_attributes: typing.Sequence[FilterAttribute],
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ReplaceFilterAttributesResponse]:
        """
        Replace the filter attributes of a corpus. This does not happen immediately, as
        this operation creates a job that completes asynchronously. These new filter
        attributes will not work until the job completes.

        You can monitor the status of the filter change using the returned job ID. The
        `corpus_key` uniquely identifies the corpus. For more information, see
        [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus having its filters replaced.

        filter_attributes : typing.Sequence[FilterAttribute]
            The new filter attributes.

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

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

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

        Returns
        -------
        HttpResponse[ReplaceFilterAttributesResponse]
            Successfully created a job that will replace the filter attributes.
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v2/corpora/{jsonable_encoder(corpus_key)}/replace_filter_attributes",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "filter_attributes": convert_and_respect_annotation_metadata(
                    object_=filter_attributes, annotation=typing.Sequence[FilterAttribute], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ReplaceFilterAttributesResponse,
                    parse_obj_as(
                        type_=ReplaceFilterAttributesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def compute_size(
        self,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ComputeCorpusSizeResponse]:
        """
        Compute the current size of a corpus, including number of documents, parts, and characters.
        The `corpus_key` uniquely identifies the corpus. For more information, see
        [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to compute size for.

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

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

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

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

    def search(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        save_history: typing.Optional[bool] = None,
        intelligent_query_rewriting: typing.Optional[bool] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[QueryFullResponse]:
        """
        Search a single corpus with a straightforward query request, specifying the corpus key and query parameters.
        * Specify the unique `corpus_key` identifying the corpus to query. The `corpus_key` is
        [created in the Vectara Console UI](https://docs.vectara.com/docs/console-ui/creating-a-corpus) or the [Create Corpus API definition](https://docs.vectara.com/docs/api-reference/admin-apis/create-corpus). When creating a new corpus, you have the option to assign a custom `corpus_key` following your preferred naming convention. This key serves as a unique identifier for the corpus, allowing it to be referenced in search requests. For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).
        * Enter the search `query` string for the corpus, which is the question you want to ask.
        * Set the maximum number of results (`limit`) to return. **Default**: 10, **minimum**: 1
        * Define the `offset` position from which to start in the result set.

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

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to query.

        query : str
            The search query string for the corpus, which is the question the user is asking.

        limit : typing.Optional[int]
            The maximum number of results to return.

        offset : typing.Optional[int]
            The position from which to start in the result set.

        save_history : typing.Optional[bool]
            Indicates whether to save the query in the query history.

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

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

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

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

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

    @contextlib.contextmanager
    def query_stream(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        search: typing.Optional[SearchCorpusParameters] = OMIT,
        generation: typing.Optional[GenerationParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[HttpResponse[typing.Iterator[QueryStreamedResponse]]]:
        """
        Perform an advanced query on a specific corpus to find relevant results, highlight relevant snippets, and use Retrieval Augmented Generation:

        * Specify the unique `corpus_key` identifying the corpus to query. The `corpus_key` is [created in the Vectara Console UI](https://docs.vectara.com/docs/console-ui/creating-a-corpus) or the [Create Corpus API definition](https://docs.vectara.com/docs/api-reference/admin-apis/create-corpus). When creating a new corpus, you have the option to assign a custom `corpus_key` following your preferred naming convention. This key serves as a unique identifier for the corpus, allowing it to be referenced in search requests. For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).
        * 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 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).
        * Use hybrid search to achieve optimal results by setting different values for `lexical_interpolation` (e.g., `0.025`). [Learn more](https://docs.vectara.com/docs/learn/hybrid-search)
        * Specify Vectara's RAG-focused LLM (Mockingbird) 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-options)

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

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to query.

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

        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.

        search : typing.Optional[SearchCorpusParameters]
            The parameters to search one corpus.

        generation : typing.Optional[GenerationParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the query to query history.

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

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

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

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

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

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

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

            yield stream()

    def query(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        search: typing.Optional[SearchCorpusParameters] = OMIT,
        generation: typing.Optional[GenerationParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[QueryFullResponse]:
        """
        Perform an advanced query on a specific corpus to find relevant results, highlight relevant snippets, and use Retrieval Augmented Generation:

        * Specify the unique `corpus_key` identifying the corpus to query. The `corpus_key` is [created in the Vectara Console UI](https://docs.vectara.com/docs/console-ui/creating-a-corpus) or the [Create Corpus API definition](https://docs.vectara.com/docs/api-reference/admin-apis/create-corpus). When creating a new corpus, you have the option to assign a custom `corpus_key` following your preferred naming convention. This key serves as a unique identifier for the corpus, allowing it to be referenced in search requests. For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).
        * 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 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).
        * Use hybrid search to achieve optimal results by setting different values for `lexical_interpolation` (e.g., `0.025`). [Learn more](https://docs.vectara.com/docs/learn/hybrid-search)
        * Specify Vectara's RAG-focused LLM (Mockingbird) 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-options)

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

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to query.

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

        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.

        search : typing.Optional[SearchCorpusParameters]
            The parameters to search one corpus.

        generation : typing.Optional[GenerationParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the query to query history.

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

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

        Returns
        -------
        HttpResponse[QueryFullResponse]

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


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

    async def list(
        self,
        *,
        limit: typing.Optional[int] = None,
        filter: typing.Optional[str] = None,
        page_key: typing.Optional[str] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[AsyncPager[Corpus]]:
        """
        List corpora in the account. The returned corpus objects contain less
        detail compared to those retrieved the direct corpus retrieval operation.

        Parameters
        ----------
        limit : typing.Optional[int]
            The maximum number of corpora to return at one time.

        filter : typing.Optional[str]
            A regular expression to filter the corpora by their name or summary.

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

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

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

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

        Returns
        -------
        AsyncHttpResponse[AsyncPager[Corpus]]
            List of corpora.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/corpora",
            base_url=self._client_wrapper.get_environment().default,
            method="GET",
            params={
                "limit": limit,
                "filter": filter,
                "page_key": page_key,
            },
            headers={
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _parsed_response = typing.cast(
                    ListCorporaResponse,
                    parse_obj_as(
                        type_=ListCorporaResponse,  # 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,
                        filter=filter,
                        page_key=_parsed_next,
                        request_timeout=request_timeout,
                        request_timeout_millis=request_timeout_millis,
                        request_options=request_options,
                    )
                _items = _parsed_response.corpora
                return AsyncHttpResponse(
                    response=_response, data=AsyncPager(has_next=_has_next, items=_items, get_next=_get_next)
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _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,
        *,
        key: CorpusKey,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        queries_are_answers: typing.Optional[bool] = OMIT,
        documents_are_questions: typing.Optional[bool] = OMIT,
        encoder_id: typing.Optional[str] = OMIT,
        encoder_name: typing.Optional[str] = OMIT,
        filter_attributes: typing.Optional[typing.Sequence[FilterAttribute]] = OMIT,
        custom_dimensions: typing.Optional[typing.Sequence[CorpusCustomDimension]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Corpus]:
        """
        Create a corpus, which is a container to store documents and associated metadata. Here, you
        define the unique `corpus_key` that identifies the corpus. The `corpus_key` can be custom-defined
        following your preferred naming convention, allowing you to easily manage the corpus's data and
        reference it in queries. For more information, see
        [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        key : CorpusKey

        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.

        name : typing.Optional[str]
            The name for the corpus. This value defaults to the key.

        description : typing.Optional[str]
            Description of the corpus.

        save_history : typing.Optional[bool]
            Indicates whether to save corpus queries to query history by default.

        queries_are_answers : typing.Optional[bool]
            Queries made to this corpus are considered answers, and not questions.

        documents_are_questions : typing.Optional[bool]
            Documents inside this corpus are considered questions, and not answers.

        encoder_id : typing.Optional[str]
            *Deprecated*: Use `encoder_name` instead.

        encoder_name : typing.Optional[str]
            The encoder used by the corpus, `boomerang-2023-q3`.

        filter_attributes : typing.Optional[typing.Sequence[FilterAttribute]]
            The new filter attributes of the corpus.
            If unset then the corpus will not have filter attributes.

        custom_dimensions : typing.Optional[typing.Sequence[CorpusCustomDimension]]
            A custom dimension is an additional numerical field attached to a document part. You
            can then multiply this numerical field with a query time custom dimension of the same
            name. This allows boosting (or burying) document parts for arbitrary reasons.
            This feature is only enabled for Pro and Enterprise customers.

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

        Returns
        -------
        AsyncHttpResponse[Corpus]
            The corpus has been created.
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/corpora",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "key": key,
                "name": name,
                "description": description,
                "save_history": save_history,
                "queries_are_answers": queries_are_answers,
                "documents_are_questions": documents_are_questions,
                "encoder_id": encoder_id,
                "encoder_name": encoder_name,
                "filter_attributes": convert_and_respect_annotation_metadata(
                    object_=filter_attributes, annotation=typing.Sequence[FilterAttribute], direction="write"
                ),
                "custom_dimensions": convert_and_respect_annotation_metadata(
                    object_=custom_dimensions, annotation=typing.Sequence[CorpusCustomDimension], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    Corpus,
                    parse_obj_as(
                        type_=Corpus,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 409:
                raise ConflictError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # 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,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Corpus]:
        """
        Get metadata about a corpus. This operation does not search the corpus contents.
        Specify the `corpus_key` to identify the corpus whose metadata you want to
        retrieve. The `corpus_key` is created when the corpus is set up, either through
        the Vectara Console UI or the Create Corpus API. For more information,
        see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to retrieve.

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

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

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

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

    async def delete(
        self,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[None]:
        """
        Permanently delete a corpus and all its associated data. The `corpus_key` uniquely identifies
        the corpus. For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to delete.

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

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

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

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

    async def update(
        self,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        enabled: typing.Optional[bool] = OMIT,
        name: typing.Optional[str] = OMIT,
        description: typing.Optional[str] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[Corpus]:
        """
        Enable, disable, or update the name and description of a corpus. This lets you
        manage data availability without deleting the corpus, which is useful for
        maintenance and security purposes. The `corpus_key` uniquely identifies the corpus.
        For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).
        Consider updating the name and description of a corpus dynamically to help keep your data
        aligned with changing business needs.

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to update.

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

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

        enabled : typing.Optional[bool]
            Set whether or not the corpus is enabled. If unset then the corpus will remain in the same state.

        name : typing.Optional[str]
            The name for the corpus. If unset or null, then the corpus will remain in the same state.

        description : typing.Optional[str]
            Description of the corpus. If unset or null, then the corpus will remain in the same state.

        save_history : typing.Optional[bool]
            Indicates whether to save corpus queries to query history by default.

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

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

    async def reset(
        self,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[None]:
        """
        Resets a corpus, which removes all documents and data from the specified corpus,
        while keeping the corpus itself. The `corpus_key` uniquely identifies the corpus.
        For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to reset.

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

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

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

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

    async def replace_filter_attributes(
        self,
        corpus_key: CorpusKey,
        *,
        filter_attributes: typing.Sequence[FilterAttribute],
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ReplaceFilterAttributesResponse]:
        """
        Replace the filter attributes of a corpus. This does not happen immediately, as
        this operation creates a job that completes asynchronously. These new filter
        attributes will not work until the job completes.

        You can monitor the status of the filter change using the returned job ID. The
        `corpus_key` uniquely identifies the corpus. For more information, see
        [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus having its filters replaced.

        filter_attributes : typing.Sequence[FilterAttribute]
            The new filter attributes.

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

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

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

        Returns
        -------
        AsyncHttpResponse[ReplaceFilterAttributesResponse]
            Successfully created a job that will replace the filter attributes.
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v2/corpora/{jsonable_encoder(corpus_key)}/replace_filter_attributes",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "filter_attributes": convert_and_respect_annotation_metadata(
                    object_=filter_attributes, annotation=typing.Sequence[FilterAttribute], direction="write"
                ),
            },
            headers={
                "content-type": "application/json",
                "Request-Timeout": str(request_timeout) if request_timeout is not None else None,
                "Request-Timeout-Millis": str(request_timeout_millis) if request_timeout_millis is not None else None,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ReplaceFilterAttributesResponse,
                    parse_obj_as(
                        type_=ReplaceFilterAttributesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def compute_size(
        self,
        corpus_key: CorpusKey,
        *,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ComputeCorpusSizeResponse]:
        """
        Compute the current size of a corpus, including number of documents, parts, and characters.
        The `corpus_key` uniquely identifies the corpus. For more information, see
        [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to compute size for.

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

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

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

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

    async def search(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        save_history: typing.Optional[bool] = None,
        intelligent_query_rewriting: typing.Optional[bool] = None,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[QueryFullResponse]:
        """
        Search a single corpus with a straightforward query request, specifying the corpus key and query parameters.
        * Specify the unique `corpus_key` identifying the corpus to query. The `corpus_key` is
        [created in the Vectara Console UI](https://docs.vectara.com/docs/console-ui/creating-a-corpus) or the [Create Corpus API definition](https://docs.vectara.com/docs/api-reference/admin-apis/create-corpus). When creating a new corpus, you have the option to assign a custom `corpus_key` following your preferred naming convention. This key serves as a unique identifier for the corpus, allowing it to be referenced in search requests. For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).
        * Enter the search `query` string for the corpus, which is the question you want to ask.
        * Set the maximum number of results (`limit`) to return. **Default**: 10, **minimum**: 1
        * Define the `offset` position from which to start in the result set.

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

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to query.

        query : str
            The search query string for the corpus, which is the question the user is asking.

        limit : typing.Optional[int]
            The maximum number of results to return.

        offset : typing.Optional[int]
            The position from which to start in the result set.

        save_history : typing.Optional[bool]
            Indicates whether to save the query in the query history.

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

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

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

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

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

    @contextlib.asynccontextmanager
    async def query_stream(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        search: typing.Optional[SearchCorpusParameters] = OMIT,
        generation: typing.Optional[GenerationParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[AsyncHttpResponse[typing.AsyncIterator[QueryStreamedResponse]]]:
        """
        Perform an advanced query on a specific corpus to find relevant results, highlight relevant snippets, and use Retrieval Augmented Generation:

        * Specify the unique `corpus_key` identifying the corpus to query. The `corpus_key` is [created in the Vectara Console UI](https://docs.vectara.com/docs/console-ui/creating-a-corpus) or the [Create Corpus API definition](https://docs.vectara.com/docs/api-reference/admin-apis/create-corpus). When creating a new corpus, you have the option to assign a custom `corpus_key` following your preferred naming convention. This key serves as a unique identifier for the corpus, allowing it to be referenced in search requests. For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).
        * 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 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).
        * Use hybrid search to achieve optimal results by setting different values for `lexical_interpolation` (e.g., `0.025`). [Learn more](https://docs.vectara.com/docs/learn/hybrid-search)
        * Specify Vectara's RAG-focused LLM (Mockingbird) 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-options)

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

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to query.

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

        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.

        search : typing.Optional[SearchCorpusParameters]
            The parameters to search one corpus.

        generation : typing.Optional[GenerationParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the query to query history.

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

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

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

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

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

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

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

            yield await stream()

    async def query(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        request_timeout: typing.Optional[int] = None,
        request_timeout_millis: typing.Optional[int] = None,
        search: typing.Optional[SearchCorpusParameters] = OMIT,
        generation: typing.Optional[GenerationParameters] = OMIT,
        save_history: typing.Optional[bool] = OMIT,
        intelligent_query_rewriting: typing.Optional[bool] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[QueryFullResponse]:
        """
        Perform an advanced query on a specific corpus to find relevant results, highlight relevant snippets, and use Retrieval Augmented Generation:

        * Specify the unique `corpus_key` identifying the corpus to query. The `corpus_key` is [created in the Vectara Console UI](https://docs.vectara.com/docs/console-ui/creating-a-corpus) or the [Create Corpus API definition](https://docs.vectara.com/docs/api-reference/admin-apis/create-corpus). When creating a new corpus, you have the option to assign a custom `corpus_key` following your preferred naming convention. This key serves as a unique identifier for the corpus, allowing it to be referenced in search requests. For more information, see [Corpus Key Definition](https://docs.vectara.com/docs/api-reference/search-apis/search#corpus-key-definition).
        * 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 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).
        * Use hybrid search to achieve optimal results by setting different values for `lexical_interpolation` (e.g., `0.025`). [Learn more](https://docs.vectara.com/docs/learn/hybrid-search)
        * Specify Vectara's RAG-focused LLM (Mockingbird) 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-options)

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

        Parameters
        ----------
        corpus_key : CorpusKey
            The unique key identifying the corpus to query.

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

        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.

        search : typing.Optional[SearchCorpusParameters]
            The parameters to search one corpus.

        generation : typing.Optional[GenerationParameters]

        save_history : typing.Optional[bool]
            Indicates whether to save the query to query history.

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

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

        Returns
        -------
        AsyncHttpResponse[QueryFullResponse]

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