# 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.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.forbidden_error import ForbiddenError
from ..errors.not_found_error import NotFoundError
from ..types.bad_request_error_body import BadRequestErrorBody
from ..types.error import Error
from ..types.generation_parameters import GenerationParameters
from ..types.not_found_error_body import NotFoundErrorBody
from ..types.query_full_response import QueryFullResponse
from ..types.query_streamed_response import QueryStreamedResponse
from ..types.search_corpora_parameters import SearchCorporaParameters

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


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

    @contextlib.contextmanager
    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[HttpResponse[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[HttpResponse[typing.Iterator[QueryStreamedResponse]]]

        """
        with self._client_wrapper.httpx_client.stream(
            "v2/query",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "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,
        *,
        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,
    ) -> HttpResponse[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
        -------
        HttpResponse[QueryFullResponse]

        """
        _response = self._client_wrapper.httpx_client.request(
            "v2/query",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "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 AsyncRawQueriesClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    @contextlib.asynccontextmanager
    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[AsyncHttpResponse[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[AsyncHttpResponse[typing.AsyncIterator[QueryStreamedResponse]]]

        """
        async with self._client_wrapper.httpx_client.stream(
            "v2/query",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "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,
        *,
        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,
    ) -> AsyncHttpResponse[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
        -------
        AsyncHttpResponse[QueryFullResponse]

        """
        _response = await self._client_wrapper.httpx_client.request(
            "v2/query",
            base_url=self._client_wrapper.get_environment().default,
            method="POST",
            json={
                "query": query,
                "search": convert_and_respect_annotation_metadata(
                    object_=search, annotation=SearchCorporaParameters, direction="write"
                ),
                "generation": convert_and_respect_annotation_metadata(
                    object_=generation, annotation=GenerationParameters, direction="write"
                ),
                "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)
