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

import typing
from json.decoder import JSONDecodeError

from ...core.api_error import ApiError
from ...core.client_wrapper import AsyncClientWrapper, SyncClientWrapper
from ...core.http_response import AsyncHttpResponse, HttpResponse
from ...core.jsonable_encoder import jsonable_encoder
from ...core.parse_error import ParsingError
from ...core.request_options import RequestOptions
from ...core.unchecked_base_model import construct_type
from ...errors.unprocessable_entity_error import UnprocessableEntityError
from ...types.conversation_initiation_source import ConversationInitiationSource
from ...types.conversation_product import ConversationProduct
from ...types.conversation_signed_url_response_model import ConversationSignedUrlResponseModel
from ...types.evaluation_success_result import EvaluationSuccessResult
from ...types.get_conversation_response_model import GetConversationResponseModel
from ...types.get_conversations_page_response_model import GetConversationsPageResponseModel
from ...types.get_sip_log_messages_response import GetSipLogMessagesResponse
from ...types.token_response_model import TokenResponseModel
from .types.conversations_get_request_format import ConversationsGetRequestFormat
from .types.conversations_list_request_exclude_statuses_item import ConversationsListRequestExcludeStatusesItem
from .types.conversations_list_request_summary_mode import ConversationsListRequestSummaryMode
from pydantic import ValidationError


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

    def get_signed_url(
        self,
        *,
        agent_id: str,
        include_conversation_id: typing.Optional[bool] = None,
        branch_id: typing.Optional[str] = None,
        environment: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[ConversationSignedUrlResponseModel]:
        """
        Get a signed url to start a conversation with an agent with an agent that requires authorization

        Parameters
        ----------
        agent_id : str
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        include_conversation_id : typing.Optional[bool]
            Whether to include a conversation_id with the response. If included, the conversation_signature cannot be used again.

        branch_id : typing.Optional[str]
            The ID of the branch to use

        environment : typing.Optional[str]
            The environment to use for resolving environment variables (e.g. 'production', 'staging'). Defaults to 'production'.

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

        Returns
        -------
        HttpResponse[ConversationSignedUrlResponseModel]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/conversation/get-signed-url",
            method="GET",
            params={
                "agent_id": agent_id,
                "include_conversation_id": include_conversation_id,
                "branch_id": branch_id,
                "environment": environment,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConversationSignedUrlResponseModel,
                    construct_type(
                        type_=ConversationSignedUrlResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_webrtc_token(
        self,
        *,
        agent_id: str,
        participant_name: typing.Optional[str] = None,
        branch_id: typing.Optional[str] = None,
        environment: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[TokenResponseModel]:
        """
        Get a WebRTC session token for real-time communication.

        Parameters
        ----------
        agent_id : str
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        participant_name : typing.Optional[str]
            Optional custom participant name. If not provided, user ID will be used

        branch_id : typing.Optional[str]
            The ID of the branch to use

        environment : typing.Optional[str]
            The environment to use for resolving environment variables (e.g. 'production', 'staging'). Defaults to 'production'.

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

        Returns
        -------
        HttpResponse[TokenResponseModel]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/conversation/token",
            method="GET",
            params={
                "agent_id": agent_id,
                "participant_name": participant_name,
                "branch_id": branch_id,
                "environment": environment,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TokenResponseModel,
                    construct_type(
                        type_=TokenResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        agent_id: typing.Optional[str] = None,
        visited_agent_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        visited_agent_branch_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        call_successful: typing.Optional[EvaluationSuccessResult] = None,
        call_start_before_unix: typing.Optional[int] = None,
        call_start_after_unix: typing.Optional[int] = None,
        call_duration_min_secs: typing.Optional[int] = None,
        call_duration_max_secs: typing.Optional[int] = None,
        rating_max: typing.Optional[int] = None,
        rating_min: typing.Optional[int] = None,
        has_feedback_comment: typing.Optional[bool] = None,
        user_id: typing.Optional[str] = None,
        evaluation_params: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        data_collection_params: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        data_collection_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        evaluation_criteria_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names_successful: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names_errored: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        main_languages: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        page_size: typing.Optional[int] = None,
        summary_mode: typing.Optional[ConversationsListRequestSummaryMode] = None,
        search: typing.Optional[str] = None,
        conversation_initiation_source: typing.Optional[ConversationInitiationSource] = None,
        text_only: typing.Optional[bool] = None,
        conversation_product_type: typing.Optional[ConversationProduct] = None,
        branch_id: typing.Optional[str] = None,
        version_id: typing.Optional[str] = None,
        topic_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        exclude_statuses: typing.Optional[
            typing.Union[
                ConversationsListRequestExcludeStatusesItem,
                typing.Sequence[ConversationsListRequestExcludeStatusesItem],
            ]
        ] = None,
        tag_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        workflow_node_entered_id: typing.Optional[str] = None,
        termination_reasons: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[GetConversationsPageResponseModel]:
        """
        Get all conversations of agents that user owns. With option to restrict to a specific agent.

        Parameters
        ----------
        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

        agent_id : typing.Optional[str]
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        visited_agent_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations where any of these agents participated. Can not exceed 50 values.

        visited_agent_branch_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations where any of these agent branches participated. Can not exceed 50 values.

        call_successful : typing.Optional[EvaluationSuccessResult]
            The result of the success evaluation

        call_start_before_unix : typing.Optional[int]
            Unix timestamp (in seconds) to filter conversations up to this start date.

        call_start_after_unix : typing.Optional[int]
            Unix timestamp (in seconds) to filter conversations after to this start date.

        call_duration_min_secs : typing.Optional[int]
            Minimum call duration in seconds.

        call_duration_max_secs : typing.Optional[int]
            Maximum call duration in seconds.

        rating_max : typing.Optional[int]
            Maximum overall rating (1-5).

        rating_min : typing.Optional[int]
            Minimum overall rating (1-5).

        has_feedback_comment : typing.Optional[bool]
            Filter conversations with user feedback comments.

        user_id : typing.Optional[str]
            Filter conversations by the user ID who initiated them.

        evaluation_params : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Evaluation filters. Repeat param. Format: criteria_id:result. Example: eval=value_framing:success

        data_collection_params : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Data collection filters. Repeat param. Format: id:op:value where op is one of eq|neq|gt|gte|lt|lte|in|exists|missing. For in, pipe-delimit values.

        data_collection_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Data collection field IDs to include in each conversation summary. Repeat param. When omitted, data_collection_results is not returned.

        evaluation_criteria_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Evaluation criteria IDs to include in each conversation summary. Repeat param. When omitted, evaluation_criteria_results is not returned.

        tool_names : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names used during the call.

        tool_names_successful : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names that had successful calls.

        tool_names_errored : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names that had errored calls.

        main_languages : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by detected main language (language code).

        page_size : typing.Optional[int]
            How many conversations to return at maximum. Can not exceed 100, defaults to 30.

        summary_mode : typing.Optional[ConversationsListRequestSummaryMode]
            Whether to include transcript summaries in the response.

        search : typing.Optional[str]
            Full-text or fuzzy search over transcript messages

        conversation_initiation_source : typing.Optional[ConversationInitiationSource]

        text_only : typing.Optional[bool]

        conversation_product_type : typing.Optional[ConversationProduct]
            Restrict results to a single conversation product surface.

        branch_id : typing.Optional[str]
            Filter conversations by branch ID.

        version_id : typing.Optional[str]
            Filter conversations by version ID.

        topic_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by topic IDs assigned during topic discovery.

        exclude_statuses : typing.Optional[typing.Union[ConversationsListRequestExcludeStatusesItem, typing.Sequence[ConversationsListRequestExcludeStatusesItem]]]
            Exclude conversations with the given statuses. Useful for hiding in-progress / processing conversations from list views.

        tag_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by conversation tag IDs assigned via the conversation-tags endpoints.

        workflow_node_entered_id : typing.Optional[str]
            Filter conversations to only those that entered the given node.

        termination_reasons : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by their stored termination_reason (metadata.termination_reason). Repeat param to match any of several.

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

        Returns
        -------
        HttpResponse[GetConversationsPageResponseModel]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/conversations",
            method="GET",
            params={
                "cursor": cursor,
                "agent_id": agent_id,
                "visited_agent_ids": visited_agent_ids,
                "visited_agent_branch_ids": visited_agent_branch_ids,
                "call_successful": call_successful,
                "call_start_before_unix": call_start_before_unix,
                "call_start_after_unix": call_start_after_unix,
                "call_duration_min_secs": call_duration_min_secs,
                "call_duration_max_secs": call_duration_max_secs,
                "rating_max": rating_max,
                "rating_min": rating_min,
                "has_feedback_comment": has_feedback_comment,
                "user_id": user_id,
                "evaluation_params": evaluation_params,
                "data_collection_params": data_collection_params,
                "data_collection_ids": data_collection_ids,
                "evaluation_criteria_ids": evaluation_criteria_ids,
                "tool_names": tool_names,
                "tool_names_successful": tool_names_successful,
                "tool_names_errored": tool_names_errored,
                "main_languages": main_languages,
                "page_size": page_size,
                "summary_mode": summary_mode,
                "search": search,
                "conversation_initiation_source": conversation_initiation_source,
                "text_only": text_only,
                "conversation_product_type": conversation_product_type,
                "branch_id": branch_id,
                "version_id": version_id,
                "topic_ids": topic_ids,
                "exclude_statuses": exclude_statuses,
                "tag_ids": tag_ids,
                "workflow_node_entered_id": workflow_node_entered_id,
                "termination_reasons": termination_reasons,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationsPageResponseModel,
                    construct_type(
                        type_=GetConversationsPageResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def resolve(
        self, *, agent_id: str, reference: str, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[GetConversationResponseModel]:
        """
        Resolve a conversation URL (a Slack message URL or a Zendesk ticket URL) to the deterministic conversation ID for the given agent, then confirm the conversation exists.

        Parameters
        ----------
        agent_id : str
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        reference : str
            A Slack message URL or a Zendesk ticket URL.

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

        Returns
        -------
        HttpResponse[GetConversationResponseModel]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            "v1/convai/conversations/resolve",
            method="GET",
            params={
                "agent_id": agent_id,
                "reference": reference,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationResponseModel,
                    construct_type(
                        type_=GetConversationResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get(
        self,
        conversation_id: str,
        *,
        format: typing.Optional[ConversationsGetRequestFormat] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[GetConversationResponseModel]:
        """
        Get the details of a particular conversation

        Parameters
        ----------
        conversation_id : str
            The id of the conversation you're taking the action on.

        format : typing.Optional[ConversationsGetRequestFormat]
            Response format. Defaults to 'json'. Set to 'opentelemetry' for an OTLP-compatible trace payload using the same structure as the post-call webhook.

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

        Returns
        -------
        HttpResponse[GetConversationResponseModel]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/convai/conversations/{jsonable_encoder(conversation_id)}",
            method="GET",
            params={
                "format": format,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationResponseModel,
                    construct_type(
                        type_=GetConversationResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def delete(
        self, conversation_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> HttpResponse[typing.Any]:
        """
        Delete a particular conversation

        Parameters
        ----------
        conversation_id : str
            The id of the conversation you're taking the action on.

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

        Returns
        -------
        HttpResponse[typing.Any]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/convai/conversations/{jsonable_encoder(conversation_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return HttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    construct_type(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    def get_sip_messages(
        self,
        conversation_id: str,
        *,
        page_size: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> HttpResponse[GetSipLogMessagesResponse]:
        """
        Get SIP messages associated with a conversation's phone call

        Parameters
        ----------
        conversation_id : str
            The id of the conversation you're taking the action on.

        page_size : typing.Optional[int]

        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

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

        Returns
        -------
        HttpResponse[GetSipLogMessagesResponse]
            Successful Response
        """
        _response = self._client_wrapper.httpx_client.request(
            f"v1/convai/conversations/{jsonable_encoder(conversation_id)}/sip-messages",
            method="GET",
            params={
                "page_size": page_size,
                "cursor": cursor,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetSipLogMessagesResponse,
                    construct_type(
                        type_=GetSipLogMessagesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return HttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)


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

    async def get_signed_url(
        self,
        *,
        agent_id: str,
        include_conversation_id: typing.Optional[bool] = None,
        branch_id: typing.Optional[str] = None,
        environment: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[ConversationSignedUrlResponseModel]:
        """
        Get a signed url to start a conversation with an agent with an agent that requires authorization

        Parameters
        ----------
        agent_id : str
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        include_conversation_id : typing.Optional[bool]
            Whether to include a conversation_id with the response. If included, the conversation_signature cannot be used again.

        branch_id : typing.Optional[str]
            The ID of the branch to use

        environment : typing.Optional[str]
            The environment to use for resolving environment variables (e.g. 'production', 'staging'). Defaults to 'production'.

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

        Returns
        -------
        AsyncHttpResponse[ConversationSignedUrlResponseModel]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/conversation/get-signed-url",
            method="GET",
            params={
                "agent_id": agent_id,
                "include_conversation_id": include_conversation_id,
                "branch_id": branch_id,
                "environment": environment,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    ConversationSignedUrlResponseModel,
                    construct_type(
                        type_=ConversationSignedUrlResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_webrtc_token(
        self,
        *,
        agent_id: str,
        participant_name: typing.Optional[str] = None,
        branch_id: typing.Optional[str] = None,
        environment: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[TokenResponseModel]:
        """
        Get a WebRTC session token for real-time communication.

        Parameters
        ----------
        agent_id : str
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        participant_name : typing.Optional[str]
            Optional custom participant name. If not provided, user ID will be used

        branch_id : typing.Optional[str]
            The ID of the branch to use

        environment : typing.Optional[str]
            The environment to use for resolving environment variables (e.g. 'production', 'staging'). Defaults to 'production'.

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

        Returns
        -------
        AsyncHttpResponse[TokenResponseModel]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/conversation/token",
            method="GET",
            params={
                "agent_id": agent_id,
                "participant_name": participant_name,
                "branch_id": branch_id,
                "environment": environment,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    TokenResponseModel,
                    construct_type(
                        type_=TokenResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def list(
        self,
        *,
        cursor: typing.Optional[str] = None,
        agent_id: typing.Optional[str] = None,
        visited_agent_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        visited_agent_branch_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        call_successful: typing.Optional[EvaluationSuccessResult] = None,
        call_start_before_unix: typing.Optional[int] = None,
        call_start_after_unix: typing.Optional[int] = None,
        call_duration_min_secs: typing.Optional[int] = None,
        call_duration_max_secs: typing.Optional[int] = None,
        rating_max: typing.Optional[int] = None,
        rating_min: typing.Optional[int] = None,
        has_feedback_comment: typing.Optional[bool] = None,
        user_id: typing.Optional[str] = None,
        evaluation_params: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        data_collection_params: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        data_collection_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        evaluation_criteria_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names_successful: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        tool_names_errored: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        main_languages: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        page_size: typing.Optional[int] = None,
        summary_mode: typing.Optional[ConversationsListRequestSummaryMode] = None,
        search: typing.Optional[str] = None,
        conversation_initiation_source: typing.Optional[ConversationInitiationSource] = None,
        text_only: typing.Optional[bool] = None,
        conversation_product_type: typing.Optional[ConversationProduct] = None,
        branch_id: typing.Optional[str] = None,
        version_id: typing.Optional[str] = None,
        topic_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        exclude_statuses: typing.Optional[
            typing.Union[
                ConversationsListRequestExcludeStatusesItem,
                typing.Sequence[ConversationsListRequestExcludeStatusesItem],
            ]
        ] = None,
        tag_ids: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        workflow_node_entered_id: typing.Optional[str] = None,
        termination_reasons: typing.Optional[typing.Union[str, typing.Sequence[str]]] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[GetConversationsPageResponseModel]:
        """
        Get all conversations of agents that user owns. With option to restrict to a specific agent.

        Parameters
        ----------
        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

        agent_id : typing.Optional[str]
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        visited_agent_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations where any of these agents participated. Can not exceed 50 values.

        visited_agent_branch_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations where any of these agent branches participated. Can not exceed 50 values.

        call_successful : typing.Optional[EvaluationSuccessResult]
            The result of the success evaluation

        call_start_before_unix : typing.Optional[int]
            Unix timestamp (in seconds) to filter conversations up to this start date.

        call_start_after_unix : typing.Optional[int]
            Unix timestamp (in seconds) to filter conversations after to this start date.

        call_duration_min_secs : typing.Optional[int]
            Minimum call duration in seconds.

        call_duration_max_secs : typing.Optional[int]
            Maximum call duration in seconds.

        rating_max : typing.Optional[int]
            Maximum overall rating (1-5).

        rating_min : typing.Optional[int]
            Minimum overall rating (1-5).

        has_feedback_comment : typing.Optional[bool]
            Filter conversations with user feedback comments.

        user_id : typing.Optional[str]
            Filter conversations by the user ID who initiated them.

        evaluation_params : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Evaluation filters. Repeat param. Format: criteria_id:result. Example: eval=value_framing:success

        data_collection_params : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Data collection filters. Repeat param. Format: id:op:value where op is one of eq|neq|gt|gte|lt|lte|in|exists|missing. For in, pipe-delimit values.

        data_collection_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Data collection field IDs to include in each conversation summary. Repeat param. When omitted, data_collection_results is not returned.

        evaluation_criteria_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Evaluation criteria IDs to include in each conversation summary. Repeat param. When omitted, evaluation_criteria_results is not returned.

        tool_names : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names used during the call.

        tool_names_successful : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names that had successful calls.

        tool_names_errored : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by tool names that had errored calls.

        main_languages : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by detected main language (language code).

        page_size : typing.Optional[int]
            How many conversations to return at maximum. Can not exceed 100, defaults to 30.

        summary_mode : typing.Optional[ConversationsListRequestSummaryMode]
            Whether to include transcript summaries in the response.

        search : typing.Optional[str]
            Full-text or fuzzy search over transcript messages

        conversation_initiation_source : typing.Optional[ConversationInitiationSource]

        text_only : typing.Optional[bool]

        conversation_product_type : typing.Optional[ConversationProduct]
            Restrict results to a single conversation product surface.

        branch_id : typing.Optional[str]
            Filter conversations by branch ID.

        version_id : typing.Optional[str]
            Filter conversations by version ID.

        topic_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by topic IDs assigned during topic discovery.

        exclude_statuses : typing.Optional[typing.Union[ConversationsListRequestExcludeStatusesItem, typing.Sequence[ConversationsListRequestExcludeStatusesItem]]]
            Exclude conversations with the given statuses. Useful for hiding in-progress / processing conversations from list views.

        tag_ids : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by conversation tag IDs assigned via the conversation-tags endpoints.

        workflow_node_entered_id : typing.Optional[str]
            Filter conversations to only those that entered the given node.

        termination_reasons : typing.Optional[typing.Union[str, typing.Sequence[str]]]
            Filter conversations by their stored termination_reason (metadata.termination_reason). Repeat param to match any of several.

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

        Returns
        -------
        AsyncHttpResponse[GetConversationsPageResponseModel]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/conversations",
            method="GET",
            params={
                "cursor": cursor,
                "agent_id": agent_id,
                "visited_agent_ids": visited_agent_ids,
                "visited_agent_branch_ids": visited_agent_branch_ids,
                "call_successful": call_successful,
                "call_start_before_unix": call_start_before_unix,
                "call_start_after_unix": call_start_after_unix,
                "call_duration_min_secs": call_duration_min_secs,
                "call_duration_max_secs": call_duration_max_secs,
                "rating_max": rating_max,
                "rating_min": rating_min,
                "has_feedback_comment": has_feedback_comment,
                "user_id": user_id,
                "evaluation_params": evaluation_params,
                "data_collection_params": data_collection_params,
                "data_collection_ids": data_collection_ids,
                "evaluation_criteria_ids": evaluation_criteria_ids,
                "tool_names": tool_names,
                "tool_names_successful": tool_names_successful,
                "tool_names_errored": tool_names_errored,
                "main_languages": main_languages,
                "page_size": page_size,
                "summary_mode": summary_mode,
                "search": search,
                "conversation_initiation_source": conversation_initiation_source,
                "text_only": text_only,
                "conversation_product_type": conversation_product_type,
                "branch_id": branch_id,
                "version_id": version_id,
                "topic_ids": topic_ids,
                "exclude_statuses": exclude_statuses,
                "tag_ids": tag_ids,
                "workflow_node_entered_id": workflow_node_entered_id,
                "termination_reasons": termination_reasons,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationsPageResponseModel,
                    construct_type(
                        type_=GetConversationsPageResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def resolve(
        self, *, agent_id: str, reference: str, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[GetConversationResponseModel]:
        """
        Resolve a conversation URL (a Slack message URL or a Zendesk ticket URL) to the deterministic conversation ID for the given agent, then confirm the conversation exists.

        Parameters
        ----------
        agent_id : str
            Agent id (agent_…) or speech engine external id (seng_), resolved to the same underlying resource.

        reference : str
            A Slack message URL or a Zendesk ticket URL.

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

        Returns
        -------
        AsyncHttpResponse[GetConversationResponseModel]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            "v1/convai/conversations/resolve",
            method="GET",
            params={
                "agent_id": agent_id,
                "reference": reference,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationResponseModel,
                    construct_type(
                        type_=GetConversationResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get(
        self,
        conversation_id: str,
        *,
        format: typing.Optional[ConversationsGetRequestFormat] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[GetConversationResponseModel]:
        """
        Get the details of a particular conversation

        Parameters
        ----------
        conversation_id : str
            The id of the conversation you're taking the action on.

        format : typing.Optional[ConversationsGetRequestFormat]
            Response format. Defaults to 'json'. Set to 'opentelemetry' for an OTLP-compatible trace payload using the same structure as the post-call webhook.

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

        Returns
        -------
        AsyncHttpResponse[GetConversationResponseModel]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/convai/conversations/{jsonable_encoder(conversation_id)}",
            method="GET",
            params={
                "format": format,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetConversationResponseModel,
                    construct_type(
                        type_=GetConversationResponseModel,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def delete(
        self, conversation_id: str, *, request_options: typing.Optional[RequestOptions] = None
    ) -> AsyncHttpResponse[typing.Any]:
        """
        Delete a particular conversation

        Parameters
        ----------
        conversation_id : str
            The id of the conversation you're taking the action on.

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

        Returns
        -------
        AsyncHttpResponse[typing.Any]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/convai/conversations/{jsonable_encoder(conversation_id)}",
            method="DELETE",
            request_options=request_options,
        )
        try:
            if _response is None or not _response.text.strip():
                return AsyncHttpResponse(response=_response, data=None)
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    typing.Any,
                    construct_type(
                        type_=typing.Any,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)

    async def get_sip_messages(
        self,
        conversation_id: str,
        *,
        page_size: typing.Optional[int] = None,
        cursor: typing.Optional[str] = None,
        request_options: typing.Optional[RequestOptions] = None,
    ) -> AsyncHttpResponse[GetSipLogMessagesResponse]:
        """
        Get SIP messages associated with a conversation's phone call

        Parameters
        ----------
        conversation_id : str
            The id of the conversation you're taking the action on.

        page_size : typing.Optional[int]

        cursor : typing.Optional[str]
            Used for fetching next page. Cursor is returned in the response.

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

        Returns
        -------
        AsyncHttpResponse[GetSipLogMessagesResponse]
            Successful Response
        """
        _response = await self._client_wrapper.httpx_client.request(
            f"v1/convai/conversations/{jsonable_encoder(conversation_id)}/sip-messages",
            method="GET",
            params={
                "page_size": page_size,
                "cursor": cursor,
            },
            request_options=request_options,
        )
        try:
            if 200 <= _response.status_code < 300:
                _data = typing.cast(
                    GetSipLogMessagesResponse,
                    construct_type(
                        type_=GetSipLogMessagesResponse,  # type: ignore
                        object_=_response.json(),
                    ),
                )
                return AsyncHttpResponse(response=_response, data=_data)
            if _response.status_code == 422:
                raise UnprocessableEntityError(
                    headers=dict(_response.headers),
                    body=typing.cast(
                        typing.Any,
                        construct_type(
                            type_=typing.Any,  # type: ignore
                            object_=_response.json(),
                        ),
                    ),
                )
            _response_json = _response.json()
        except JSONDecodeError:
            raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response.text)
        except ValidationError as e:
            raise ParsingError(
                status_code=_response.status_code, headers=dict(_response.headers), body=_response.json(), cause=e
            )
        raise ApiError(status_code=_response.status_code, headers=dict(_response.headers), body=_response_json)
