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

from ..core.client_wrapper import SyncClientWrapper
import typing
from ..core.request_options import RequestOptions
from ..types.run import Run
from ..core.unchecked_base_model import construct_type
from ..errors.unprocessable_entity_error import UnprocessableEntityError
from ..types.http_validation_error import HttpValidationError
from json.decoder import JSONDecodeError
from ..core.api_error import ApiError
from ..core.jsonable_encoder import jsonable_encoder
import datetime as dt
from ..types.message_role import MessageRole
from ..types.letta_schemas_message_message import LettaSchemasMessageMessage
from ..core.datetime_utils import serialize_datetime
from ..types.usage_statistics import UsageStatistics
from ..core.client_wrapper import AsyncClientWrapper


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

    def list_runs(self, *, request_options: typing.Optional[RequestOptions] = None) -> typing.List[Run]:
        """
        List all runs.

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

        Returns
        -------
        typing.List[Run]
            Successful Response

        Examples
        --------
        from letta_client import Letta

        client = Letta(
            token="YOUR_TOKEN",
        )
        client.runs.list_runs()
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/runs/",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Run],
                    construct_type(
                        type_=typing.List[Run],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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 list_active_runs(self, *, request_options: typing.Optional[RequestOptions] = None) -> typing.List[Run]:
        """
        List all active runs.

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

        Returns
        -------
        typing.List[Run]
            Successful Response

        Examples
        --------
        from letta_client import Letta

        client = Letta(
            token="YOUR_TOKEN",
        )
        client.runs.list_active_runs()
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/runs/active",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Run],
                    construct_type(
                        type_=typing.List[Run],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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_run(self, run_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Run:
        """
        Get the status of a run.

        Parameters
        ----------
        run_id : str

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

        Returns
        -------
        Run
            Successful Response

        Examples
        --------
        from letta_client import Letta

        client = Letta(
            token="YOUR_TOKEN",
        )
        client.runs.get_run(
            run_id="run_id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/runs/{jsonable_encoder(run_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Run,
                    construct_type(
                        type_=Run,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    def delete_run(self, run_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Run:
        """
        Delete a run by its run_id.

        Parameters
        ----------
        run_id : str

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

        Returns
        -------
        Run
            Successful Response

        Examples
        --------
        from letta_client import Letta

        client = Letta(
            token="YOUR_TOKEN",
        )
        client.runs.delete_run(
            run_id="run_id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/runs/{jsonable_encoder(run_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Run,
                    construct_type(
                        type_=Run,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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_run_messages(
        self,
        run_id: str,
        *,
        cursor: typing.Optional[str] = None,
        start_date: typing.Optional[dt.datetime] = None,
        end_date: typing.Optional[dt.datetime] = None,
        limit: typing.Optional[int] = None,
        query_text: typing.Optional[str] = None,
        ascending: typing.Optional[bool] = None,
        tags: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        match_all_tags: typing.Optional[bool] = None,
        role: typing.Optional[MessageRole] = None,
        tool_name: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[LettaSchemasMessageMessage]:
        """
        Get messages associated with a run with filtering options.

        Args:
            run_id: ID of the run
            cursor: Cursor for pagination
            start_date: Filter messages after this date
            end_date: Filter messages before this date
            limit: Maximum number of messages to return
            query_text: Search text in message content
            ascending: Sort order by creation time
            tags: Filter by message tags
            match_all_tags: If true, match all tags. If false, match any tag
            role: Filter by message role (user/assistant/system/tool)
            tool_name: Filter by tool call name
            user_id: ID of the user making the request

        Parameters
        ----------
        run_id : str

        cursor : typing.Optional[str]
            Cursor for pagination

        start_date : typing.Optional[dt.datetime]
            Filter messages after this date

        end_date : typing.Optional[dt.datetime]
            Filter messages before this date

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

        query_text : typing.Optional[str]
            Search text in message content

        ascending : typing.Optional[bool]
            Sort order by creation time

        tags : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter by message tags

        match_all_tags : typing.Optional[bool]
            If true, match all tags. If false, match any tag

        role : typing.Optional[MessageRole]
            Filter by message role

        tool_name : typing.Optional[str]
            Filter by tool call name

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

        Returns
        -------
        typing.List[LettaSchemasMessageMessage]
            Successful Response

        Examples
        --------
        from letta_client import Letta

        client = Letta(
            token="YOUR_TOKEN",
        )
        client.runs.get_run_messages(
            run_id="run_id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/runs/{jsonable_encoder(run_id)}/messages",
            method="GET",
            params={
                "cursor": cursor,
                "start_date": serialize_datetime(start_date) if start_date is not None else None,
                "end_date": serialize_datetime(end_date) if end_date is not None else None,
                "limit": limit,
                "query_text": query_text,
                "ascending": ascending,
                "tags": tags,
                "match_all_tags": match_all_tags,
                "role": role,
                "tool_name": tool_name,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[LettaSchemasMessageMessage],
                    construct_type(
                        type_=typing.List[LettaSchemasMessageMessage],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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_run_usage(self, run_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> UsageStatistics:
        """
        Get usage statistics for a run.

        Parameters
        ----------
        run_id : str

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

        Returns
        -------
        UsageStatistics
            Successful Response

        Examples
        --------
        from letta_client import Letta

        client = Letta(
            token="YOUR_TOKEN",
        )
        client.runs.get_run_usage(
            run_id="run_id",
        )
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/runs/{jsonable_encoder(run_id)}/usage",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    UsageStatistics,
                    construct_type(
                        type_=UsageStatistics,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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 AsyncRunsClient:
    def __init__(self, *, client_wrapper: AsyncClientWrapper):
        self._client_wrapper = client_wrapper

    async def list_runs(self, *, request_options: typing.Optional[RequestOptions] = None) -> typing.List[Run]:
        """
        List all runs.

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

        Returns
        -------
        typing.List[Run]
            Successful Response

        Examples
        --------
        import asyncio

        from letta_client import AsyncLetta

        client = AsyncLetta(
            token="YOUR_TOKEN",
        )


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


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/runs/",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Run],
                    construct_type(
                        type_=typing.List[Run],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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 list_active_runs(self, *, request_options: typing.Optional[RequestOptions] = None) -> typing.List[Run]:
        """
        List all active runs.

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

        Returns
        -------
        typing.List[Run]
            Successful Response

        Examples
        --------
        import asyncio

        from letta_client import AsyncLetta

        client = AsyncLetta(
            token="YOUR_TOKEN",
        )


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


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/runs/active",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[Run],
                    construct_type(
                        type_=typing.List[Run],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get_run(self, run_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Run:
        """
        Get the status of a run.

        Parameters
        ----------
        run_id : str

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

        Returns
        -------
        Run
            Successful Response

        Examples
        --------
        import asyncio

        from letta_client import AsyncLetta

        client = AsyncLetta(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.runs.get_run(
                run_id="run_id",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/runs/{jsonable_encoder(run_id)}",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Run,
                    construct_type(
                        type_=Run,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def delete_run(self, run_id: str, *, request_options: typing.Optional[RequestOptions] = None) -> Run:
        """
        Delete a run by its run_id.

        Parameters
        ----------
        run_id : str

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

        Returns
        -------
        Run
            Successful Response

        Examples
        --------
        import asyncio

        from letta_client import AsyncLetta

        client = AsyncLetta(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.runs.delete_run(
                run_id="run_id",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/runs/{jsonable_encoder(run_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    Run,
                    construct_type(
                        type_=Run,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get_run_messages(
        self,
        run_id: str,
        *,
        cursor: typing.Optional[str] = None,
        start_date: typing.Optional[dt.datetime] = None,
        end_date: typing.Optional[dt.datetime] = None,
        limit: typing.Optional[int] = None,
        query_text: typing.Optional[str] = None,
        ascending: typing.Optional[bool] = None,
        tags: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        match_all_tags: typing.Optional[bool] = None,
        role: typing.Optional[MessageRole] = None,
        tool_name: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> typing.List[LettaSchemasMessageMessage]:
        """
        Get messages associated with a run with filtering options.

        Args:
            run_id: ID of the run
            cursor: Cursor for pagination
            start_date: Filter messages after this date
            end_date: Filter messages before this date
            limit: Maximum number of messages to return
            query_text: Search text in message content
            ascending: Sort order by creation time
            tags: Filter by message tags
            match_all_tags: If true, match all tags. If false, match any tag
            role: Filter by message role (user/assistant/system/tool)
            tool_name: Filter by tool call name
            user_id: ID of the user making the request

        Parameters
        ----------
        run_id : str

        cursor : typing.Optional[str]
            Cursor for pagination

        start_date : typing.Optional[dt.datetime]
            Filter messages after this date

        end_date : typing.Optional[dt.datetime]
            Filter messages before this date

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

        query_text : typing.Optional[str]
            Search text in message content

        ascending : typing.Optional[bool]
            Sort order by creation time

        tags : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter by message tags

        match_all_tags : typing.Optional[bool]
            If true, match all tags. If false, match any tag

        role : typing.Optional[MessageRole]
            Filter by message role

        tool_name : typing.Optional[str]
            Filter by tool call name

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

        Returns
        -------
        typing.List[LettaSchemasMessageMessage]
            Successful Response

        Examples
        --------
        import asyncio

        from letta_client import AsyncLetta

        client = AsyncLetta(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.runs.get_run_messages(
                run_id="run_id",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/runs/{jsonable_encoder(run_id)}/messages",
            method="GET",
            params={
                "cursor": cursor,
                "start_date": serialize_datetime(start_date) if start_date is not None else None,
                "end_date": serialize_datetime(end_date) if end_date is not None else None,
                "limit": limit,
                "query_text": query_text,
                "ascending": ascending,
                "tags": tags,
                "match_all_tags": match_all_tags,
                "role": role,
                "tool_name": tool_name,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    typing.List[LettaSchemasMessageMessage],
                    construct_type(
                        type_=typing.List[LettaSchemasMessageMessage],  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # type: ignore
                            object_=_response.json(),
                        ),
                    )
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, body=_response.text)
        raise ApiError(status_code=_response.status_code, body=_response_json)

    async def get_run_usage(
        self, run_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> UsageStatistics:
        """
        Get usage statistics for a run.

        Parameters
        ----------
        run_id : str

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

        Returns
        -------
        UsageStatistics
            Successful Response

        Examples
        --------
        import asyncio

        from letta_client import AsyncLetta

        client = AsyncLetta(
            token="YOUR_TOKEN",
        )


        async def main() -> None:
            await client.runs.get_run_usage(
                run_id="run_id",
            )


        asyncio.run(main())
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/runs/{jsonable_encoder(run_id)}/usage",
            method="GET",
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                return typing.cast(
                    UsageStatistics,
                    construct_type(
                        type_=UsageStatistics,  # type: ignore
                        object_=_response.json(),
                    ),
                )
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    typing.cast(
                        HttpValidationError,
                        construct_type(
                            type_=HttpValidationError,  # 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)
