"""Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
# @generated-id: 40692a878064

from .basesdk import BaseSDK
from mistralai.client import errors, models, utils
from mistralai.client._hooks import HookContext
from mistralai.client.types import OptionalNullable, UNSET
from mistralai.client.utils import eventstreaming, get_security_from_env
from mistralai.client.utils.unmarshal_json_response import unmarshal_json_response
from typing import Any, Dict, List, Mapping, Optional, Union

# region imports
import typing
from typing import AsyncGenerator
import logging
from collections import defaultdict

from mistralai.client.models import (
    ResponseStartedEvent,
    ConversationEventsData,
    InputEntries,
)
from mistralai.extra.run.result import (
    RunResult,
    RunResultEvents,
    FunctionResultEvent,
    reconstitue_entries,
)
from mistralai.extra.run.utils import run_requirements
from mistralai.extra.observability.otel import GenAISpanEnum, get_or_create_otel_tracer

logger = logging.getLogger(__name__)
tracing_enabled, tracer = get_or_create_otel_tracer()

if typing.TYPE_CHECKING:
    from mistralai.extra.run.context import RunContext

# endregion imports


class Conversations(BaseSDK):
    r"""(beta) Conversations API"""

    # region sdk-class-body
    # Custom run code allowing client side execution of code

    @run_requirements
    async def run_async(
        self,
        run_ctx: "RunContext",
        inputs: Union[models.ConversationInputs, models.ConversationInputsTypedDict],
        instructions: OptionalNullable[str] = UNSET,
        tools: OptionalNullable[
            Union[
                List[models.ConversationRequestTool],
                List[models.ConversationRequestToolTypedDict],
            ]
        ] = UNSET,
        completion_args: OptionalNullable[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = UNSET,
        name: OptionalNullable[str] = UNSET,
        description: OptionalNullable[str] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> RunResult:
        """Run a conversation with the given inputs and context.

        The execution of a run will only stop when no required local execution can be done."""
        from mistralai.client.beta import Beta  # pylint: disable=import-outside-toplevel
        from mistralai.extra.run.context import _validate_run  # pylint: disable=import-outside-toplevel
        from mistralai.extra.run.tools import get_function_calls  # pylint: disable=import-outside-toplevel

        with tracer.start_as_current_span(GenAISpanEnum.VALIDATE_RUN.value):
            req, run_result, input_entries = await _validate_run(
                beta_client=Beta(self.sdk_configuration),
                run_ctx=run_ctx,
                inputs=inputs,
                instructions=instructions,
                tools=tools,
                completion_args=completion_args,
            )

        with tracer.start_as_current_span(GenAISpanEnum.CONVERSATION.value):
            while True:
                if run_ctx.conversation_id is None:
                    res = await self.start_async(
                        inputs=input_entries,
                        http_headers=http_headers,
                        name=name,
                        description=description,
                        retries=retries,
                        server_url=server_url,
                        timeout_ms=timeout_ms,
                        **req,  # type: ignore
                    )
                    run_result.conversation_id = res.conversation_id
                    run_ctx.conversation_id = res.conversation_id
                    logger.info(  # pylint: disable=logging-fstring-interpolation
                        f"Started Run with conversation with id {res.conversation_id}"
                    )
                else:
                    res = await self.append_async(
                        conversation_id=run_ctx.conversation_id,
                        inputs=input_entries,
                        retries=retries,
                        server_url=server_url,
                        timeout_ms=timeout_ms,
                    )
                run_ctx.request_count += 1
                run_result.output_entries.extend(res.outputs)
                fcalls = get_function_calls(res.outputs)
                if not fcalls:
                    logger.debug("No more function calls to execute")
                    break
                fresults = await run_ctx.execute_function_calls(fcalls)
                run_result.output_entries.extend(fresults)
                input_entries = typing.cast(list[InputEntries], fresults)
        return run_result

    @run_requirements
    async def run_stream_async(
        self,
        run_ctx: "RunContext",
        inputs: Union[models.ConversationInputs, models.ConversationInputsTypedDict],
        instructions: OptionalNullable[str] = UNSET,
        tools: OptionalNullable[
            Union[
                List[models.ConversationRequestTool],
                List[models.ConversationRequestToolTypedDict],
            ]
        ] = UNSET,
        completion_args: OptionalNullable[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = UNSET,
        name: OptionalNullable[str] = UNSET,
        description: OptionalNullable[str] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> AsyncGenerator[Union[RunResultEvents, RunResult], None]:
        """Similar to `run_async` but returns a generator which streams events.

        The last streamed object is the RunResult object which summarises what happened in the run."""
        from mistralai.client.beta import Beta  # pylint: disable=import-outside-toplevel
        from mistralai.extra.run.context import _validate_run  # pylint: disable=import-outside-toplevel
        from mistralai.extra.run.tools import get_function_calls  # pylint: disable=import-outside-toplevel

        req, run_result, input_entries = await _validate_run(
            beta_client=Beta(self.sdk_configuration),
            run_ctx=run_ctx,
            inputs=inputs,
            instructions=instructions,
            tools=tools,
            completion_args=completion_args,
        )

        async def run_generator() -> (
            AsyncGenerator[Union[RunResultEvents, RunResult], None]
        ):
            current_entries = input_entries
            while True:
                received_event_tracker: defaultdict[
                    int, list[ConversationEventsData]
                ] = defaultdict(list)
                if run_ctx.conversation_id is None:
                    res = await self.start_stream_async(
                        inputs=current_entries,
                        http_headers=http_headers,
                        name=name,
                        description=description,
                        retries=retries,
                        server_url=server_url,
                        timeout_ms=timeout_ms,
                        **req,  # type: ignore
                    )
                else:
                    res = await self.append_stream_async(
                        conversation_id=run_ctx.conversation_id,
                        inputs=current_entries,
                        retries=retries,
                        server_url=server_url,
                        timeout_ms=timeout_ms,
                    )
                async for event in res:
                    if (
                        isinstance(event.data, ResponseStartedEvent)
                        and run_ctx.conversation_id is None
                    ):
                        run_result.conversation_id = event.data.conversation_id
                        run_ctx.conversation_id = event.data.conversation_id
                        logger.info(  # pylint: disable=logging-fstring-interpolation
                            f"Started Run with conversation with id {run_ctx.conversation_id}"
                        )
                    if (
                        output_index := getattr(event.data, "output_index", None)
                    ) is not None:
                        received_event_tracker[output_index].append(event.data)
                    yield typing.cast(RunResultEvents, event)
                run_ctx.request_count += 1
                outputs = reconstitue_entries(received_event_tracker)
                run_result.output_entries.extend(outputs)
                fcalls = get_function_calls(outputs)
                if not fcalls:
                    logger.debug("No more function calls to execute")
                    break
                fresults = await run_ctx.execute_function_calls(fcalls)
                run_result.output_entries.extend(fresults)
                for fresult in fresults:
                    yield RunResultEvents(
                        event="function.result",
                        data=FunctionResultEvent(
                            type="function.result",
                            result=fresult.result,
                            tool_call_id=fresult.tool_call_id,
                        ),
                    )
                current_entries = typing.cast(list[InputEntries], fresults)
            yield run_result

        return run_generator()

    # endregion sdk-class-body

    def start(
        self,
        *,
        inputs: Union[models.ConversationInputs, models.ConversationInputsTypedDict],
        store: OptionalNullable[bool] = UNSET,
        handoff_execution: OptionalNullable[
            models.ConversationRequestHandoffExecution
        ] = UNSET,
        instructions: OptionalNullable[str] = UNSET,
        tools: OptionalNullable[
            Union[
                List[models.ConversationRequestTool],
                List[models.ConversationRequestToolTypedDict],
            ]
        ] = UNSET,
        completion_args: OptionalNullable[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = UNSET,
        guardrails: OptionalNullable[
            Union[List[models.GuardrailConfig], List[models.GuardrailConfigTypedDict]]
        ] = UNSET,
        name: OptionalNullable[str] = UNSET,
        description: OptionalNullable[str] = UNSET,
        metadata: OptionalNullable[
            Union[models.MetadataDict, models.MetadataDictTypedDict]
        ] = UNSET,
        agent_id: OptionalNullable[str] = UNSET,
        agent_version: OptionalNullable[
            Union[
                models.ConversationRequestAgentVersion,
                models.ConversationRequestAgentVersionTypedDict,
            ]
        ] = UNSET,
        model: OptionalNullable[str] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationResponse:
        r"""Create a conversation and append entries to it.

        Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation.

        :param inputs:
        :param store:
        :param handoff_execution:
        :param instructions:
        :param tools:
        :param completion_args:
        :param guardrails:
        :param name:
        :param description:
        :param metadata:
        :param agent_id:
        :param agent_version:
        :param model:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.ConversationRequest(
            inputs=utils.get_pydantic_model(inputs, models.ConversationInputs),
            store=store,
            handoff_execution=handoff_execution,
            instructions=instructions,
            tools=utils.get_pydantic_model(
                tools, OptionalNullable[List[models.ConversationRequestTool]]
            ),
            completion_args=utils.get_pydantic_model(
                completion_args, OptionalNullable[models.CompletionArgs]
            ),
            guardrails=utils.get_pydantic_model(
                guardrails, OptionalNullable[List[models.GuardrailConfig]]
            ),
            name=name,
            description=description,
            metadata=utils.get_pydantic_model(
                metadata, OptionalNullable[models.MetadataDict]
            ),
            agent_id=agent_id,
            agent_version=agent_version,
            model=model,
        )

        req = self._build_request(
            method="POST",
            path="/v1/conversations",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.ConversationRequest
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_start",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    async def start_async(
        self,
        *,
        inputs: Union[models.ConversationInputs, models.ConversationInputsTypedDict],
        store: OptionalNullable[bool] = UNSET,
        handoff_execution: OptionalNullable[
            models.ConversationRequestHandoffExecution
        ] = UNSET,
        instructions: OptionalNullable[str] = UNSET,
        tools: OptionalNullable[
            Union[
                List[models.ConversationRequestTool],
                List[models.ConversationRequestToolTypedDict],
            ]
        ] = UNSET,
        completion_args: OptionalNullable[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = UNSET,
        guardrails: OptionalNullable[
            Union[List[models.GuardrailConfig], List[models.GuardrailConfigTypedDict]]
        ] = UNSET,
        name: OptionalNullable[str] = UNSET,
        description: OptionalNullable[str] = UNSET,
        metadata: OptionalNullable[
            Union[models.MetadataDict, models.MetadataDictTypedDict]
        ] = UNSET,
        agent_id: OptionalNullable[str] = UNSET,
        agent_version: OptionalNullable[
            Union[
                models.ConversationRequestAgentVersion,
                models.ConversationRequestAgentVersionTypedDict,
            ]
        ] = UNSET,
        model: OptionalNullable[str] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationResponse:
        r"""Create a conversation and append entries to it.

        Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation.

        :param inputs:
        :param store:
        :param handoff_execution:
        :param instructions:
        :param tools:
        :param completion_args:
        :param guardrails:
        :param name:
        :param description:
        :param metadata:
        :param agent_id:
        :param agent_version:
        :param model:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.ConversationRequest(
            inputs=utils.get_pydantic_model(inputs, models.ConversationInputs),
            store=store,
            handoff_execution=handoff_execution,
            instructions=instructions,
            tools=utils.get_pydantic_model(
                tools, OptionalNullable[List[models.ConversationRequestTool]]
            ),
            completion_args=utils.get_pydantic_model(
                completion_args, OptionalNullable[models.CompletionArgs]
            ),
            guardrails=utils.get_pydantic_model(
                guardrails, OptionalNullable[List[models.GuardrailConfig]]
            ),
            name=name,
            description=description,
            metadata=utils.get_pydantic_model(
                metadata, OptionalNullable[models.MetadataDict]
            ),
            agent_id=agent_id,
            agent_version=agent_version,
            model=model,
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/conversations",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.ConversationRequest
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_start",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    def list(
        self,
        *,
        page: Optional[int] = 0,
        page_size: Optional[int] = 100,
        metadata: OptionalNullable[Dict[str, Any]] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> List[models.AgentsAPIV1ConversationsListResponse]:
        r"""List all created conversations.

        Retrieve a list of conversation entities sorted by creation time.

        :param page:
        :param page_size:
        :param metadata:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsListRequest(
            page=page,
            page_size=page_size,
            metadata=metadata,
        )

        req = self._build_request(
            method="GET",
            path="/v1/conversations",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_list",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                List[models.AgentsAPIV1ConversationsListResponse], http_res
            )
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    async def list_async(
        self,
        *,
        page: Optional[int] = 0,
        page_size: Optional[int] = 100,
        metadata: OptionalNullable[Dict[str, Any]] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> List[models.AgentsAPIV1ConversationsListResponse]:
        r"""List all created conversations.

        Retrieve a list of conversation entities sorted by creation time.

        :param page:
        :param page_size:
        :param metadata:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsListRequest(
            page=page,
            page_size=page_size,
            metadata=metadata,
        )

        req = self._build_request_async(
            method="GET",
            path="/v1/conversations",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_list",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(
                List[models.AgentsAPIV1ConversationsListResponse], http_res
            )
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    def get(
        self,
        *,
        conversation_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ResponseV1ConversationsGet:
        r"""Retrieve a conversation information.

        Given a conversation_id retrieve a conversation entity with its attributes.

        :param conversation_id: ID of the conversation from which we are fetching metadata.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsGetRequest(
            conversation_id=conversation_id,
        )

        req = self._build_request(
            method="GET",
            path="/v1/conversations/{conversation_id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_get",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ResponseV1ConversationsGet, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    async def get_async(
        self,
        *,
        conversation_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ResponseV1ConversationsGet:
        r"""Retrieve a conversation information.

        Given a conversation_id retrieve a conversation entity with its attributes.

        :param conversation_id: ID of the conversation from which we are fetching metadata.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsGetRequest(
            conversation_id=conversation_id,
        )

        req = self._build_request_async(
            method="GET",
            path="/v1/conversations/{conversation_id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_get",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ResponseV1ConversationsGet, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    def delete(
        self,
        *,
        conversation_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ):
        r"""Delete a conversation.

        Delete a conversation given a conversation_id.

        :param conversation_id: ID of the conversation from which we are fetching metadata.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsDeleteRequest(
            conversation_id=conversation_id,
        )

        req = self._build_request(
            method="DELETE",
            path="/v1/conversations/{conversation_id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_delete",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "204", "*"):
            return
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    async def delete_async(
        self,
        *,
        conversation_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ):
        r"""Delete a conversation.

        Delete a conversation given a conversation_id.

        :param conversation_id: ID of the conversation from which we are fetching metadata.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsDeleteRequest(
            conversation_id=conversation_id,
        )

        req = self._build_request_async(
            method="DELETE",
            path="/v1/conversations/{conversation_id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_delete",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "204", "*"):
            return
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    def append(
        self,
        *,
        conversation_id: str,
        inputs: Optional[
            Union[models.ConversationInputs, models.ConversationInputsTypedDict]
        ] = None,
        store: Optional[bool] = True,
        handoff_execution: Optional[
            models.ConversationAppendRequestHandoffExecution
        ] = "server",
        completion_args: Optional[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = None,
        tool_confirmations: OptionalNullable[
            Union[
                List[models.ToolCallConfirmation],
                List[models.ToolCallConfirmationTypedDict],
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationResponse:
        r"""Append new entries to an existing conversation.

        Run completion on the history of the conversation and the user entries. Return the new created entries.

        :param conversation_id: ID of the conversation to which we append entries.
        :param inputs:
        :param store: Whether to store the results into our servers or not.
        :param handoff_execution:
        :param completion_args: White-listed arguments from the completion API
        :param tool_confirmations:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsAppendRequest(
            conversation_id=conversation_id,
            conversation_append_request=models.ConversationAppendRequest(
                inputs=utils.get_pydantic_model(
                    inputs, Optional[models.ConversationInputs]
                ),
                store=store,
                handoff_execution=handoff_execution,
                completion_args=utils.get_pydantic_model(
                    completion_args, Optional[models.CompletionArgs]
                ),
                tool_confirmations=utils.get_pydantic_model(
                    tool_confirmations,
                    OptionalNullable[List[models.ToolCallConfirmation]],
                ),
            ),
        )

        req = self._build_request(
            method="POST",
            path="/v1/conversations/{conversation_id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.conversation_append_request,
                False,
                False,
                "json",
                models.ConversationAppendRequest,
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_append",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    async def append_async(
        self,
        *,
        conversation_id: str,
        inputs: Optional[
            Union[models.ConversationInputs, models.ConversationInputsTypedDict]
        ] = None,
        store: Optional[bool] = True,
        handoff_execution: Optional[
            models.ConversationAppendRequestHandoffExecution
        ] = "server",
        completion_args: Optional[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = None,
        tool_confirmations: OptionalNullable[
            Union[
                List[models.ToolCallConfirmation],
                List[models.ToolCallConfirmationTypedDict],
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationResponse:
        r"""Append new entries to an existing conversation.

        Run completion on the history of the conversation and the user entries. Return the new created entries.

        :param conversation_id: ID of the conversation to which we append entries.
        :param inputs:
        :param store: Whether to store the results into our servers or not.
        :param handoff_execution:
        :param completion_args: White-listed arguments from the completion API
        :param tool_confirmations:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsAppendRequest(
            conversation_id=conversation_id,
            conversation_append_request=models.ConversationAppendRequest(
                inputs=utils.get_pydantic_model(
                    inputs, Optional[models.ConversationInputs]
                ),
                store=store,
                handoff_execution=handoff_execution,
                completion_args=utils.get_pydantic_model(
                    completion_args, Optional[models.CompletionArgs]
                ),
                tool_confirmations=utils.get_pydantic_model(
                    tool_confirmations,
                    OptionalNullable[List[models.ToolCallConfirmation]],
                ),
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/conversations/{conversation_id}",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.conversation_append_request,
                False,
                False,
                "json",
                models.ConversationAppendRequest,
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_append",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    def get_history(
        self,
        *,
        conversation_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationHistory:
        r"""Retrieve all entries in a conversation.

        Given a conversation_id retrieve all the entries belonging to that conversation. The entries are sorted in the order they were appended, those can be messages, connectors or function_call.

        :param conversation_id: ID of the conversation from which we are fetching entries.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsHistoryRequest(
            conversation_id=conversation_id,
        )

        req = self._build_request(
            method="GET",
            path="/v1/conversations/{conversation_id}/history",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_history",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationHistory, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    async def get_history_async(
        self,
        *,
        conversation_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationHistory:
        r"""Retrieve all entries in a conversation.

        Given a conversation_id retrieve all the entries belonging to that conversation. The entries are sorted in the order they were appended, those can be messages, connectors or function_call.

        :param conversation_id: ID of the conversation from which we are fetching entries.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsHistoryRequest(
            conversation_id=conversation_id,
        )

        req = self._build_request_async(
            method="GET",
            path="/v1/conversations/{conversation_id}/history",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_history",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationHistory, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    def get_messages(
        self,
        *,
        conversation_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationMessages:
        r"""Retrieve all messages in a conversation.

        Given a conversation_id retrieve all the messages belonging to that conversation. This is similar to retrieving all entries except we filter the messages only.

        :param conversation_id: ID of the conversation from which we are fetching messages.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsMessagesRequest(
            conversation_id=conversation_id,
        )

        req = self._build_request(
            method="GET",
            path="/v1/conversations/{conversation_id}/messages",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_messages",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationMessages, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    async def get_messages_async(
        self,
        *,
        conversation_id: str,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationMessages:
        r"""Retrieve all messages in a conversation.

        Given a conversation_id retrieve all the messages belonging to that conversation. This is similar to retrieving all entries except we filter the messages only.

        :param conversation_id: ID of the conversation from which we are fetching messages.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsMessagesRequest(
            conversation_id=conversation_id,
        )

        req = self._build_request_async(
            method="GET",
            path="/v1/conversations/{conversation_id}/messages",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=False,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_messages",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationMessages, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    def restart(
        self,
        *,
        conversation_id: str,
        from_entry_id: str,
        inputs: Optional[
            Union[models.ConversationInputs, models.ConversationInputsTypedDict]
        ] = None,
        store: Optional[bool] = True,
        handoff_execution: Optional[
            models.ConversationRestartRequestHandoffExecution
        ] = "server",
        completion_args: Optional[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = None,
        guardrails: OptionalNullable[
            Union[List[models.GuardrailConfig], List[models.GuardrailConfigTypedDict]]
        ] = UNSET,
        metadata: OptionalNullable[
            Union[models.MetadataDict, models.MetadataDictTypedDict]
        ] = UNSET,
        agent_version: OptionalNullable[
            Union[
                models.ConversationRestartRequestAgentVersion,
                models.ConversationRestartRequestAgentVersionTypedDict,
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationResponse:
        r"""Restart a conversation starting from a given entry.

        Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned.

        :param conversation_id: ID of the original conversation which is being restarted.
        :param from_entry_id:
        :param inputs:
        :param store: Whether to store the results into our servers or not.
        :param handoff_execution:
        :param completion_args: White-listed arguments from the completion API
        :param guardrails:
        :param metadata: Custom metadata for the conversation.
        :param agent_version: Specific version of the agent to use when restarting. If not provided, uses the current version.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsRestartRequest(
            conversation_id=conversation_id,
            conversation_restart_request=models.ConversationRestartRequest(
                inputs=utils.get_pydantic_model(
                    inputs, Optional[models.ConversationInputs]
                ),
                store=store,
                handoff_execution=handoff_execution,
                completion_args=utils.get_pydantic_model(
                    completion_args, Optional[models.CompletionArgs]
                ),
                guardrails=utils.get_pydantic_model(
                    guardrails, OptionalNullable[List[models.GuardrailConfig]]
                ),
                metadata=utils.get_pydantic_model(
                    metadata, OptionalNullable[models.MetadataDict]
                ),
                from_entry_id=from_entry_id,
                agent_version=agent_version,
            ),
        )

        req = self._build_request(
            method="POST",
            path="/v1/conversations/{conversation_id}/restart",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.conversation_restart_request,
                False,
                False,
                "json",
                models.ConversationRestartRequest,
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_restart",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    async def restart_async(
        self,
        *,
        conversation_id: str,
        from_entry_id: str,
        inputs: Optional[
            Union[models.ConversationInputs, models.ConversationInputsTypedDict]
        ] = None,
        store: Optional[bool] = True,
        handoff_execution: Optional[
            models.ConversationRestartRequestHandoffExecution
        ] = "server",
        completion_args: Optional[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = None,
        guardrails: OptionalNullable[
            Union[List[models.GuardrailConfig], List[models.GuardrailConfigTypedDict]]
        ] = UNSET,
        metadata: OptionalNullable[
            Union[models.MetadataDict, models.MetadataDictTypedDict]
        ] = UNSET,
        agent_version: OptionalNullable[
            Union[
                models.ConversationRestartRequestAgentVersion,
                models.ConversationRestartRequestAgentVersionTypedDict,
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> models.ConversationResponse:
        r"""Restart a conversation starting from a given entry.

        Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned.

        :param conversation_id: ID of the original conversation which is being restarted.
        :param from_entry_id:
        :param inputs:
        :param store: Whether to store the results into our servers or not.
        :param handoff_execution:
        :param completion_args: White-listed arguments from the completion API
        :param guardrails:
        :param metadata: Custom metadata for the conversation.
        :param agent_version: Specific version of the agent to use when restarting. If not provided, uses the current version.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsRestartRequest(
            conversation_id=conversation_id,
            conversation_restart_request=models.ConversationRestartRequest(
                inputs=utils.get_pydantic_model(
                    inputs, Optional[models.ConversationInputs]
                ),
                store=store,
                handoff_execution=handoff_execution,
                completion_args=utils.get_pydantic_model(
                    completion_args, Optional[models.CompletionArgs]
                ),
                guardrails=utils.get_pydantic_model(
                    guardrails, OptionalNullable[List[models.GuardrailConfig]]
                ),
                metadata=utils.get_pydantic_model(
                    metadata, OptionalNullable[models.MetadataDict]
                ),
                from_entry_id=from_entry_id,
                agent_version=agent_version,
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/conversations/{conversation_id}/restart",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="application/json",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.conversation_restart_request,
                False,
                False,
                "json",
                models.ConversationRestartRequest,
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_restart",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "application/json"):
            return unmarshal_json_response(models.ConversationResponse, http_res)
        if utils.match_response(http_res, "422", "application/json"):
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res
            )
            raise errors.HTTPValidationError(response_data, http_res)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        raise errors.SDKError("Unexpected response received", http_res)

    def start_stream(
        self,
        *,
        inputs: Union[models.ConversationInputs, models.ConversationInputsTypedDict],
        store: OptionalNullable[bool] = UNSET,
        handoff_execution: OptionalNullable[
            models.ConversationStreamRequestHandoffExecution
        ] = UNSET,
        instructions: OptionalNullable[str] = UNSET,
        tools: OptionalNullable[
            Union[
                List[models.ConversationStreamRequestTool],
                List[models.ConversationStreamRequestToolTypedDict],
            ]
        ] = UNSET,
        completion_args: OptionalNullable[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = UNSET,
        guardrails: OptionalNullable[
            Union[List[models.GuardrailConfig], List[models.GuardrailConfigTypedDict]]
        ] = UNSET,
        name: OptionalNullable[str] = UNSET,
        description: OptionalNullable[str] = UNSET,
        metadata: OptionalNullable[
            Union[models.MetadataDict, models.MetadataDictTypedDict]
        ] = UNSET,
        agent_id: OptionalNullable[str] = UNSET,
        agent_version: OptionalNullable[
            Union[
                models.ConversationStreamRequestAgentVersion,
                models.ConversationStreamRequestAgentVersionTypedDict,
            ]
        ] = UNSET,
        model: OptionalNullable[str] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> eventstreaming.EventStream[models.ConversationEvents]:
        r"""Create a conversation and append entries to it.

        Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation.

        :param inputs:
        :param store:
        :param handoff_execution:
        :param instructions:
        :param tools:
        :param completion_args:
        :param guardrails:
        :param name:
        :param description:
        :param metadata:
        :param agent_id:
        :param agent_version:
        :param model:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.ConversationStreamRequest(
            inputs=utils.get_pydantic_model(inputs, models.ConversationInputs),
            store=store,
            handoff_execution=handoff_execution,
            instructions=instructions,
            tools=utils.get_pydantic_model(
                tools, OptionalNullable[List[models.ConversationStreamRequestTool]]
            ),
            completion_args=utils.get_pydantic_model(
                completion_args, OptionalNullable[models.CompletionArgs]
            ),
            guardrails=utils.get_pydantic_model(
                guardrails, OptionalNullable[List[models.GuardrailConfig]]
            ),
            name=name,
            description=description,
            metadata=utils.get_pydantic_model(
                metadata, OptionalNullable[models.MetadataDict]
            ),
            agent_id=agent_id,
            agent_version=agent_version,
            model=model,
        )

        req = self._build_request(
            method="POST",
            path="/v1/conversations#stream",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="text/event-stream",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.ConversationStreamRequest
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_start_stream",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            stream=True,
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "text/event-stream"):
            return eventstreaming.EventStream(
                http_res,
                lambda raw: utils.unmarshal_json(raw, models.ConversationEvents),
                client_ref=self,
            )
        if utils.match_response(http_res, "422", "application/json"):
            http_res_text = utils.stream_to_text(http_res)
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res, http_res_text
            )
            raise errors.HTTPValidationError(response_data, http_res, http_res_text)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        http_res_text = utils.stream_to_text(http_res)
        raise errors.SDKError("Unexpected response received", http_res, http_res_text)

    async def start_stream_async(
        self,
        *,
        inputs: Union[models.ConversationInputs, models.ConversationInputsTypedDict],
        store: OptionalNullable[bool] = UNSET,
        handoff_execution: OptionalNullable[
            models.ConversationStreamRequestHandoffExecution
        ] = UNSET,
        instructions: OptionalNullable[str] = UNSET,
        tools: OptionalNullable[
            Union[
                List[models.ConversationStreamRequestTool],
                List[models.ConversationStreamRequestToolTypedDict],
            ]
        ] = UNSET,
        completion_args: OptionalNullable[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = UNSET,
        guardrails: OptionalNullable[
            Union[List[models.GuardrailConfig], List[models.GuardrailConfigTypedDict]]
        ] = UNSET,
        name: OptionalNullable[str] = UNSET,
        description: OptionalNullable[str] = UNSET,
        metadata: OptionalNullable[
            Union[models.MetadataDict, models.MetadataDictTypedDict]
        ] = UNSET,
        agent_id: OptionalNullable[str] = UNSET,
        agent_version: OptionalNullable[
            Union[
                models.ConversationStreamRequestAgentVersion,
                models.ConversationStreamRequestAgentVersionTypedDict,
            ]
        ] = UNSET,
        model: OptionalNullable[str] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> eventstreaming.EventStreamAsync[models.ConversationEvents]:
        r"""Create a conversation and append entries to it.

        Create a new conversation, using a base model or an agent and append entries. Completion and tool executions are run and the response is appended to the conversation.Use the returned conversation_id to continue the conversation.

        :param inputs:
        :param store:
        :param handoff_execution:
        :param instructions:
        :param tools:
        :param completion_args:
        :param guardrails:
        :param name:
        :param description:
        :param metadata:
        :param agent_id:
        :param agent_version:
        :param model:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.ConversationStreamRequest(
            inputs=utils.get_pydantic_model(inputs, models.ConversationInputs),
            store=store,
            handoff_execution=handoff_execution,
            instructions=instructions,
            tools=utils.get_pydantic_model(
                tools, OptionalNullable[List[models.ConversationStreamRequestTool]]
            ),
            completion_args=utils.get_pydantic_model(
                completion_args, OptionalNullable[models.CompletionArgs]
            ),
            guardrails=utils.get_pydantic_model(
                guardrails, OptionalNullable[List[models.GuardrailConfig]]
            ),
            name=name,
            description=description,
            metadata=utils.get_pydantic_model(
                metadata, OptionalNullable[models.MetadataDict]
            ),
            agent_id=agent_id,
            agent_version=agent_version,
            model=model,
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/conversations#stream",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=False,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="text/event-stream",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request, False, False, "json", models.ConversationStreamRequest
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_start_stream",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            stream=True,
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "text/event-stream"):
            return eventstreaming.EventStreamAsync(
                http_res,
                lambda raw: utils.unmarshal_json(raw, models.ConversationEvents),
                client_ref=self,
            )
        if utils.match_response(http_res, "422", "application/json"):
            http_res_text = await utils.stream_to_text_async(http_res)
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res, http_res_text
            )
            raise errors.HTTPValidationError(response_data, http_res, http_res_text)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        http_res_text = await utils.stream_to_text_async(http_res)
        raise errors.SDKError("Unexpected response received", http_res, http_res_text)

    def append_stream(
        self,
        *,
        conversation_id: str,
        inputs: Optional[
            Union[models.ConversationInputs, models.ConversationInputsTypedDict]
        ] = None,
        store: Optional[bool] = True,
        handoff_execution: Optional[
            models.ConversationAppendStreamRequestHandoffExecution
        ] = "server",
        completion_args: Optional[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = None,
        tool_confirmations: OptionalNullable[
            Union[
                List[models.ToolCallConfirmation],
                List[models.ToolCallConfirmationTypedDict],
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> eventstreaming.EventStream[models.ConversationEvents]:
        r"""Append new entries to an existing conversation.

        Run completion on the history of the conversation and the user entries. Return the new created entries.

        :param conversation_id: ID of the conversation to which we append entries.
        :param inputs:
        :param store: Whether to store the results into our servers or not.
        :param handoff_execution:
        :param completion_args: White-listed arguments from the completion API
        :param tool_confirmations:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsAppendStreamRequest(
            conversation_id=conversation_id,
            conversation_append_stream_request=models.ConversationAppendStreamRequest(
                inputs=utils.get_pydantic_model(
                    inputs, Optional[models.ConversationInputs]
                ),
                store=store,
                handoff_execution=handoff_execution,
                completion_args=utils.get_pydantic_model(
                    completion_args, Optional[models.CompletionArgs]
                ),
                tool_confirmations=utils.get_pydantic_model(
                    tool_confirmations,
                    OptionalNullable[List[models.ToolCallConfirmation]],
                ),
            ),
        )

        req = self._build_request(
            method="POST",
            path="/v1/conversations/{conversation_id}#stream",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="text/event-stream",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.conversation_append_stream_request,
                False,
                False,
                "json",
                models.ConversationAppendStreamRequest,
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_append_stream",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            stream=True,
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "text/event-stream"):
            return eventstreaming.EventStream(
                http_res,
                lambda raw: utils.unmarshal_json(raw, models.ConversationEvents),
                client_ref=self,
            )
        if utils.match_response(http_res, "422", "application/json"):
            http_res_text = utils.stream_to_text(http_res)
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res, http_res_text
            )
            raise errors.HTTPValidationError(response_data, http_res, http_res_text)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        http_res_text = utils.stream_to_text(http_res)
        raise errors.SDKError("Unexpected response received", http_res, http_res_text)

    async def append_stream_async(
        self,
        *,
        conversation_id: str,
        inputs: Optional[
            Union[models.ConversationInputs, models.ConversationInputsTypedDict]
        ] = None,
        store: Optional[bool] = True,
        handoff_execution: Optional[
            models.ConversationAppendStreamRequestHandoffExecution
        ] = "server",
        completion_args: Optional[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = None,
        tool_confirmations: OptionalNullable[
            Union[
                List[models.ToolCallConfirmation],
                List[models.ToolCallConfirmationTypedDict],
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> eventstreaming.EventStreamAsync[models.ConversationEvents]:
        r"""Append new entries to an existing conversation.

        Run completion on the history of the conversation and the user entries. Return the new created entries.

        :param conversation_id: ID of the conversation to which we append entries.
        :param inputs:
        :param store: Whether to store the results into our servers or not.
        :param handoff_execution:
        :param completion_args: White-listed arguments from the completion API
        :param tool_confirmations:
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsAppendStreamRequest(
            conversation_id=conversation_id,
            conversation_append_stream_request=models.ConversationAppendStreamRequest(
                inputs=utils.get_pydantic_model(
                    inputs, Optional[models.ConversationInputs]
                ),
                store=store,
                handoff_execution=handoff_execution,
                completion_args=utils.get_pydantic_model(
                    completion_args, Optional[models.CompletionArgs]
                ),
                tool_confirmations=utils.get_pydantic_model(
                    tool_confirmations,
                    OptionalNullable[List[models.ToolCallConfirmation]],
                ),
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/conversations/{conversation_id}#stream",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="text/event-stream",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.conversation_append_stream_request,
                False,
                False,
                "json",
                models.ConversationAppendStreamRequest,
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_append_stream",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            stream=True,
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "text/event-stream"):
            return eventstreaming.EventStreamAsync(
                http_res,
                lambda raw: utils.unmarshal_json(raw, models.ConversationEvents),
                client_ref=self,
            )
        if utils.match_response(http_res, "422", "application/json"):
            http_res_text = await utils.stream_to_text_async(http_res)
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res, http_res_text
            )
            raise errors.HTTPValidationError(response_data, http_res, http_res_text)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        http_res_text = await utils.stream_to_text_async(http_res)
        raise errors.SDKError("Unexpected response received", http_res, http_res_text)

    def restart_stream(
        self,
        *,
        conversation_id: str,
        from_entry_id: str,
        inputs: Optional[
            Union[models.ConversationInputs, models.ConversationInputsTypedDict]
        ] = None,
        store: Optional[bool] = True,
        handoff_execution: Optional[
            models.ConversationRestartStreamRequestHandoffExecution
        ] = "server",
        completion_args: Optional[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = None,
        guardrails: OptionalNullable[
            Union[List[models.GuardrailConfig], List[models.GuardrailConfigTypedDict]]
        ] = UNSET,
        metadata: OptionalNullable[
            Union[models.MetadataDict, models.MetadataDictTypedDict]
        ] = UNSET,
        agent_version: OptionalNullable[
            Union[
                models.ConversationRestartStreamRequestAgentVersion,
                models.ConversationRestartStreamRequestAgentVersionTypedDict,
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> eventstreaming.EventStream[models.ConversationEvents]:
        r"""Restart a conversation starting from a given entry.

        Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned.

        :param conversation_id: ID of the original conversation which is being restarted.
        :param from_entry_id:
        :param inputs:
        :param store: Whether to store the results into our servers or not.
        :param handoff_execution:
        :param completion_args: White-listed arguments from the completion API
        :param guardrails:
        :param metadata: Custom metadata for the conversation.
        :param agent_version: Specific version of the agent to use when restarting. If not provided, uses the current version.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsRestartStreamRequest(
            conversation_id=conversation_id,
            conversation_restart_stream_request=models.ConversationRestartStreamRequest(
                inputs=utils.get_pydantic_model(
                    inputs, Optional[models.ConversationInputs]
                ),
                store=store,
                handoff_execution=handoff_execution,
                completion_args=utils.get_pydantic_model(
                    completion_args, Optional[models.CompletionArgs]
                ),
                guardrails=utils.get_pydantic_model(
                    guardrails, OptionalNullable[List[models.GuardrailConfig]]
                ),
                metadata=utils.get_pydantic_model(
                    metadata, OptionalNullable[models.MetadataDict]
                ),
                from_entry_id=from_entry_id,
                agent_version=agent_version,
            ),
        )

        req = self._build_request(
            method="POST",
            path="/v1/conversations/{conversation_id}/restart#stream",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="text/event-stream",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.conversation_restart_stream_request,
                False,
                False,
                "json",
                models.ConversationRestartStreamRequest,
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = self.do_request(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_restart_stream",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            stream=True,
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "text/event-stream"):
            return eventstreaming.EventStream(
                http_res,
                lambda raw: utils.unmarshal_json(raw, models.ConversationEvents),
                client_ref=self,
            )
        if utils.match_response(http_res, "422", "application/json"):
            http_res_text = utils.stream_to_text(http_res)
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res, http_res_text
            )
            raise errors.HTTPValidationError(response_data, http_res, http_res_text)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = utils.stream_to_text(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        http_res_text = utils.stream_to_text(http_res)
        raise errors.SDKError("Unexpected response received", http_res, http_res_text)

    async def restart_stream_async(
        self,
        *,
        conversation_id: str,
        from_entry_id: str,
        inputs: Optional[
            Union[models.ConversationInputs, models.ConversationInputsTypedDict]
        ] = None,
        store: Optional[bool] = True,
        handoff_execution: Optional[
            models.ConversationRestartStreamRequestHandoffExecution
        ] = "server",
        completion_args: Optional[
            Union[models.CompletionArgs, models.CompletionArgsTypedDict]
        ] = None,
        guardrails: OptionalNullable[
            Union[List[models.GuardrailConfig], List[models.GuardrailConfigTypedDict]]
        ] = UNSET,
        metadata: OptionalNullable[
            Union[models.MetadataDict, models.MetadataDictTypedDict]
        ] = UNSET,
        agent_version: OptionalNullable[
            Union[
                models.ConversationRestartStreamRequestAgentVersion,
                models.ConversationRestartStreamRequestAgentVersionTypedDict,
            ]
        ] = UNSET,
        retries: OptionalNullable[utils.RetryConfig] = UNSET,
        server_url: Optional[str] = None,
        timeout_ms: Optional[int] = None,
        http_headers: Optional[Mapping[str, str]] = None,
    ) -> eventstreaming.EventStreamAsync[models.ConversationEvents]:
        r"""Restart a conversation starting from a given entry.

        Given a conversation_id and an id, recreate a conversation from this point and run completion. A new conversation is returned with the new entries returned.

        :param conversation_id: ID of the original conversation which is being restarted.
        :param from_entry_id:
        :param inputs:
        :param store: Whether to store the results into our servers or not.
        :param handoff_execution:
        :param completion_args: White-listed arguments from the completion API
        :param guardrails:
        :param metadata: Custom metadata for the conversation.
        :param agent_version: Specific version of the agent to use when restarting. If not provided, uses the current version.
        :param retries: Override the default retry configuration for this method
        :param server_url: Override the default server URL for this method
        :param timeout_ms: Override the default request timeout configuration for this method in milliseconds
        :param http_headers: Additional headers to set or replace on requests.
        """
        base_url = None
        url_variables = None
        if timeout_ms is None:
            timeout_ms = self.sdk_configuration.timeout_ms

        if server_url is not None:
            base_url = server_url
        else:
            base_url = self._get_url(base_url, url_variables)

        request = models.AgentsAPIV1ConversationsRestartStreamRequest(
            conversation_id=conversation_id,
            conversation_restart_stream_request=models.ConversationRestartStreamRequest(
                inputs=utils.get_pydantic_model(
                    inputs, Optional[models.ConversationInputs]
                ),
                store=store,
                handoff_execution=handoff_execution,
                completion_args=utils.get_pydantic_model(
                    completion_args, Optional[models.CompletionArgs]
                ),
                guardrails=utils.get_pydantic_model(
                    guardrails, OptionalNullable[List[models.GuardrailConfig]]
                ),
                metadata=utils.get_pydantic_model(
                    metadata, OptionalNullable[models.MetadataDict]
                ),
                from_entry_id=from_entry_id,
                agent_version=agent_version,
            ),
        )

        req = self._build_request_async(
            method="POST",
            path="/v1/conversations/{conversation_id}/restart#stream",
            base_url=base_url,
            url_variables=url_variables,
            request=request,
            request_body_required=True,
            request_has_path_params=True,
            request_has_query_params=True,
            user_agent_header="user-agent",
            accept_header_value="text/event-stream",
            http_headers=http_headers,
            security=self.sdk_configuration.security,
            get_serialized_body=lambda: utils.serialize_request_body(
                request.conversation_restart_stream_request,
                False,
                False,
                "json",
                models.ConversationRestartStreamRequest,
            ),
            allow_empty_value=None,
            timeout_ms=timeout_ms,
        )

        if retries == UNSET:
            if self.sdk_configuration.retry_config is not UNSET:
                retries = self.sdk_configuration.retry_config

        retry_config = None
        if isinstance(retries, utils.RetryConfig):
            retry_config = (retries, ["429", "500", "502", "503", "504"])

        http_res = await self.do_request_async(
            hook_ctx=HookContext(
                config=self.sdk_configuration,
                base_url=base_url or "",
                operation_id="agents_api_v1_conversations_restart_stream",
                oauth2_scopes=None,
                security_source=get_security_from_env(
                    self.sdk_configuration.security, models.Security
                ),
            ),
            request=req,
            error_status_codes=["422", "4XX", "5XX"],
            stream=True,
            retry_config=retry_config,
        )

        response_data: Any = None
        if utils.match_response(http_res, "200", "text/event-stream"):
            return eventstreaming.EventStreamAsync(
                http_res,
                lambda raw: utils.unmarshal_json(raw, models.ConversationEvents),
                client_ref=self,
            )
        if utils.match_response(http_res, "422", "application/json"):
            http_res_text = await utils.stream_to_text_async(http_res)
            response_data = unmarshal_json_response(
                errors.HTTPValidationErrorData, http_res, http_res_text
            )
            raise errors.HTTPValidationError(response_data, http_res, http_res_text)
        if utils.match_response(http_res, "4XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)
        if utils.match_response(http_res, "5XX", "*"):
            http_res_text = await utils.stream_to_text_async(http_res)
            raise errors.SDKError("API error occurred", http_res, http_res_text)

        http_res_text = await utils.stream_to_text_async(http_res)
        raise errors.SDKError("Unexpected response received", http_res, http_res_text)
