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

import typing
from .environment import NeuralTrustApiEnvironment
import httpx
from .core.client_wrapper import SyncClientWrapper
from .evaluation_set.client import EvaluationSetClient
from .testset.client import TestsetClient
from .knowledge_base.client import KnowledgeBaseClient
from .types.trace_task import TraceTask
from .types.user import User
from .types.metadata import Metadata
from .core.request_options import RequestOptions
from .types.trace_response import TraceResponse
from .core.serialization import convert_and_respect_annotation_metadata
from .core.pydantic_utilities import parse_obj_as
from .errors.method_not_allowed_error import MethodNotAllowedError
from json.decoder import JSONDecodeError
from .core.api_error import ApiError
from .types.evaluation_set_response import EvaluationSetResponse
from .types.testset_response import TestsetResponse
from .types.knowledge_base_response import KnowledgeBaseResponse
from .core.client_wrapper import AsyncClientWrapper
from .evaluation_set.client import AsyncEvaluationSetClient
from .testset.client import AsyncTestsetClient
from .knowledge_base.client import AsyncKnowledgeBaseClient

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


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

    Parameters
    ----------
    base_url : typing.Optional[str]
        The base url to use for requests from the client.

    environment : NeuralTrustApiEnvironment
        The environment to use for requests from the client. from .environment import NeuralTrustApiEnvironment



        Defaults to NeuralTrustApiEnvironment.DEFAULT



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

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

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

    Examples
    --------
    from NeuralTrust import NeuralTrustApi

    client = NeuralTrustApi(
        api_key="YOUR_API_KEY",
    )
    """

    def __init__(
        self,
        *,
        base_url: typing.Optional[str] = None,
        environment: NeuralTrustApiEnvironment = NeuralTrustApiEnvironment.DEFAULT,
        api_key: str,
        timeout: typing.Optional[float] = None,
        follow_redirects: typing.Optional[bool] = True,
        httpx_client: typing.Optional[httpx.Client] = None,
    ):
        _defaulted_timeout = (
            timeout if timeout is not None else 60 if httpx_client is None else None
        )
        self._client_wrapper = SyncClientWrapper(
            base_url=_get_base_url(base_url=base_url, environment=environment),
            api_key=api_key,
            httpx_client=httpx_client
            if httpx_client is not None
            else httpx.Client(
                timeout=_defaulted_timeout, follow_redirects=follow_redirects
            )
            if follow_redirects is not None
            else httpx.Client(timeout=_defaulted_timeout),
            timeout=_defaulted_timeout,
        )
        self.evaluation_set = EvaluationSetClient(client_wrapper=self._client_wrapper)
        self.testset = TestsetClient(client_wrapper=self._client_wrapper)
        self.knowledge_base = KnowledgeBaseClient(client_wrapper=self._client_wrapper)

    def trace(
        self,
        *,
        conversation_id: str,
        interaction_id: str,
        type: str,
        task: TraceTask,
        input: str,
        start_timestamp: str,
        end_timestamp: str,
        latency: typing.Optional[int] = OMIT,
        session_id: typing.Optional[str] = OMIT,
        channel_id: typing.Optional[str] = OMIT,
        output: typing.Optional[str] = OMIT,
        custom: typing.Optional[str] = OMIT,
        user: typing.Optional[User] = OMIT,
        metadata: typing.Optional[Metadata] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> TraceResponse:
        """
        Add a new trace

        Parameters
        ----------
        conversation_id : str
            conversation id

        interaction_id : str
            interaction id

        type : str
            type of trace

        task : TraceTask
            task to perform

        input : str
            content to retrieve or generate

        start_timestamp : str
            start timestamp of the trace

        end_timestamp : str
            end timestamp of the trace

        latency : typing.Optional[int]
            latency of the trace

        session_id : typing.Optional[str]
            session id

        channel_id : typing.Optional[str]
            channel id

        output : typing.Optional[str]
            generated content

        custom : typing.Optional[str]
            custom data

        user : typing.Optional[User]

        metadata : typing.Optional[Metadata]

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

        Returns
        -------
        TraceResponse
            Successful operation

        Examples
        --------
        from NeuralTrust import NeuralTrustApi

        client = NeuralTrustApi(
            api_key="YOUR_API_KEY",
        )
        client.trace(
            conversation_id="conversation_id",
            interaction_id="interaction_id",
            type="type",
            task="retrieval",
            input="What is the weather in Tokyo?",
            start_timestamp="start_timestamp",
            end_timestamp="end_timestamp",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "trace",
            method="POST",
            json={
                "conversation_id": conversation_id,
                "interaction_id": interaction_id,
                "session_id": session_id,
                "type": type,
                "task": task,
                "channel_id": channel_id,
                "input": input,
                "output": output,
                "start_timestamp": start_timestamp,
                "end_timestamp": end_timestamp,
                "latency": latency,
                "custom": custom,
                "user": convert_and_respect_annotation_metadata(
                    object_=user, annotation=User, direction="write"
                ),
                "metadata": convert_and_respect_annotation_metadata(
                    object_=metadata, annotation=Metadata, direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    TraceResponse,
                    parse_obj_as(
                        type_=TraceResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # 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 evaluation_set(
        self,
        *,
        name: str,
        description: str,
        scheduler: typing.Optional[str] = OMIT,
        metadata: typing.Optional[Metadata] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> EvaluationSetResponse:
        """
        Add a new evaluation set

        Parameters
        ----------
        name : str
            Name of the evaluation set

        description : str
            Description of the evaluation set

        scheduler : typing.Optional[str]
            Scheduler of the evaluation set

        metadata : typing.Optional[Metadata]

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

        Returns
        -------
        EvaluationSetResponse
            Successful operation

        Examples
        --------
        from NeuralTrust import NeuralTrustApi

        client = NeuralTrustApi(
            api_key="YOUR_API_KEY",
        )
        client.evaluation_set(
            name="name",
            description="description",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            "evaluation-set",
            method="POST",
            json={
                "name": name,
                "description": description,
                "scheduler": scheduler,
                "metadata": convert_and_respect_annotation_metadata(
                    object_=metadata, annotation=Metadata, direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    EvaluationSetResponse,
                    parse_obj_as(
                        type_=EvaluationSetResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # 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 testset(
        self,
        *,
        name: typing.Optional[str] = OMIT,
        evaluation_set_id: typing.Optional[str] = OMIT,
        knowledge_base_id: typing.Optional[str] = OMIT,
        num_questions: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> TestsetResponse:
        """
        Add a new testset

        Parameters
        ----------
        name : typing.Optional[str]
            Name of the testset

        evaluation_set_id : typing.Optional[str]
            ID of the evaluation set

        knowledge_base_id : typing.Optional[str]
            ID of the knowledge base

        num_questions : typing.Optional[int]
            Number of questions in the testset

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

        Returns
        -------
        TestsetResponse
            Successful operation

        Examples
        --------
        from NeuralTrust import NeuralTrustApi

        client = NeuralTrustApi(
            api_key="YOUR_API_KEY",
        )
        client.testset()
        """
        _response = self._client_wrapper.httpx_client.request(
            "testset",
            method="POST",
            json={
                "name": name,
                "evaluation_set_id": evaluation_set_id,
                "knowledge_base_id": knowledge_base_id,
                "num_questions": num_questions,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    TestsetResponse,
                    parse_obj_as(
                        type_=TestsetResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # 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 knowledge_base(
        self,
        *,
        type: typing.Optional[str] = OMIT,
        credentials: typing.Optional[
            typing.Dict[str, typing.Optional[typing.Any]]
        ] = OMIT,
        seed_topics: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> KnowledgeBaseResponse:
        """
        Add a new knowledge base

        Parameters
        ----------
        type : typing.Optional[str]
            Type of the knowledge base

        credentials : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Credentials of the knowledge base

        seed_topics : typing.Optional[typing.Sequence[str]]
            Seed topics of the knowledge base

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

        Returns
        -------
        KnowledgeBaseResponse
            Successful operation

        Examples
        --------
        from NeuralTrust import NeuralTrustApi

        client = NeuralTrustApi(
            api_key="YOUR_API_KEY",
        )
        client.knowledge_base()
        """
        print("Creating...")
        _response = self._client_wrapper.httpx_client.request(
            "knowledge-base",
            method="POST",
            json={
                "type": type,
                "credentials": credentials,
                "seed_topics": seed_topics,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    KnowledgeBaseResponse,
                    parse_obj_as(
                        type_=KnowledgeBaseResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # 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 AsyncNeuralTrustApi:
    """
    Use this class to access the different functions within the SDK. You can instantiate any number of clients with different configuration that will propagate to these functions.

    Parameters
    ----------
    base_url : typing.Optional[str]
        The base url to use for requests from the client.

    environment : NeuralTrustApiEnvironment
        The environment to use for requests from the client. from .environment import NeuralTrustApiEnvironment



        Defaults to NeuralTrustApiEnvironment.DEFAULT



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

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

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

    Examples
    --------
    from NeuralTrust import AsyncNeuralTrustApi

    client = AsyncNeuralTrustApi(
        api_key="YOUR_API_KEY",
    )
    """

    def __init__(
        self,
        *,
        base_url: typing.Optional[str] = None,
        environment: NeuralTrustApiEnvironment = NeuralTrustApiEnvironment.DEFAULT,
        api_key: str,
        timeout: typing.Optional[float] = None,
        follow_redirects: typing.Optional[bool] = True,
        httpx_client: typing.Optional[httpx.AsyncClient] = None,
    ):
        _defaulted_timeout = (
            timeout if timeout is not None else 60 if httpx_client is None else None
        )
        self._client_wrapper = AsyncClientWrapper(
            base_url=_get_base_url(base_url=base_url, environment=environment),
            api_key=api_key,
            httpx_client=httpx_client
            if httpx_client is not None
            else httpx.AsyncClient(
                timeout=_defaulted_timeout, follow_redirects=follow_redirects
            )
            if follow_redirects is not None
            else httpx.AsyncClient(timeout=_defaulted_timeout),
            timeout=_defaulted_timeout,
        )
        self.evaluation_set = AsyncEvaluationSetClient(
            client_wrapper=self._client_wrapper
        )
        self.testset = AsyncTestsetClient(client_wrapper=self._client_wrapper)
        self.knowledge_base = AsyncKnowledgeBaseClient(
            client_wrapper=self._client_wrapper
        )

    async def trace(
        self,
        *,
        conversation_id: str,
        interaction_id: str,
        type: str,
        task: TraceTask,
        input: str,
        start_timestamp: str,
        end_timestamp: str,
        session_id: typing.Optional[str] = OMIT,
        channel_id: typing.Optional[str] = OMIT,
        output: typing.Optional[str] = OMIT,
        custom: typing.Optional[str] = OMIT,
        user: typing.Optional[User] = OMIT,
        metadata: typing.Optional[Metadata] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> TraceResponse:
        """
        Add a new trace

        Parameters
        ----------
        conversation_id : str
            conversation id

        interaction_id : str
            interaction id

        type : str
            type of trace

        task : TraceTask
            task to perform

        input : str
            content to retrieve or generate

        start_timestamp : str
            start timestamp of the trace

        end_timestamp : str
            end timestamp of the trace

        session_id : typing.Optional[str]
            session id

        channel_id : typing.Optional[str]
            channel id

        output : typing.Optional[str]
            generated content

        custom : typing.Optional[str]
            custom data

        user : typing.Optional[User]

        metadata : typing.Optional[Metadata]

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

        Returns
        -------
        TraceResponse
            Successful operation

        Examples
        --------
        import asyncio

        from NeuralTrust import AsyncNeuralTrustApi

        client = AsyncNeuralTrustApi(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.trace(
                conversation_id="conversation_id",
                interaction_id="interaction_id",
                type="type",
                task="retrieval",
                input="What is the weather in Tokyo?",
                start_timestamp="start_timestamp",
                end_timestamp="end_timestamp",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "trace",
            method="POST",
            json={
                "conversation_id": conversation_id,
                "interaction_id": interaction_id,
                "session_id": session_id,
                "type": type,
                "task": task,
                "channel_id": channel_id,
                "input": input,
                "output": output,
                "start_timestamp": start_timestamp,
                "end_timestamp": end_timestamp,
                "custom": custom,
                "user": convert_and_respect_annotation_metadata(
                    object_=user, annotation=User, direction="write"
                ),
                "metadata": convert_and_respect_annotation_metadata(
                    object_=metadata, annotation=Metadata, direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    TraceResponse,
                    parse_obj_as(
                        type_=TraceResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # 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 evaluation_set(
        self,
        *,
        name: str,
        description: str,
        scheduler: typing.Optional[str] = OMIT,
        metadata: typing.Optional[Metadata] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> EvaluationSetResponse:
        """
        Add a new evaluation set

        Parameters
        ----------
        name : str
            Name of the evaluation set

        description : str
            Description of the evaluation set

        scheduler : typing.Optional[str]
            Scheduler of the evaluation set

        metadata : typing.Optional[Metadata]

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

        Returns
        -------
        EvaluationSetResponse
            Successful operation

        Examples
        --------
        import asyncio

        from NeuralTrust import AsyncNeuralTrustApi

        client = AsyncNeuralTrustApi(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.evaluation_set(
                name="name",
                description="description",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "evaluation-set",
            method="POST",
            json={
                "name": name,
                "description": description,
                "scheduler": scheduler,
                "metadata": convert_and_respect_annotation_metadata(
                    object_=metadata, annotation=Metadata, direction="write"
                ),
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    EvaluationSetResponse,
                    parse_obj_as(
                        type_=EvaluationSetResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # 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 testset(
        self,
        *,
        name: typing.Optional[str] = OMIT,
        evaluation_set_id: typing.Optional[str] = OMIT,
        knowledge_base_id: typing.Optional[str] = OMIT,
        num_questions: typing.Optional[int] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> TestsetResponse:
        """
        Add a new testset

        Parameters
        ----------
        name : typing.Optional[str]
            Name of the testset

        evaluation_set_id : typing.Optional[str]
            ID of the evaluation set

        knowledge_base_id : typing.Optional[str]
            ID of the knowledge base

        num_questions : typing.Optional[int]
            Number of questions in the testset

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

        Returns
        -------
        TestsetResponse
            Successful operation

        Examples
        --------
        import asyncio

        from NeuralTrust import AsyncNeuralTrustApi

        client = AsyncNeuralTrustApi(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.testset()


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "testset",
            method="POST",
            json={
                "name": name,
                "evaluation_set_id": evaluation_set_id,
                "knowledge_base_id": knowledge_base_id,
                "num_questions": num_questions,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    TestsetResponse,
                    parse_obj_as(
                        type_=TestsetResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # 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 knowledge_base(
        self,
        *,
        type: typing.Optional[str] = OMIT,
        credentials: typing.Optional[
            typing.Dict[str, typing.Optional[typing.Any]]
        ] = OMIT,
        seed_topics: typing.Optional[typing.Sequence[str]] = OMIT,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> KnowledgeBaseResponse:
        """
        Add a new knowledge base

        Parameters
        ----------
        type : typing.Optional[str]
            Type of the knowledge base

        credentials : typing.Optional[typing.Dict[str, typing.Optional[typing.Any]]]
            Credentials of the knowledge base

        seed_topics : typing.Optional[typing.Sequence[str]]
            Seed topics of the knowledge base

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

        Returns
        -------
        KnowledgeBaseResponse
            Successful operation

        Examples
        --------
        import asyncio

        from NeuralTrust import AsyncNeuralTrustApi

        client = AsyncNeuralTrustApi(
            api_key="YOUR_API_KEY",
        )


        async def main() -> None:
            await client.knowledge_base()


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "knowledge-base",
            method="POST",
            json={
                "type": type,
                "credentials": credentials,
                "seed_topics": seed_topics,
            },
            request_options=request_options,
            omit=OMIT,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    KnowledgeBaseResponse,
                    parse_obj_as(
                        type_=KnowledgeBaseResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 405:
                raise MethodNotAllowedError(
                    typing.cast(
                        typing.Optional[typing.Any],
                        parse_obj_as(
                            type_=typing.Optional[typing.Any],  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)


def _get_base_url(
    *, base_url: typing.Optional[str] = None, environment: NeuralTrustApiEnvironment
) -> str:
    if base_url is not None:
        return base_url
    elif environment is not None:
        return environment.value
    else:
        raise Exception(
            "Please pass in either base_url or environment to construct the client"
        )
