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

import typing
from ..core.client_wrapper import SyncClientWrapper
from ..types.search_corpora_parameters import SearchCorporaParameters
from ..types.generation_parameters import GenerationParameters
from ..core.request_options import RequestOptions
from ..types.query_streamed_response import QueryStreamedResponse
import httpx_sse
from ..core.pydantic_utilities import parse_obj_as
import json
from ..errors.bad_request_error import BadRequestError
from ..types.bad_request_error_body import BadRequestErrorBody
from ..errors.forbidden_error import ForbiddenError
from ..types.error import Error
from ..errors.not_found_error import NotFoundError
from ..types.not_found_error_body import NotFoundErrorBody
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..types.query_full_response import QueryFullResponse
from ..types.corpus_key import CorpusKey
from ..core.jsonable_encoder import jsonable_encoder
from .types.search_corpus_parameters import SearchCorpusParameters
from ..core.client_wrapper import AsyncClientWrapper

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


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

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

        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.

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

        Parameters
        ----------
        query : str
            The query to receive an answer on.

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

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

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


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

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        response = client.queries.query_stream(
            query="string",
            search=SearchCorporaParameters(
                corpora=[
                    KeyedSearchCorpus(
                        corpus_key={"key": "value"},
                        custom_dimensions={"key": "value"},
                        metadata_filter={"key": "value"},
                        lexical_interpolation={"key": "value"},
                        semantics={"key": "value"},
                    )
                ],
                offset=1,
                limit=1,
                context_configuration=ContextConfiguration(
                    characters_before=1,
                    characters_after=1,
                    sentences_before=1,
                    sentences_after=1,
                    start_tag="string",
                    end_tag="string",
                ),
                reranker=CustomerSpecificReranker(
                    reranker_id="string",
                ),
            ),
            generation=GenerationParameters(
                prompt_name="string",
                max_used_search_results=1,
                prompt_text="string",
                max_response_characters=1,
                response_language="auto",
                model_parameters=ModelParameters(
                    max_tokens=1,
                    temperature=1.1,
                    frequency_penalty=1.1,
                    presence_penalty=1.1,
                ),
                citations=CitationParameters(
                    style="none",
                    url_pattern="string",
                    text_pattern="string",
                ),
                enable_factual_consistency_score=True,
            ),
        )
        for chunk in response:
            yield chunk
        """
        with self._client_wrapper.httpx_client.stream(
            "v2/query",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": search,
                "generation": generation,
                "stream_response": True,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _event_source = httpx_sse.EventSource(_response)
                    for _sse in _event_source.iter_sse():
                        try:
                            yield typing.cast(
                                QueryStreamedResponse,
                                parse_obj_as(
                                    type_=QueryStreamedResponse,  # type: ignore
                                    object_=json.loads(_sse.data),
                                ),
                            )
                        except:
                            pass
                    return
                _response.read()
                if _response.status_code == 400:
                    raise BadRequestError(
                        typing.cast(
                            BadRequestErrorBody,
                            parse_obj_as(
                                type_=BadRequestErrorBody,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                if _response.status_code == 403:
                    raise ForbiddenError(
                        typing.cast(
                            Error,
                            parse_obj_as(
                                type_=Error,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                if _response.status_code == 404:
                    raise NotFoundError(
                        typing.cast(
                            NotFoundErrorBody,
                            parse_obj_as(
                                type_=NotFoundErrorBody,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                _response_json = _response.json()
            except JSONDecodeError:
                raise ApiError(status_code=_response.status_code, body=_response.text)
            raise ApiError(status_code=_response.status_code, body=_response_json)

    def query(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryFullResponse:
        """
        Perform a multi-purpose query that can retrieve relevant information from one or more corpora and generate a response using RAG.

        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.

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

        Parameters
        ----------
        query : str
            The query to receive an answer on.

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

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

        Returns
        -------
        QueryFullResponse


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

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.queries.query(
            query="Am I allowed to bring pets to work?",
            search=SearchCorporaParameters(),
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/query",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": search,
                "generation": generation,
                "stream_response": False,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryFullResponse,
                    parse_obj_as(
                        type_=QueryFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def search(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryFullResponse:
        """
        Search a single corpus with a simple query request.

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

        query : str
            The search query string for the corpus.

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

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

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

        Returns
        -------
        QueryFullResponse
            A response to a query.

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

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.queries.search(
            corpus_key="my-corpus",
            query="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,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryFullResponse,
                    parse_obj_as(
                        type_=QueryFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def query_corpus_stream(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        search: typing.Optional[SearchCorpusParameters] = OMIT,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.Iterator[QueryStreamedResponse]:
        """
        Query a specific corpus and find relevant results, highlight relevant snippets, and use Retrieval Augmented Generation.

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

        query : str
            The query to receive an answer on.

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

        generation : typing.Optional[GenerationParameters]

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

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


        Examples
        --------
        from vectara import (
            CitationParameters,
            ContextConfiguration,
            CustomerSpecificReranker,
            GenerationParameters,
            ModelParameters,
            Vectara,
        )
        from vectara.queries import SearchCorpusParameters

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        response = client.queries.query_corpus_stream(
            corpus_key="string",
            query="string",
            search=SearchCorpusParameters(
                custom_dimensions={"key": "value"},
                metadata_filter={"key": "value"},
                lexical_interpolation={"key": "value"},
                semantics={"key": "value"},
                offset=1,
                limit=1,
                context_configuration=ContextConfiguration(
                    characters_before=1,
                    characters_after=1,
                    sentences_before=1,
                    sentences_after=1,
                    start_tag="string",
                    end_tag="string",
                ),
                reranker=CustomerSpecificReranker(
                    reranker_id="string",
                ),
            ),
            generation=GenerationParameters(
                prompt_name="string",
                max_used_search_results=1,
                prompt_text="string",
                max_response_characters=1,
                response_language="auto",
                model_parameters=ModelParameters(
                    max_tokens=1,
                    temperature=1.1,
                    frequency_penalty=1.1,
                    presence_penalty=1.1,
                ),
                citations=CitationParameters(
                    style="none",
                    url_pattern="string",
                    text_pattern="string",
                ),
                enable_factual_consistency_score=True,
            ),
        )
        for chunk in response:
            yield chunk
        """
        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": search,
                "generation": generation,
                "stream_response": True,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _event_source = httpx_sse.EventSource(_response)
                    for _sse in _event_source.iter_sse():
                        try:
                            yield typing.cast(
                                QueryStreamedResponse,
                                parse_obj_as(
                                    type_=QueryStreamedResponse,  # type: ignore
                                    object_=json.loads(_sse.data),
                                ),
                            )
                        except:
                            pass
                    return
                _response.read()
                if _response.status_code == 400:
                    raise BadRequestError(
                        typing.cast(
                            BadRequestErrorBody,
                            parse_obj_as(
                                type_=BadRequestErrorBody,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                if _response.status_code == 403:
                    raise ForbiddenError(
                        typing.cast(
                            Error,
                            parse_obj_as(
                                type_=Error,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                if _response.status_code == 404:
                    raise NotFoundError(
                        typing.cast(
                            NotFoundErrorBody,
                            parse_obj_as(
                                type_=NotFoundErrorBody,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                _response_json = _response.json()
            except JSONDecodeError:
                raise ApiError(status_code=_response.status_code, body=_response.text)
            raise ApiError(status_code=_response.status_code, body=_response_json)

    def query_corpus(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        search: typing.Optional[SearchCorpusParameters] = OMIT,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryFullResponse:
        """
        Query a specific corpus and find relevant results, highlight relevant snippets, and use Retrieval Augmented Generation.

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

        query : str
            The query to receive an answer on.

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

        generation : typing.Optional[GenerationParameters]

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

        Returns
        -------
        QueryFullResponse


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

        client = Vectara(
            api_key="YOUR_API_KEY",
            client_id="YOUR_CLIENT_ID",
            client_secret="YOUR_CLIENT_SECRET",
        )
        client.queries.query_corpus(
            corpus_key="my-corpus",
            query="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="POST",
            json={
                "query": query,
                "search": search,
                "generation": generation,
                "stream_response": False,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryFullResponse,
                    parse_obj_as(
                        type_=QueryFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


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

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

        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.

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

        Parameters
        ----------
        query : str
            The query to receive an answer on.

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

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

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


        Examples
        --------
        import asyncio

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

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


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


        asyncio.run(main())
        """
        async with self._client_wrapper.httpx_client.stream(
            "v2/query",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": search,
                "generation": generation,
                "stream_response": True,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _event_source = httpx_sse.EventSource(_response)
                    async for _sse in _event_source.aiter_sse():
                        try:
                            yield typing.cast(
                                QueryStreamedResponse,
                                parse_obj_as(
                                    type_=QueryStreamedResponse,  # type: ignore
                                    object_=json.loads(_sse.data),
                                ),
                            )
                        except:
                            pass
                    return
                await _response.aread()
                if _response.status_code == 400:
                    raise BadRequestError(
                        typing.cast(
                            BadRequestErrorBody,
                            parse_obj_as(
                                type_=BadRequestErrorBody,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                if _response.status_code == 403:
                    raise ForbiddenError(
                        typing.cast(
                            Error,
                            parse_obj_as(
                                type_=Error,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                if _response.status_code == 404:
                    raise NotFoundError(
                        typing.cast(
                            NotFoundErrorBody,
                            parse_obj_as(
                                type_=NotFoundErrorBody,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                _response_json = _response.json()
            except JSONDecodeError:
                raise ApiError(status_code=_response.status_code, body=_response.text)
            raise ApiError(status_code=_response.status_code, body=_response_json)

    async def query(
        self,
        *,
        query: str,
        search: SearchCorporaParameters,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryFullResponse:
        """
        Perform a multi-purpose query that can retrieve relevant information from one or more corpora and generate a response using RAG.

        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.

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

        Parameters
        ----------
        query : str
            The query to receive an answer on.

        search : SearchCorporaParameters

        generation : typing.Optional[GenerationParameters]

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

        Returns
        -------
        QueryFullResponse


        Examples
        --------
        import asyncio

        from vectara import AsyncVectara, SearchCorporaParameters

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


        async def main() -> None:
            await client.queries.query(
                query="Am I allowed to bring pets to work?",
                search=SearchCorporaParameters(),
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/query",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": search,
                "generation": generation,
                "stream_response": False,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryFullResponse,
                    parse_obj_as(
                        type_=QueryFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def search(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        limit: typing.Optional[int] = None,
        offset: typing.Optional[int] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryFullResponse:
        """
        Search a single corpus with a simple query request.

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

        query : str
            The search query string for the corpus.

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

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

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

        Returns
        -------
        QueryFullResponse
            A response to a query.

        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

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


        async def main() -> None:
            await client.queries.search(
                corpus_key="my-corpus",
                query="query",
            )


        asyncio.run(main())
        """
        _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,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryFullResponse,
                    parse_obj_as(
                        type_=QueryFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def query_corpus_stream(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        search: typing.Optional[SearchCorpusParameters] = OMIT,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.AsyncIterator[QueryStreamedResponse]:
        """
        Query a specific corpus and find relevant results, highlight relevant snippets, and use Retrieval Augmented Generation.

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

        query : str
            The query to receive an answer on.

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

        generation : typing.Optional[GenerationParameters]

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

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


        Examples
        --------
        import asyncio

        from vectara import (
            AsyncVectara,
            CitationParameters,
            ContextConfiguration,
            CustomerSpecificReranker,
            GenerationParameters,
            ModelParameters,
        )
        from vectara.queries import SearchCorpusParameters

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


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


        asyncio.run(main())
        """
        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": search,
                "generation": generation,
                "stream_response": True,
            },
            request_options=request_options,
            omit=OMIT,
        ) as _response:
            try:
                if 200 <= _response.status_code < 300:
                    _event_source = httpx_sse.EventSource(_response)
                    async for _sse in _event_source.aiter_sse():
                        try:
                            yield typing.cast(
                                QueryStreamedResponse,
                                parse_obj_as(
                                    type_=QueryStreamedResponse,  # type: ignore
                                    object_=json.loads(_sse.data),
                                ),
                            )
                        except:
                            pass
                    return
                await _response.aread()
                if _response.status_code == 400:
                    raise BadRequestError(
                        typing.cast(
                            BadRequestErrorBody,
                            parse_obj_as(
                                type_=BadRequestErrorBody,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                if _response.status_code == 403:
                    raise ForbiddenError(
                        typing.cast(
                            Error,
                            parse_obj_as(
                                type_=Error,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                if _response.status_code == 404:
                    raise NotFoundError(
                        typing.cast(
                            NotFoundErrorBody,
                            parse_obj_as(
                                type_=NotFoundErrorBody,  # type: ignore
                                object_=_response.json(),
                            ),
                        )
                    )
                _response_json = _response.json()
            except JSONDecodeError:
                raise ApiError(status_code=_response.status_code, body=_response.text)
            raise ApiError(status_code=_response.status_code, body=_response_json)

    async def query_corpus(
        self,
        corpus_key: CorpusKey,
        *,
        query: str,
        search: typing.Optional[SearchCorpusParameters] = OMIT,
        generation: typing.Optional[GenerationParameters] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> QueryFullResponse:
        """
        Query a specific corpus and find relevant results, highlight relevant snippets, and use Retrieval Augmented Generation.

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

        query : str
            The query to receive an answer on.

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

        generation : typing.Optional[GenerationParameters]

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

        Returns
        -------
        QueryFullResponse


        Examples
        --------
        import asyncio

        from vectara import AsyncVectara

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


        async def main() -> None:
            await client.queries.query_corpus(
                corpus_key="my-corpus",
                query="query",
            )


        asyncio.run(main())
        """
        _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": search,
                "generation": generation,
                "stream_response": False,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    QueryFullResponse,
                    parse_obj_as(
                        type_=QueryFullResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 400:
                raise BadRequestError(
                    typing.cast(
                        BadRequestErrorBody,
                        parse_obj_as(
                            type_=BadRequestErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 403:
                raise ForbiddenError(
                    typing.cast(
                        Error,
                        parse_obj_as(
                            type_=Error,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            if _response.status_code == 404:
                raise NotFoundError(
                    typing.cast(
                        NotFoundErrorBody,
                        parse_obj_as(
                            type_=NotFoundErrorBody,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)
