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

import typing

from ..core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ..core.request_options import RequestOptions
from ..types.generation_parameters import GenerationParameters
from ..types.query_full_response import QueryFullResponse
from ..types.query_streamed_response import QueryStreamedResponse
from ..types.search_corpora_parameters import SearchCorporaParameters
from .raw_client import AsyncRawQueriesClient, RawQueriesClient

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


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

    @property
    def with_raw_response(self) -> RawQueriesClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        RawQueriesClient
        """
        return self._raw_client

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

        * 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 opt-in Retrieval Augmented Generation (RAG) (`generation`) for enhanced query performance. Generation is opt in by setting the `generation` property. By excluding the property or by setting it to null, the response
        will not include generation. [Learn more](https://docs.vectara.com/docs/learn/grounded-generation/configure-query-summarization)
        * Specify 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-customization-options)
        * Customize citation formats in summaries using the `citations` object to include numeric, HTML, or Markdown links. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#citation-format-in-summary)

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

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

        search : SearchCorporaParameters

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

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

        generation : typing.Optional[GenerationParameters]

        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[QueryStreamedResponse]


        Examples
        --------
        from vectara import Vectara
        from vectara import SearchCorporaParameters
        from vectara import KeyedSearchCorpus
        from vectara import ContextConfiguration
        from vectara import CustomerSpecificReranker
        from vectara import GenerationParameters
        client = Vectara(api_key="YOUR_API_KEY", client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", )
        response = client.queries.query_stream(query='What is a hallucination?', search=SearchCorporaParameters(corpora=[KeyedSearchCorpus(corpus_key='corpus_key', metadata_filter='', lexical_interpolation=0.005, )], context_configuration=ContextConfiguration(sentences_before=2, sentences_after=2, ), reranker=CustomerSpecificReranker(reranker_id='rnk_272725719', ), ), generation=GenerationParameters(response_language="eng", enable_factual_consistency_score=True, ), )
        for chunk in response:
            yield chunk
        """
        with self._raw_client.query_stream(
            query=query,
            search=search,
            request_timeout=request_timeout,
            request_timeout_millis=request_timeout_millis,
            generation=generation,
            save_history=save_history,
            intelligent_query_rewriting=intelligent_query_rewriting,
            request_options=request_options,
        ) as r:
            yield from r.data

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

        * 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 opt-in Retrieval Augmented Generation (RAG) (`generation`) for enhanced query performance. Generation is opt in by setting the `generation` property. By excluding the property or by setting it to null, the response
        will not include generation. [Learn more](https://docs.vectara.com/docs/learn/grounded-generation/configure-query-summarization)
        * Specify 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-customization-options)
        * Customize citation formats in summaries using the `citations` object to include numeric, HTML, or Markdown links. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#citation-format-in-summary)

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

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

        search : SearchCorporaParameters

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

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

        generation : typing.Optional[GenerationParameters]

        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
        -------
        QueryFullResponse


        Examples
        --------
        from vectara import Vectara
        from vectara import SearchCorporaParameters
        from vectara import KeyedSearchCorpus
        from vectara import ContextConfiguration
        from vectara import CustomerSpecificReranker
        from vectara import GenerationParameters
        client = Vectara(api_key="YOUR_API_KEY", client_id="YOUR_CLIENT_ID", client_secret="YOUR_CLIENT_SECRET", )
        client.queries.query(query='What is a hallucination?', search=SearchCorporaParameters(corpora=[KeyedSearchCorpus(corpus_key='corpus_key', metadata_filter='', lexical_interpolation=0.005, )], context_configuration=ContextConfiguration(sentences_before=2, sentences_after=2, ), reranker=CustomerSpecificReranker(reranker_id='rnk_272725719', ), ), generation=GenerationParameters(response_language="eng", enable_factual_consistency_score=True, ), )
        """
        response = self._raw_client.query(
            query=query,
            search=search,
            request_timeout=request_timeout,
            request_timeout_millis=request_timeout_millis,
            generation=generation,
            save_history=save_history,
            intelligent_query_rewriting=intelligent_query_rewriting,
            request_options=request_options,
        )
        return response.data


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

    @property
    def with_raw_response(self) -> AsyncRawQueriesClient:
        """
        Retrieves a raw implementation of this client that returns raw responses.

        Returns
        -------
        AsyncRawQueriesClient
        """
        return self._raw_client

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

        * 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 opt-in Retrieval Augmented Generation (RAG) (`generation`) for enhanced query performance. Generation is opt in by setting the `generation` property. By excluding the property or by setting it to null, the response
        will not include generation. [Learn more](https://docs.vectara.com/docs/learn/grounded-generation/configure-query-summarization)
        * Specify 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-customization-options)
        * Customize citation formats in summaries using the `citations` object to include numeric, HTML, or Markdown links. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#citation-format-in-summary)

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

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

        search : SearchCorporaParameters

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

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

        generation : typing.Optional[GenerationParameters]

        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[QueryStreamedResponse]


        Examples
        --------
        from vectara import AsyncVectara
        from vectara import SearchCorporaParameters
        from vectara import KeyedSearchCorpus
        from vectara import ContextConfiguration
        from vectara import CustomerSpecificReranker
        from vectara import GenerationParameters
        import asyncio
        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='What is a hallucination?', search=SearchCorporaParameters(corpora=[KeyedSearchCorpus(corpus_key='corpus_key', metadata_filter='', lexical_interpolation=0.005, )], context_configuration=ContextConfiguration(sentences_before=2, sentences_after=2, ), reranker=CustomerSpecificReranker(reranker_id='rnk_272725719', ), ), generation=GenerationParameters(response_language="eng", enable_factual_consistency_score=True, ), )
            async for chunk in response:
                yield chunk
        asyncio.run(main())
        """
        async with self._raw_client.query_stream(
            query=query,
            search=search,
            request_timeout=request_timeout,
            request_timeout_millis=request_timeout_millis,
            generation=generation,
            save_history=save_history,
            intelligent_query_rewriting=intelligent_query_rewriting,
            request_options=request_options,
        ) as r:
            async for data in r.data:
                yield data

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

        * 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 opt-in Retrieval Augmented Generation (RAG) (`generation`) for enhanced query performance. Generation is opt in by setting the `generation` property. By excluding the property or by setting it to null, the response
        will not include generation. [Learn more](https://docs.vectara.com/docs/learn/grounded-generation/configure-query-summarization)
        * Specify 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-customization-options)
        * Customize citation formats in summaries using the `citations` object to include numeric, HTML, or Markdown links. [Learn more](https://docs.vectara.com/docs/api-reference/search-apis/search#citation-format-in-summary)

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

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

        search : SearchCorporaParameters

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

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

        generation : typing.Optional[GenerationParameters]

        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
        -------
        QueryFullResponse


        Examples
        --------
        from vectara import AsyncVectara
        from vectara import SearchCorporaParameters
        from vectara import KeyedSearchCorpus
        from vectara import ContextConfiguration
        from vectara import CustomerSpecificReranker
        from vectara import GenerationParameters
        import asyncio
        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='What is a hallucination?', search=SearchCorporaParameters(corpora=[KeyedSearchCorpus(corpus_key='corpus_key', metadata_filter='', lexical_interpolation=0.005, )], context_configuration=ContextConfiguration(sentences_before=2, sentences_after=2, ), reranker=CustomerSpecificReranker(reranker_id='rnk_272725719', ), ), generation=GenerationParameters(response_language="eng", enable_factual_consistency_score=True, ), )
        asyncio.run(main())
        """
        response = await self._raw_client.query(
            query=query,
            search=search,
            request_timeout=request_timeout,
            request_timeout_millis=request_timeout_millis,
            generation=generation,
            save_history=save_history,
            intelligent_query_rewriting=intelligent_query_rewriting,
            request_options=request_options,
        )
        return response.data
