# File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. from __future__ import annotations from typing import Dict, List, Union, Iterable, Optional from typing_extensions import Literal import httpx from .tags import ( TagsResource, AsyncTagsResource, TagsResourceWithRawResponse, AsyncTagsResourceWithRawResponse, TagsResourceWithStreamingResponse, AsyncTagsResourceWithStreamingResponse, ) from .tools import ( ToolsResource, AsyncToolsResource, ToolsResourceWithRawResponse, AsyncToolsResourceWithRawResponse, ToolsResourceWithStreamingResponse, AsyncToolsResourceWithStreamingResponse, ) from .deleted import ( DeletedResource, AsyncDeletedResource, DeletedResourceWithRawResponse, AsyncDeletedResourceWithRawResponse, DeletedResourceWithStreamingResponse, AsyncDeletedResourceWithStreamingResponse, ) from .versions import ( VersionsResource, AsyncVersionsResource, VersionsResourceWithRawResponse, AsyncVersionsResourceWithRawResponse, VersionsResourceWithStreamingResponse, AsyncVersionsResourceWithStreamingResponse, ) from ...._types import Body, Omit, Query, Headers, NotGiven, SequenceNotStr, omit, not_given from ...._utils import path_template, maybe_transform, strip_not_given, async_maybe_transform from ...._compat import cached_property from ....types.ai import ( assistant_chat_params, assistant_create_params, assistant_delete_params, assistant_update_params, assistant_imports_params, assistant_retrieve_params, assistant_send_sms_params, assistant_whatsapp_params, ) from .tests.tests import ( TestsResource, AsyncTestsResource, TestsResourceWithRawResponse, AsyncTestsResourceWithRawResponse, TestsResourceWithStreamingResponse, AsyncTestsResourceWithStreamingResponse, ) from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import ( to_raw_response_wrapper, to_streamed_response_wrapper, async_to_raw_response_wrapper, async_to_streamed_response_wrapper, ) from .instructions import ( InstructionsResource, AsyncInstructionsResource, InstructionsResourceWithRawResponse, AsyncInstructionsResourceWithRawResponse, InstructionsResourceWithStreamingResponse, AsyncInstructionsResourceWithStreamingResponse, ) from .canary_deploys import ( CanaryDeploysResource, AsyncCanaryDeploysResource, CanaryDeploysResourceWithRawResponse, AsyncCanaryDeploysResourceWithRawResponse, CanaryDeploysResourceWithStreamingResponse, AsyncCanaryDeploysResourceWithStreamingResponse, ) from ...._base_client import make_request_options from .scheduled_events import ( ScheduledEventsResource, AsyncScheduledEventsResource, ScheduledEventsResourceWithRawResponse, AsyncScheduledEventsResourceWithRawResponse, ScheduledEventsResourceWithStreamingResponse, AsyncScheduledEventsResourceWithStreamingResponse, ) from ....types.ai.assistants_list import AssistantsList from ....types.ai.enabled_features import EnabledFeatures from ....types.ai.inference_embedding import InferenceEmbedding from ....types.ai.assistant_tool_param import AssistantToolParam from ....types.ai.widget_settings_param import WidgetSettingsParam from ....types.ai.external_llm_req_param import ExternalLlmReqParam from ....types.ai.insight_settings_param import InsightSettingsParam from ....types.ai.privacy_settings_param import PrivacySettingsParam from ....types.ai.assistant_chat_response import AssistantChatResponse from ....types.ai.observability_req_param import ObservabilityReqParam from ....types.ai.messaging_settings_param import MessagingSettingsParam from ....types.ai.telephony_settings_param import TelephonySettingsParam from ....types.ai.websocket_settings_param import WebsocketSettingsParam from ....types.ai.assistant_delete_response import AssistantDeleteResponse from ....types.ai.delegation_settings_param import DelegationSettingsParam from ....types.ai.fallback_config_req_param import FallbackConfigReqParam from ....types.ai.assistant_a2_a_agent_param import AssistantA2AAgentParam from ....types.ai.assistant_mcp_server_param import AssistantMcpServerParam from ....types.ai.assistant_integration_param import AssistantIntegrationParam from ....types.ai.assistant_send_sms_response import AssistantSendSMSResponse from ....types.ai.assistant_whatsapp_response import AssistantWhatsappResponse from ....types.ai.conversation_flow_req_param import ConversationFlowReqParam from ....types.ai.transcription_settings_param import TranscriptionSettingsParam from ....types.ai.avatar_settings_request_param import AvatarSettingsRequestParam from ....types.ai.post_conversation_settings_req_param import PostConversationSettingsReqParam from ....types.ai.inference_embedding_voice_settings_param import InferenceEmbeddingVoiceSettingsParam from ....types.ai.inference_embedding_interruption_settings_param import InferenceEmbeddingInterruptionSettingsParam __all__ = ["AssistantsResource", "AsyncAssistantsResource"] class AssistantsResource(SyncAPIResource): """Configure AI assistant specifications""" @cached_property def tests(self) -> TestsResource: """Configure AI assistant specifications""" return TestsResource(self._client) @cached_property def canary_deploys(self) -> CanaryDeploysResource: """Configure AI assistant specifications""" return CanaryDeploysResource(self._client) @cached_property def scheduled_events(self) -> ScheduledEventsResource: """Configure AI assistant specifications""" return ScheduledEventsResource(self._client) @cached_property def tools(self) -> ToolsResource: """Configure AI assistant specifications""" return ToolsResource(self._client) @cached_property def versions(self) -> VersionsResource: """Configure AI assistant specifications""" return VersionsResource(self._client) @cached_property def tags(self) -> TagsResource: """Configure AI assistant specifications""" return TagsResource(self._client) @cached_property def instructions(self) -> InstructionsResource: """Configure AI assistant specifications""" return InstructionsResource(self._client) @cached_property def deleted(self) -> DeletedResource: """Configure AI assistant specifications""" return DeletedResource(self._client) @cached_property def with_raw_response(self) -> AssistantsResourceWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/team-telnyx/telnyx-python#accessing-raw-response-data-eg-headers """ return AssistantsResourceWithRawResponse(self) @cached_property def with_streaming_response(self) -> AssistantsResourceWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/team-telnyx/telnyx-python#with_streaming_response """ return AssistantsResourceWithStreamingResponse(self) def create( self, *, instructions: str, name: str, a2a_agents: Iterable[AssistantA2AAgentParam] | Omit = omit, avatar_settings: Optional[AvatarSettingsRequestParam] | Omit = omit, conversation_flow: ConversationFlowReqParam | Omit = omit, delegation_settings: DelegationSettingsParam | Omit = omit, description: str | Omit = omit, dynamic_variables: Dict[str, object] | Omit = omit, dynamic_variables_webhook_timeout_ms: int | Omit = omit, dynamic_variables_webhook_url: str | Omit = omit, enabled_features: List[EnabledFeatures] | Omit = omit, external_llm: ExternalLlmReqParam | Omit = omit, fallback_config: FallbackConfigReqParam | Omit = omit, greeting: str | Omit = omit, insight_settings: InsightSettingsParam | Omit = omit, integrations: Iterable[AssistantIntegrationParam] | Omit = omit, interruption_settings: InferenceEmbeddingInterruptionSettingsParam | Omit = omit, llm_api_key_ref: str | Omit = omit, mcp_servers: Iterable[AssistantMcpServerParam] | Omit = omit, messaging_settings: MessagingSettingsParam | Omit = omit, model: str | Omit = omit, observability_settings: ObservabilityReqParam | Omit = omit, post_conversation_settings: PostConversationSettingsReqParam | Omit = omit, privacy_settings: PrivacySettingsParam | Omit = omit, tags: SequenceNotStr[str] | Omit = omit, telephony_settings: TelephonySettingsParam | Omit = omit, tool_ids: SequenceNotStr[str] | Omit = omit, tools: Iterable[AssistantToolParam] | Omit = omit, transcription: TranscriptionSettingsParam | Omit = omit, voice_settings: InferenceEmbeddingVoiceSettingsParam | Omit = omit, websocket_settings: WebsocketSettingsParam | Omit = omit, widget_settings: WidgetSettingsParam | Omit = omit, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Creates a new AI assistant from the provided configuration, including its model, instructions, and attached tools, and returns the created assistant. Args: instructions: System instructions for the assistant. These may be templated with [dynamic variables](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables) a2a_agents: A2A agents this assistant can delegate to. Tools are not stored here: at the start of every conversation each agent's card is fetched and one tool is derived per skill the card advertises, named `a2a__`. The following limits are not enforced when the assistant is saved, and anything past them is dropped when the conversation starts: 64 agents per assistant, 64 skills per card, 128 derived tools per assistant, and a 6 second budget for all card fetches combined. An agent whose card cannot be fetched costs the assistant that capability for the conversation; it does not fail the call. avatar_settings: **Beta:** Configuration for the Telnyx open-source avatar provider. Use a stock avatar or an organization-owned custom avatar returned by the Avatars API. Discover the available stock catalog with GET /v2/ai/avatars and filter[avatar_type]=stock; follow meta.total_pages to load every page. conversation_flow: Conversation flow as supplied by API clients (create / update). A directed graph of `FlowNodeReq` connected by `FlowEdge`s. Validation enforces unique node/edge IDs, that `start_node_id` references a real node, and that every edge's endpoints reference real nodes. delegation_settings: Splits the conversation between a frontend model that talks to the caller and a backend model that does the work. On the GPT-Live route the frontend model cannot call tools at all — when it needs something done it raises a delegation and waits. On the chat completion route the frontend keeps a single `delegate` tool that returns immediately, so the conversation carries on while the backend works. Either way the backend's answer is spoken as commentary or kept as silent context, depending on `speak_results`. Beta feature. dynamic_variables: Map of dynamic variables and their default values dynamic_variables_webhook_timeout_ms: Timeout in milliseconds for the dynamic variables webhook. Must be between 1 and 10000 ms. If the webhook does not respond within this timeout, the call proceeds with default values. See the [dynamic variables guide](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables). dynamic_variables_webhook_url: If `dynamic_variables_webhook_url` is set, Telnyx sends a POST request to this URL at the start of the conversation to resolve dynamic variables. **Gotcha:** the webhook response must wrap variables under a top-level `dynamic_variables` object, e.g. `{"dynamic_variables": {"customer_name": "Jane"}}`. Returning a flat object will be ignored and variables will fall back to their defaults. See the [dynamic variables guide](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables) for the full request/response format and timeout behavior. greeting: Text that the assistant will use to start the conversation. This may be templated with [dynamic variables](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables). Use an empty string to have the assistant wait for the user to speak first. Use the special value `` to have the assistant generate the greeting based on the system instructions. integrations: Connected integrations attached to the assistant. The catalog of available integrations is at `/ai/integrations`; the user's connected integrations are at `/ai/integrations/connections`. Each item references a catalog integration by `integration_id`. interruption_settings: Settings for interruptions and how the assistant decides the user has finished speaking. These timings are most relevant when using non turn-taking transcription models. For turn-taking models like `deepgram/flux`, end-of-turn behavior is controlled by the transcription end-of-turn settings under `transcription.settings` (`eot_threshold`, `eot_timeout_ms`, `eager_eot_threshold`). llm_api_key_ref: This is only needed when using third-party inference providers selected by `model`. The `identifier` for an integration secret [/v2/integration_secrets](https://developers.telnyx.com/api-reference/integration-secrets/create-a-secret) that refers to your LLM provider's API key. For bring-your-own endpoint authentication, use `external_llm.llm_api_key_ref` instead. Warning: Free plans are unlikely to work with this integration. mcp_servers: MCP servers attached to the assistant. Create MCP servers with `/ai/mcp_servers`, then reference them by `id` here. model: ID of the model to use when `external_llm` is not set. You can use the [Get models API](https://developers.telnyx.com/api-reference/openai-chat/get-available-models-openai-compatible) to see available models. If `external_llm` is provided, the assistant uses `external_llm` instead of this field. If neither `model` nor `external_llm` is provided, Telnyx applies the default model. post_conversation_settings: Configuration for post-conversation processing. When enabled, the assistant receives one additional LLM turn after the conversation ends, allowing it to execute final tool calls such as sending a summary or updating a record via webhook or function tools. Integration and MCP server tools are not available post-conversation; call-control tools (e.g. hangup, transfer) are also unavailable. Beta feature. tags: Tags associated with the assistant. Tags can also be managed with the assistant tag endpoints. tool_ids: IDs of shared tools to attach to the assistant. New integrations should prefer `tool_ids` over inline `tools`. tools: Deprecated for new integrations. Inline tool definitions available to the assistant. Prefer `tool_ids` to attach shared tools created with the AI Tools endpoints. websocket_settings: Streams conversation and telephony events to a WebSocket server you host, and accepts messages injected back into the conversation. Telnyx opens the connection as a client, once per conversation. Delivery is best effort throughout: while the connection is down events are dropped rather than queued, and no socket failure is ever allowed to affect the call. Beta feature. widget_settings: Configuration settings for the assistant's web widget. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return self._post( "/ai/assistants", body=maybe_transform( { "instructions": instructions, "name": name, "a2a_agents": a2a_agents, "avatar_settings": avatar_settings, "conversation_flow": conversation_flow, "delegation_settings": delegation_settings, "description": description, "dynamic_variables": dynamic_variables, "dynamic_variables_webhook_timeout_ms": dynamic_variables_webhook_timeout_ms, "dynamic_variables_webhook_url": dynamic_variables_webhook_url, "enabled_features": enabled_features, "external_llm": external_llm, "fallback_config": fallback_config, "greeting": greeting, "insight_settings": insight_settings, "integrations": integrations, "interruption_settings": interruption_settings, "llm_api_key_ref": llm_api_key_ref, "mcp_servers": mcp_servers, "messaging_settings": messaging_settings, "model": model, "observability_settings": observability_settings, "post_conversation_settings": post_conversation_settings, "privacy_settings": privacy_settings, "tags": tags, "telephony_settings": telephony_settings, "tool_ids": tool_ids, "tools": tools, "transcription": transcription, "voice_settings": voice_settings, "websocket_settings": websocket_settings, "widget_settings": widget_settings, }, assistant_create_params.AssistantCreateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=InferenceEmbedding, ) def retrieve( self, assistant_id: str, *, call_control_id: str | Omit = omit, fetch_dynamic_variables_from_webhook: bool | Omit = omit, from_: str | Omit = omit, to: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Retrieve an AI Assistant configuration by `assistant_id`. Args: call_control_id: Filter results by call control id. fetch_dynamic_variables_from_webhook: Whether to fetch dynamic variables from the configured webhook. from_: Start of the filter range. to: End of the filter range. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return self._get( path_template("/ai/assistants/{assistant_id}", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=maybe_transform( { "call_control_id": call_control_id, "fetch_dynamic_variables_from_webhook": fetch_dynamic_variables_from_webhook, "from_": from_, "to": to, }, assistant_retrieve_params.AssistantRetrieveParams, ), ), cast_to=InferenceEmbedding, ) def update( self, assistant_id: str, *, a2a_agents: Iterable[AssistantA2AAgentParam] | Omit = omit, avatar_settings: Optional[AvatarSettingsRequestParam] | Omit = omit, conversation_flow: ConversationFlowReqParam | Omit = omit, delegation_settings: DelegationSettingsParam | Omit = omit, description: str | Omit = omit, dynamic_variables: Dict[str, object] | Omit = omit, dynamic_variables_webhook_timeout_ms: int | Omit = omit, dynamic_variables_webhook_url: str | Omit = omit, enabled_features: List[EnabledFeatures] | Omit = omit, external_llm: ExternalLlmReqParam | Omit = omit, fallback_config: FallbackConfigReqParam | Omit = omit, greeting: str | Omit = omit, insight_settings: InsightSettingsParam | Omit = omit, instructions: str | Omit = omit, integrations: Iterable[AssistantIntegrationParam] | Omit = omit, interruption_settings: InferenceEmbeddingInterruptionSettingsParam | Omit = omit, llm_api_key_ref: str | Omit = omit, mcp_servers: Iterable[AssistantMcpServerParam] | Omit = omit, messaging_settings: MessagingSettingsParam | Omit = omit, model: str | Omit = omit, name: str | Omit = omit, observability_settings: ObservabilityReqParam | Omit = omit, post_conversation_settings: PostConversationSettingsReqParam | Omit = omit, privacy_settings: PrivacySettingsParam | Omit = omit, promote_to_main: bool | Omit = omit, tags: SequenceNotStr[str] | Omit = omit, telephony_settings: TelephonySettingsParam | Omit = omit, tool_ids: SequenceNotStr[str] | Omit = omit, tools: Iterable[AssistantToolParam] | Omit = omit, transcription: TranscriptionSettingsParam | Omit = omit, version_name: str | Omit = omit, voice_settings: InferenceEmbeddingVoiceSettingsParam | Omit = omit, websocket_settings: WebsocketSettingsParam | Omit = omit, widget_settings: WidgetSettingsParam | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Updates the specified AI assistant's attributes and returns the updated assistant. The request can also control how the change is promoted across assistant versions. Every update saves a new version, and an assistant keeps at most 10 versions: once it has more, the oldest versions are permanently deleted, except the main version and any version referenced by a traffic distribution rule. Args: a2a_agents: A2A agents this assistant can delegate to. Tools are not stored here: at the start of every conversation each agent's card is fetched and one tool is derived per skill the card advertises, named `a2a__`. The following limits are not enforced when the assistant is saved, and anything past them is dropped when the conversation starts: 64 agents per assistant, 64 skills per card, 128 derived tools per assistant, and a 6 second budget for all card fetches combined. An agent whose card cannot be fetched costs the assistant that capability for the conversation; it does not fail the call. Omit this field to leave the assistant's agents unchanged; send an empty array to remove them all. avatar_settings: **Beta:** Configuration for the Telnyx open-source avatar provider. Use a stock avatar or an organization-owned custom avatar returned by the Avatars API. Discover the available stock catalog with GET /v2/ai/avatars and filter[avatar_type]=stock; follow meta.total_pages to load every page. conversation_flow: Conversation flow as supplied by API clients (create / update). A directed graph of `FlowNodeReq` connected by `FlowEdge`s. Validation enforces unique node/edge IDs, that `start_node_id` references a real node, and that every edge's endpoints reference real nodes. delegation_settings: Splits the conversation between a frontend model that talks to the caller and a backend model that does the work. On the GPT-Live route the frontend model cannot call tools at all — when it needs something done it raises a delegation and waits. On the chat completion route the frontend keeps a single `delegate` tool that returns immediately, so the conversation carries on while the backend works. Either way the backend's answer is spoken as commentary or kept as silent context, depending on `speak_results`. Beta feature. dynamic_variables: Map of dynamic variables and their default values dynamic_variables_webhook_timeout_ms: Timeout in milliseconds for the dynamic variables webhook. Must be between 1 and 10000 ms. If the webhook does not respond within this timeout, the call proceeds with default values. See the [dynamic variables guide](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables). dynamic_variables_webhook_url: If `dynamic_variables_webhook_url` is set, Telnyx sends a POST request to this URL at the start of the conversation to resolve dynamic variables. **Gotcha:** the webhook response must wrap variables under a top-level `dynamic_variables` object, e.g. `{"dynamic_variables": {"customer_name": "Jane"}}`. Returning a flat object will be ignored and variables will fall back to their defaults. See the [dynamic variables guide](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables) for the full request/response format and timeout behavior. greeting: Text that the assistant will use to start the conversation. This may be templated with [dynamic variables](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables). Use an empty string to have the assistant wait for the user to speak first. Use the special value `` to have the assistant generate the greeting based on the system instructions. instructions: System instructions for the assistant. These may be templated with [dynamic variables](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables) integrations: Connected integrations attached to the assistant. The catalog of available integrations is at `/ai/integrations`; the user's connected integrations are at `/ai/integrations/connections`. Each item references a catalog integration by `integration_id`. interruption_settings: Settings for interruptions and how the assistant decides the user has finished speaking. These timings are most relevant when using non turn-taking transcription models. For turn-taking models like `deepgram/flux`, end-of-turn behavior is controlled by the transcription end-of-turn settings under `transcription.settings` (`eot_threshold`, `eot_timeout_ms`, `eager_eot_threshold`). llm_api_key_ref: This is only needed when using third-party inference providers selected by `model`. The `identifier` for an integration secret [/v2/integration_secrets](https://developers.telnyx.com/api-reference/integration-secrets/create-a-secret) that refers to your LLM provider's API key. For bring-your-own endpoint authentication, use `external_llm.llm_api_key_ref` instead. Warning: Free plans are unlikely to work with this integration. mcp_servers: MCP servers attached to the assistant. Create MCP servers with `/ai/mcp_servers`, then reference them by `id` here. model: ID of the model to use when `external_llm` is not set. You can use the [Get models API](https://developers.telnyx.com/api-reference/openai-chat/get-available-models-openai-compatible) to see available models. If `external_llm` is provided, the assistant uses `external_llm` instead of this field. If neither `model` nor `external_llm` is provided, Telnyx applies the default model. post_conversation_settings: Configuration for post-conversation processing. When enabled, the assistant receives one additional LLM turn after the conversation ends, allowing it to execute final tool calls such as sending a summary or updating a record via webhook or function tools. Integration and MCP server tools are not available post-conversation; call-control tools (e.g. hangup, transfer) are also unavailable. Beta feature. promote_to_main: Indicates whether the assistant should be promoted to the main version. Defaults to true. tags: Tags associated with the assistant. Tags can also be managed with the assistant tag endpoints. tool_ids: IDs of shared tools to attach to the assistant. New integrations should prefer `tool_ids` over inline `tools`. On update, a sent `tool_ids` array fully replaces the assistant's attached shared tools; omit the field to leave them unchanged. Single-instance tool types are counted across inline `tools` and `tool_ids` combined, so attaching a shared tool of such a type when an instance already exists returns HTTP 400 with error code 10015. tools: Deprecated for new integrations. Inline tool definitions available to the assistant. Prefer `tool_ids` to attach shared tools created with the AI Tools endpoints. On update, a sent `tools` array fully replaces the assistant's inline tools; omit the field to leave the inline tools unchanged. Each tool type except `function`, `webhook`, and `client_side_tool` allows at most one instance per assistant, counted across inline `tools` and shared `tool_ids` combined — sending a duplicate of such a type returns HTTP 400 with error code 10015. Responses merge shared tools into `tools` with `shared: true`; when updating, omit those tools from the `tools` array and manage them through `tool_ids` instead. version_name: Human-readable name for the assistant version. websocket_settings: Streams conversation and telephony events to a WebSocket server you host, and accepts messages injected back into the conversation. Telnyx opens the connection as a client, once per conversation. Delivery is best effort throughout: while the connection is down events are dropped rather than queued, and no socket failure is ever allowed to affect the call. Beta feature. widget_settings: Configuration settings for the assistant's web widget. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return self._post( path_template("/ai/assistants/{assistant_id}", assistant_id=assistant_id), body=maybe_transform( { "a2a_agents": a2a_agents, "avatar_settings": avatar_settings, "conversation_flow": conversation_flow, "delegation_settings": delegation_settings, "description": description, "dynamic_variables": dynamic_variables, "dynamic_variables_webhook_timeout_ms": dynamic_variables_webhook_timeout_ms, "dynamic_variables_webhook_url": dynamic_variables_webhook_url, "enabled_features": enabled_features, "external_llm": external_llm, "fallback_config": fallback_config, "greeting": greeting, "insight_settings": insight_settings, "instructions": instructions, "integrations": integrations, "interruption_settings": interruption_settings, "llm_api_key_ref": llm_api_key_ref, "mcp_servers": mcp_servers, "messaging_settings": messaging_settings, "model": model, "name": name, "observability_settings": observability_settings, "post_conversation_settings": post_conversation_settings, "privacy_settings": privacy_settings, "promote_to_main": promote_to_main, "tags": tags, "telephony_settings": telephony_settings, "tool_ids": tool_ids, "tools": tools, "transcription": transcription, "version_name": version_name, "voice_settings": voice_settings, "websocket_settings": websocket_settings, "widget_settings": widget_settings, }, assistant_update_params.AssistantUpdateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=InferenceEmbedding, ) def list( self, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantsList: """Retrieve a list of all AI Assistants configured by the user.""" return self._get( "/ai/assistants", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantsList, ) def delete( self, assistant_id: str, *, hard_delete: bool | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantDeleteResponse: """ Delete an AI Assistant by `assistant_id`. By default this performs a soft delete: the assistant moves to the Recently Deleted list and stays restorable for 30 days, after which it is permanently deleted automatically. The assistant's versions and TeXML application are preserved during the retention window. Pass `hard_delete=true` to skip the retention window and permanently delete the assistant immediately. A hard delete erases the assistant and all of its versions, and deletes its TeXML application unless phone numbers are still assigned to it. It does not delete conversations, recordings, shared tools the assistant referenced, or knowledge-base embeddings. Deletion fails with `400` if other assistants reference this one through a handoff tool or a conversation-flow edge — remove those references first. Args: hard_delete: Permanently delete the assistant immediately instead of soft-deleting it to the Recently Deleted list, where it stays restorable for 30 days. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return self._delete( path_template("/ai/assistants/{assistant_id}", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=maybe_transform({"hard_delete": hard_delete}, assistant_delete_params.AssistantDeleteParams), ), cast_to=AssistantDeleteResponse, ) def chat( self, assistant_id: str, *, content: str, conversation_id: str, name: str | Omit = omit, stream: bool | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantChatResponse: """ This endpoint allows a client to send a chat message to a specific AI Assistant. The assistant processes the message and returns a relevant reply based on the current conversation context. Refer to the Conversation API to [create a conversation](https://developers.telnyx.com/api-reference/conversations/create-a-conversation), [filter existing conversations](https://developers.telnyx.com/api-reference/conversations/list-conversations), [fetch messages for a conversation](https://developers.telnyx.com/api-reference/conversations/get-conversation-messages), and [manually add messages to a conversation](https://developers.telnyx.com/api-reference/conversations/create-message). Args: content: The message content sent by the client to the assistant conversation_id: A unique identifier for the conversation thread, used to maintain context name: The optional display name of the user sending the message stream: When true, the response is streamed as Server-Sent Events (`text/event-stream`): `delta` events carry content fragments as they are generated, a final `done` event carries the full content plus `whatsapp_template`, and a terminal `error` event reports failures that happen after streaming started. When false (default), the response is a single JSON object. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return self._post( path_template("/ai/assistants/{assistant_id}/chat", assistant_id=assistant_id), body=maybe_transform( { "content": content, "conversation_id": conversation_id, "name": name, "stream": stream, }, assistant_chat_params.AssistantChatParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantChatResponse, ) def clone( self, assistant_id: str, *, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Clone an existing assistant, excluding telephony and messaging settings. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return self._post( path_template("/ai/assistants/{assistant_id}/clone", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=InferenceEmbedding, ) def get_texml( self, assistant_id: str, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> str: """ Get an assistant texml by `assistant_id`. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return self._get( path_template("/ai/assistants/{assistant_id}/texml", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=str, ) def imports( self, *, api_key_ref: str, provider: Literal["elevenlabs", "vapi", "retell"], import_ids: SequenceNotStr[str] | Omit = omit, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantsList: """Import assistants from external providers. Any assistant that has already been imported will be overwritten with its latest version from the importing provider. Args: api_key_ref: Integration secret pointer that refers to the API key for the external provider. This should be an identifier for an integration secret created via /v2/integration_secrets. provider: The external provider to import assistants from. import_ids: Optional list of assistant IDs to import from the external provider. If not provided, all assistants will be imported. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return self._post( "/ai/assistants/import", body=maybe_transform( { "api_key_ref": api_key_ref, "provider": provider, "import_ids": import_ids, }, assistant_imports_params.AssistantImportsParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantsList, ) def restore( self, assistant_id: str, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Restore a soft-deleted assistant from the Recently Deleted list. The assistant becomes fully active again with its versions and TeXML application as they were at deletion time. Restoring does not re-enable numbers or connections that were released separately after the deletion. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return self._post( path_template("/ai/assistants/{assistant_id}/restore", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=InferenceEmbedding, ) def send_sms( self, assistant_id: str, *, from_: str, to: str, conversation_metadata: Dict[str, Union[str, int, bool]] | Omit = omit, should_create_conversation: bool | Omit = omit, text: str | Omit = omit, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantSendSMSResponse: """Send an SMS message for an assistant. This endpoint: 1. Validates the assistant exists and has messaging profile configured 2. If should_create_conversation is true, creates a new conversation with metadata 3. Sends the SMS message (If `text` is set, this will be sent. Otherwise, if this is the first message in the conversation and the assistant has a `greeting` configured, this will be sent. Otherwise the assistant will generate the text to send.) 4. Updates conversation metadata if provided 5. Returns the conversation ID Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return self._post( path_template("/ai/assistants/{assistant_id}/chat/sms", assistant_id=assistant_id), body=maybe_transform( { "from_": from_, "to": to, "conversation_metadata": conversation_metadata, "should_create_conversation": should_create_conversation, "text": text, }, assistant_send_sms_params.AssistantSendSMSParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantSendSMSResponse, ) def whatsapp( self, assistant_id: str, *, content: str, from_: str, to: str, conversation_metadata: Dict[str, Union[str, int, bool]] | Omit = omit, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantWhatsappResponse: """Start a WhatsApp conversation with a customer from the business side. This endpoint: 1. Validates that `from` is a WhatsApp number on your account whose messaging profile has this assistant configured 2. Creates a new `whatsapp_chat` conversation with the provided metadata 3. Asks the assistant to pick one of its approved WhatsApp templates and fill its variables from `content` 4. Sends the template from `from` to `to` 5. Returns the conversation ID and the message ID When the customer replies, the reply is routed to the same conversation and the assistant answers within the 24-hour customer service window. The assistant needs a `whatsapp_template` tool with at least one approved template, data retention enabled and PII redaction disabled. Args: content: Instruction for the assistant, including the values for the template variables, e.g. `Send the login verification code 482913 to the customer.` from_: WhatsApp number on your account to send from, in E.164 format. Its messaging profile must have this assistant configured. to: Customer to message, as an E.164 phone number or a WhatsApp business-scoped user ID (BSUID). conversation_metadata: Metadata stored on the conversation. Keys starting with `telnyx_` and the `assistant_id` key are reserved. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return self._post( path_template("/ai/assistants/{assistant_id}/chat/whatsapp", assistant_id=assistant_id), body=maybe_transform( { "content": content, "from_": from_, "to": to, "conversation_metadata": conversation_metadata, }, assistant_whatsapp_params.AssistantWhatsappParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantWhatsappResponse, ) class AsyncAssistantsResource(AsyncAPIResource): """Configure AI assistant specifications""" @cached_property def tests(self) -> AsyncTestsResource: """Configure AI assistant specifications""" return AsyncTestsResource(self._client) @cached_property def canary_deploys(self) -> AsyncCanaryDeploysResource: """Configure AI assistant specifications""" return AsyncCanaryDeploysResource(self._client) @cached_property def scheduled_events(self) -> AsyncScheduledEventsResource: """Configure AI assistant specifications""" return AsyncScheduledEventsResource(self._client) @cached_property def tools(self) -> AsyncToolsResource: """Configure AI assistant specifications""" return AsyncToolsResource(self._client) @cached_property def versions(self) -> AsyncVersionsResource: """Configure AI assistant specifications""" return AsyncVersionsResource(self._client) @cached_property def tags(self) -> AsyncTagsResource: """Configure AI assistant specifications""" return AsyncTagsResource(self._client) @cached_property def instructions(self) -> AsyncInstructionsResource: """Configure AI assistant specifications""" return AsyncInstructionsResource(self._client) @cached_property def deleted(self) -> AsyncDeletedResource: """Configure AI assistant specifications""" return AsyncDeletedResource(self._client) @cached_property def with_raw_response(self) -> AsyncAssistantsResourceWithRawResponse: """ This property can be used as a prefix for any HTTP method call to return the raw response object instead of the parsed content. For more information, see https://www.github.com/team-telnyx/telnyx-python#accessing-raw-response-data-eg-headers """ return AsyncAssistantsResourceWithRawResponse(self) @cached_property def with_streaming_response(self) -> AsyncAssistantsResourceWithStreamingResponse: """ An alternative to `.with_raw_response` that doesn't eagerly read the response body. For more information, see https://www.github.com/team-telnyx/telnyx-python#with_streaming_response """ return AsyncAssistantsResourceWithStreamingResponse(self) async def create( self, *, instructions: str, name: str, a2a_agents: Iterable[AssistantA2AAgentParam] | Omit = omit, avatar_settings: Optional[AvatarSettingsRequestParam] | Omit = omit, conversation_flow: ConversationFlowReqParam | Omit = omit, delegation_settings: DelegationSettingsParam | Omit = omit, description: str | Omit = omit, dynamic_variables: Dict[str, object] | Omit = omit, dynamic_variables_webhook_timeout_ms: int | Omit = omit, dynamic_variables_webhook_url: str | Omit = omit, enabled_features: List[EnabledFeatures] | Omit = omit, external_llm: ExternalLlmReqParam | Omit = omit, fallback_config: FallbackConfigReqParam | Omit = omit, greeting: str | Omit = omit, insight_settings: InsightSettingsParam | Omit = omit, integrations: Iterable[AssistantIntegrationParam] | Omit = omit, interruption_settings: InferenceEmbeddingInterruptionSettingsParam | Omit = omit, llm_api_key_ref: str | Omit = omit, mcp_servers: Iterable[AssistantMcpServerParam] | Omit = omit, messaging_settings: MessagingSettingsParam | Omit = omit, model: str | Omit = omit, observability_settings: ObservabilityReqParam | Omit = omit, post_conversation_settings: PostConversationSettingsReqParam | Omit = omit, privacy_settings: PrivacySettingsParam | Omit = omit, tags: SequenceNotStr[str] | Omit = omit, telephony_settings: TelephonySettingsParam | Omit = omit, tool_ids: SequenceNotStr[str] | Omit = omit, tools: Iterable[AssistantToolParam] | Omit = omit, transcription: TranscriptionSettingsParam | Omit = omit, voice_settings: InferenceEmbeddingVoiceSettingsParam | Omit = omit, websocket_settings: WebsocketSettingsParam | Omit = omit, widget_settings: WidgetSettingsParam | Omit = omit, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Creates a new AI assistant from the provided configuration, including its model, instructions, and attached tools, and returns the created assistant. Args: instructions: System instructions for the assistant. These may be templated with [dynamic variables](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables) a2a_agents: A2A agents this assistant can delegate to. Tools are not stored here: at the start of every conversation each agent's card is fetched and one tool is derived per skill the card advertises, named `a2a__`. The following limits are not enforced when the assistant is saved, and anything past them is dropped when the conversation starts: 64 agents per assistant, 64 skills per card, 128 derived tools per assistant, and a 6 second budget for all card fetches combined. An agent whose card cannot be fetched costs the assistant that capability for the conversation; it does not fail the call. avatar_settings: **Beta:** Configuration for the Telnyx open-source avatar provider. Use a stock avatar or an organization-owned custom avatar returned by the Avatars API. Discover the available stock catalog with GET /v2/ai/avatars and filter[avatar_type]=stock; follow meta.total_pages to load every page. conversation_flow: Conversation flow as supplied by API clients (create / update). A directed graph of `FlowNodeReq` connected by `FlowEdge`s. Validation enforces unique node/edge IDs, that `start_node_id` references a real node, and that every edge's endpoints reference real nodes. delegation_settings: Splits the conversation between a frontend model that talks to the caller and a backend model that does the work. On the GPT-Live route the frontend model cannot call tools at all — when it needs something done it raises a delegation and waits. On the chat completion route the frontend keeps a single `delegate` tool that returns immediately, so the conversation carries on while the backend works. Either way the backend's answer is spoken as commentary or kept as silent context, depending on `speak_results`. Beta feature. dynamic_variables: Map of dynamic variables and their default values dynamic_variables_webhook_timeout_ms: Timeout in milliseconds for the dynamic variables webhook. Must be between 1 and 10000 ms. If the webhook does not respond within this timeout, the call proceeds with default values. See the [dynamic variables guide](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables). dynamic_variables_webhook_url: If `dynamic_variables_webhook_url` is set, Telnyx sends a POST request to this URL at the start of the conversation to resolve dynamic variables. **Gotcha:** the webhook response must wrap variables under a top-level `dynamic_variables` object, e.g. `{"dynamic_variables": {"customer_name": "Jane"}}`. Returning a flat object will be ignored and variables will fall back to their defaults. See the [dynamic variables guide](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables) for the full request/response format and timeout behavior. greeting: Text that the assistant will use to start the conversation. This may be templated with [dynamic variables](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables). Use an empty string to have the assistant wait for the user to speak first. Use the special value `` to have the assistant generate the greeting based on the system instructions. integrations: Connected integrations attached to the assistant. The catalog of available integrations is at `/ai/integrations`; the user's connected integrations are at `/ai/integrations/connections`. Each item references a catalog integration by `integration_id`. interruption_settings: Settings for interruptions and how the assistant decides the user has finished speaking. These timings are most relevant when using non turn-taking transcription models. For turn-taking models like `deepgram/flux`, end-of-turn behavior is controlled by the transcription end-of-turn settings under `transcription.settings` (`eot_threshold`, `eot_timeout_ms`, `eager_eot_threshold`). llm_api_key_ref: This is only needed when using third-party inference providers selected by `model`. The `identifier` for an integration secret [/v2/integration_secrets](https://developers.telnyx.com/api-reference/integration-secrets/create-a-secret) that refers to your LLM provider's API key. For bring-your-own endpoint authentication, use `external_llm.llm_api_key_ref` instead. Warning: Free plans are unlikely to work with this integration. mcp_servers: MCP servers attached to the assistant. Create MCP servers with `/ai/mcp_servers`, then reference them by `id` here. model: ID of the model to use when `external_llm` is not set. You can use the [Get models API](https://developers.telnyx.com/api-reference/openai-chat/get-available-models-openai-compatible) to see available models. If `external_llm` is provided, the assistant uses `external_llm` instead of this field. If neither `model` nor `external_llm` is provided, Telnyx applies the default model. post_conversation_settings: Configuration for post-conversation processing. When enabled, the assistant receives one additional LLM turn after the conversation ends, allowing it to execute final tool calls such as sending a summary or updating a record via webhook or function tools. Integration and MCP server tools are not available post-conversation; call-control tools (e.g. hangup, transfer) are also unavailable. Beta feature. tags: Tags associated with the assistant. Tags can also be managed with the assistant tag endpoints. tool_ids: IDs of shared tools to attach to the assistant. New integrations should prefer `tool_ids` over inline `tools`. tools: Deprecated for new integrations. Inline tool definitions available to the assistant. Prefer `tool_ids` to attach shared tools created with the AI Tools endpoints. websocket_settings: Streams conversation and telephony events to a WebSocket server you host, and accepts messages injected back into the conversation. Telnyx opens the connection as a client, once per conversation. Delivery is best effort throughout: while the connection is down events are dropped rather than queued, and no socket failure is ever allowed to affect the call. Beta feature. widget_settings: Configuration settings for the assistant's web widget. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return await self._post( "/ai/assistants", body=await async_maybe_transform( { "instructions": instructions, "name": name, "a2a_agents": a2a_agents, "avatar_settings": avatar_settings, "conversation_flow": conversation_flow, "delegation_settings": delegation_settings, "description": description, "dynamic_variables": dynamic_variables, "dynamic_variables_webhook_timeout_ms": dynamic_variables_webhook_timeout_ms, "dynamic_variables_webhook_url": dynamic_variables_webhook_url, "enabled_features": enabled_features, "external_llm": external_llm, "fallback_config": fallback_config, "greeting": greeting, "insight_settings": insight_settings, "integrations": integrations, "interruption_settings": interruption_settings, "llm_api_key_ref": llm_api_key_ref, "mcp_servers": mcp_servers, "messaging_settings": messaging_settings, "model": model, "observability_settings": observability_settings, "post_conversation_settings": post_conversation_settings, "privacy_settings": privacy_settings, "tags": tags, "telephony_settings": telephony_settings, "tool_ids": tool_ids, "tools": tools, "transcription": transcription, "voice_settings": voice_settings, "websocket_settings": websocket_settings, "widget_settings": widget_settings, }, assistant_create_params.AssistantCreateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=InferenceEmbedding, ) async def retrieve( self, assistant_id: str, *, call_control_id: str | Omit = omit, fetch_dynamic_variables_from_webhook: bool | Omit = omit, from_: str | Omit = omit, to: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Retrieve an AI Assistant configuration by `assistant_id`. Args: call_control_id: Filter results by call control id. fetch_dynamic_variables_from_webhook: Whether to fetch dynamic variables from the configured webhook. from_: Start of the filter range. to: End of the filter range. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return await self._get( path_template("/ai/assistants/{assistant_id}", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=await async_maybe_transform( { "call_control_id": call_control_id, "fetch_dynamic_variables_from_webhook": fetch_dynamic_variables_from_webhook, "from_": from_, "to": to, }, assistant_retrieve_params.AssistantRetrieveParams, ), ), cast_to=InferenceEmbedding, ) async def update( self, assistant_id: str, *, a2a_agents: Iterable[AssistantA2AAgentParam] | Omit = omit, avatar_settings: Optional[AvatarSettingsRequestParam] | Omit = omit, conversation_flow: ConversationFlowReqParam | Omit = omit, delegation_settings: DelegationSettingsParam | Omit = omit, description: str | Omit = omit, dynamic_variables: Dict[str, object] | Omit = omit, dynamic_variables_webhook_timeout_ms: int | Omit = omit, dynamic_variables_webhook_url: str | Omit = omit, enabled_features: List[EnabledFeatures] | Omit = omit, external_llm: ExternalLlmReqParam | Omit = omit, fallback_config: FallbackConfigReqParam | Omit = omit, greeting: str | Omit = omit, insight_settings: InsightSettingsParam | Omit = omit, instructions: str | Omit = omit, integrations: Iterable[AssistantIntegrationParam] | Omit = omit, interruption_settings: InferenceEmbeddingInterruptionSettingsParam | Omit = omit, llm_api_key_ref: str | Omit = omit, mcp_servers: Iterable[AssistantMcpServerParam] | Omit = omit, messaging_settings: MessagingSettingsParam | Omit = omit, model: str | Omit = omit, name: str | Omit = omit, observability_settings: ObservabilityReqParam | Omit = omit, post_conversation_settings: PostConversationSettingsReqParam | Omit = omit, privacy_settings: PrivacySettingsParam | Omit = omit, promote_to_main: bool | Omit = omit, tags: SequenceNotStr[str] | Omit = omit, telephony_settings: TelephonySettingsParam | Omit = omit, tool_ids: SequenceNotStr[str] | Omit = omit, tools: Iterable[AssistantToolParam] | Omit = omit, transcription: TranscriptionSettingsParam | Omit = omit, version_name: str | Omit = omit, voice_settings: InferenceEmbeddingVoiceSettingsParam | Omit = omit, websocket_settings: WebsocketSettingsParam | Omit = omit, widget_settings: WidgetSettingsParam | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Updates the specified AI assistant's attributes and returns the updated assistant. The request can also control how the change is promoted across assistant versions. Every update saves a new version, and an assistant keeps at most 10 versions: once it has more, the oldest versions are permanently deleted, except the main version and any version referenced by a traffic distribution rule. Args: a2a_agents: A2A agents this assistant can delegate to. Tools are not stored here: at the start of every conversation each agent's card is fetched and one tool is derived per skill the card advertises, named `a2a__`. The following limits are not enforced when the assistant is saved, and anything past them is dropped when the conversation starts: 64 agents per assistant, 64 skills per card, 128 derived tools per assistant, and a 6 second budget for all card fetches combined. An agent whose card cannot be fetched costs the assistant that capability for the conversation; it does not fail the call. Omit this field to leave the assistant's agents unchanged; send an empty array to remove them all. avatar_settings: **Beta:** Configuration for the Telnyx open-source avatar provider. Use a stock avatar or an organization-owned custom avatar returned by the Avatars API. Discover the available stock catalog with GET /v2/ai/avatars and filter[avatar_type]=stock; follow meta.total_pages to load every page. conversation_flow: Conversation flow as supplied by API clients (create / update). A directed graph of `FlowNodeReq` connected by `FlowEdge`s. Validation enforces unique node/edge IDs, that `start_node_id` references a real node, and that every edge's endpoints reference real nodes. delegation_settings: Splits the conversation between a frontend model that talks to the caller and a backend model that does the work. On the GPT-Live route the frontend model cannot call tools at all — when it needs something done it raises a delegation and waits. On the chat completion route the frontend keeps a single `delegate` tool that returns immediately, so the conversation carries on while the backend works. Either way the backend's answer is spoken as commentary or kept as silent context, depending on `speak_results`. Beta feature. dynamic_variables: Map of dynamic variables and their default values dynamic_variables_webhook_timeout_ms: Timeout in milliseconds for the dynamic variables webhook. Must be between 1 and 10000 ms. If the webhook does not respond within this timeout, the call proceeds with default values. See the [dynamic variables guide](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables). dynamic_variables_webhook_url: If `dynamic_variables_webhook_url` is set, Telnyx sends a POST request to this URL at the start of the conversation to resolve dynamic variables. **Gotcha:** the webhook response must wrap variables under a top-level `dynamic_variables` object, e.g. `{"dynamic_variables": {"customer_name": "Jane"}}`. Returning a flat object will be ignored and variables will fall back to their defaults. See the [dynamic variables guide](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables) for the full request/response format and timeout behavior. greeting: Text that the assistant will use to start the conversation. This may be templated with [dynamic variables](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables). Use an empty string to have the assistant wait for the user to speak first. Use the special value `` to have the assistant generate the greeting based on the system instructions. instructions: System instructions for the assistant. These may be templated with [dynamic variables](https://developers.telnyx.com/docs/inference/ai-assistants/dynamic-variables) integrations: Connected integrations attached to the assistant. The catalog of available integrations is at `/ai/integrations`; the user's connected integrations are at `/ai/integrations/connections`. Each item references a catalog integration by `integration_id`. interruption_settings: Settings for interruptions and how the assistant decides the user has finished speaking. These timings are most relevant when using non turn-taking transcription models. For turn-taking models like `deepgram/flux`, end-of-turn behavior is controlled by the transcription end-of-turn settings under `transcription.settings` (`eot_threshold`, `eot_timeout_ms`, `eager_eot_threshold`). llm_api_key_ref: This is only needed when using third-party inference providers selected by `model`. The `identifier` for an integration secret [/v2/integration_secrets](https://developers.telnyx.com/api-reference/integration-secrets/create-a-secret) that refers to your LLM provider's API key. For bring-your-own endpoint authentication, use `external_llm.llm_api_key_ref` instead. Warning: Free plans are unlikely to work with this integration. mcp_servers: MCP servers attached to the assistant. Create MCP servers with `/ai/mcp_servers`, then reference them by `id` here. model: ID of the model to use when `external_llm` is not set. You can use the [Get models API](https://developers.telnyx.com/api-reference/openai-chat/get-available-models-openai-compatible) to see available models. If `external_llm` is provided, the assistant uses `external_llm` instead of this field. If neither `model` nor `external_llm` is provided, Telnyx applies the default model. post_conversation_settings: Configuration for post-conversation processing. When enabled, the assistant receives one additional LLM turn after the conversation ends, allowing it to execute final tool calls such as sending a summary or updating a record via webhook or function tools. Integration and MCP server tools are not available post-conversation; call-control tools (e.g. hangup, transfer) are also unavailable. Beta feature. promote_to_main: Indicates whether the assistant should be promoted to the main version. Defaults to true. tags: Tags associated with the assistant. Tags can also be managed with the assistant tag endpoints. tool_ids: IDs of shared tools to attach to the assistant. New integrations should prefer `tool_ids` over inline `tools`. On update, a sent `tool_ids` array fully replaces the assistant's attached shared tools; omit the field to leave them unchanged. Single-instance tool types are counted across inline `tools` and `tool_ids` combined, so attaching a shared tool of such a type when an instance already exists returns HTTP 400 with error code 10015. tools: Deprecated for new integrations. Inline tool definitions available to the assistant. Prefer `tool_ids` to attach shared tools created with the AI Tools endpoints. On update, a sent `tools` array fully replaces the assistant's inline tools; omit the field to leave the inline tools unchanged. Each tool type except `function`, `webhook`, and `client_side_tool` allows at most one instance per assistant, counted across inline `tools` and shared `tool_ids` combined — sending a duplicate of such a type returns HTTP 400 with error code 10015. Responses merge shared tools into `tools` with `shared: true`; when updating, omit those tools from the `tools` array and manage them through `tool_ids` instead. version_name: Human-readable name for the assistant version. websocket_settings: Streams conversation and telephony events to a WebSocket server you host, and accepts messages injected back into the conversation. Telnyx opens the connection as a client, once per conversation. Delivery is best effort throughout: while the connection is down events are dropped rather than queued, and no socket failure is ever allowed to affect the call. Beta feature. widget_settings: Configuration settings for the assistant's web widget. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return await self._post( path_template("/ai/assistants/{assistant_id}", assistant_id=assistant_id), body=await async_maybe_transform( { "a2a_agents": a2a_agents, "avatar_settings": avatar_settings, "conversation_flow": conversation_flow, "delegation_settings": delegation_settings, "description": description, "dynamic_variables": dynamic_variables, "dynamic_variables_webhook_timeout_ms": dynamic_variables_webhook_timeout_ms, "dynamic_variables_webhook_url": dynamic_variables_webhook_url, "enabled_features": enabled_features, "external_llm": external_llm, "fallback_config": fallback_config, "greeting": greeting, "insight_settings": insight_settings, "instructions": instructions, "integrations": integrations, "interruption_settings": interruption_settings, "llm_api_key_ref": llm_api_key_ref, "mcp_servers": mcp_servers, "messaging_settings": messaging_settings, "model": model, "name": name, "observability_settings": observability_settings, "post_conversation_settings": post_conversation_settings, "privacy_settings": privacy_settings, "promote_to_main": promote_to_main, "tags": tags, "telephony_settings": telephony_settings, "tool_ids": tool_ids, "tools": tools, "transcription": transcription, "version_name": version_name, "voice_settings": voice_settings, "websocket_settings": websocket_settings, "widget_settings": widget_settings, }, assistant_update_params.AssistantUpdateParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=InferenceEmbedding, ) async def list( self, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantsList: """Retrieve a list of all AI Assistants configured by the user.""" return await self._get( "/ai/assistants", options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantsList, ) async def delete( self, assistant_id: str, *, hard_delete: bool | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantDeleteResponse: """ Delete an AI Assistant by `assistant_id`. By default this performs a soft delete: the assistant moves to the Recently Deleted list and stays restorable for 30 days, after which it is permanently deleted automatically. The assistant's versions and TeXML application are preserved during the retention window. Pass `hard_delete=true` to skip the retention window and permanently delete the assistant immediately. A hard delete erases the assistant and all of its versions, and deletes its TeXML application unless phone numbers are still assigned to it. It does not delete conversations, recordings, shared tools the assistant referenced, or knowledge-base embeddings. Deletion fails with `400` if other assistants reference this one through a handoff tool or a conversation-flow edge — remove those references first. Args: hard_delete: Permanently delete the assistant immediately instead of soft-deleting it to the Recently Deleted list, where it stays restorable for 30 days. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return await self._delete( path_template("/ai/assistants/{assistant_id}", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout, query=await async_maybe_transform( {"hard_delete": hard_delete}, assistant_delete_params.AssistantDeleteParams ), ), cast_to=AssistantDeleteResponse, ) async def chat( self, assistant_id: str, *, content: str, conversation_id: str, name: str | Omit = omit, stream: bool | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantChatResponse: """ This endpoint allows a client to send a chat message to a specific AI Assistant. The assistant processes the message and returns a relevant reply based on the current conversation context. Refer to the Conversation API to [create a conversation](https://developers.telnyx.com/api-reference/conversations/create-a-conversation), [filter existing conversations](https://developers.telnyx.com/api-reference/conversations/list-conversations), [fetch messages for a conversation](https://developers.telnyx.com/api-reference/conversations/get-conversation-messages), and [manually add messages to a conversation](https://developers.telnyx.com/api-reference/conversations/create-message). Args: content: The message content sent by the client to the assistant conversation_id: A unique identifier for the conversation thread, used to maintain context name: The optional display name of the user sending the message stream: When true, the response is streamed as Server-Sent Events (`text/event-stream`): `delta` events carry content fragments as they are generated, a final `done` event carries the full content plus `whatsapp_template`, and a terminal `error` event reports failures that happen after streaming started. When false (default), the response is a single JSON object. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return await self._post( path_template("/ai/assistants/{assistant_id}/chat", assistant_id=assistant_id), body=await async_maybe_transform( { "content": content, "conversation_id": conversation_id, "name": name, "stream": stream, }, assistant_chat_params.AssistantChatParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantChatResponse, ) async def clone( self, assistant_id: str, *, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Clone an existing assistant, excluding telephony and messaging settings. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return await self._post( path_template("/ai/assistants/{assistant_id}/clone", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=InferenceEmbedding, ) async def get_texml( self, assistant_id: str, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> str: """ Get an assistant texml by `assistant_id`. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return await self._get( path_template("/ai/assistants/{assistant_id}/texml", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=str, ) async def imports( self, *, api_key_ref: str, provider: Literal["elevenlabs", "vapi", "retell"], import_ids: SequenceNotStr[str] | Omit = omit, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantsList: """Import assistants from external providers. Any assistant that has already been imported will be overwritten with its latest version from the importing provider. Args: api_key_ref: Integration secret pointer that refers to the API key for the external provider. This should be an identifier for an integration secret created via /v2/integration_secrets. provider: The external provider to import assistants from. import_ids: Optional list of assistant IDs to import from the external provider. If not provided, all assistants will be imported. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return await self._post( "/ai/assistants/import", body=await async_maybe_transform( { "api_key_ref": api_key_ref, "provider": provider, "import_ids": import_ids, }, assistant_imports_params.AssistantImportsParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantsList, ) async def restore( self, assistant_id: str, *, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> InferenceEmbedding: """ Restore a soft-deleted assistant from the Recently Deleted list. The assistant becomes fully active again with its versions and TeXML application as they were at deletion time. Restoring does not re-enable numbers or connections that were released separately after the deletion. Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") return await self._post( path_template("/ai/assistants/{assistant_id}/restore", assistant_id=assistant_id), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=InferenceEmbedding, ) async def send_sms( self, assistant_id: str, *, from_: str, to: str, conversation_metadata: Dict[str, Union[str, int, bool]] | Omit = omit, should_create_conversation: bool | Omit = omit, text: str | Omit = omit, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantSendSMSResponse: """Send an SMS message for an assistant. This endpoint: 1. Validates the assistant exists and has messaging profile configured 2. If should_create_conversation is true, creates a new conversation with metadata 3. Sends the SMS message (If `text` is set, this will be sent. Otherwise, if this is the first message in the conversation and the assistant has a `greeting` configured, this will be sent. Otherwise the assistant will generate the text to send.) 4. Updates conversation metadata if provided 5. Returns the conversation ID Args: extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return await self._post( path_template("/ai/assistants/{assistant_id}/chat/sms", assistant_id=assistant_id), body=await async_maybe_transform( { "from_": from_, "to": to, "conversation_metadata": conversation_metadata, "should_create_conversation": should_create_conversation, "text": text, }, assistant_send_sms_params.AssistantSendSMSParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantSendSMSResponse, ) async def whatsapp( self, assistant_id: str, *, content: str, from_: str, to: str, conversation_metadata: Dict[str, Union[str, int, bool]] | Omit = omit, idempotency_key: str | Omit = omit, # Use the following arguments if you need to pass additional parameters to the API that aren't available via kwargs. # The extra values given here take precedence over values defined on the client or passed to this method. extra_headers: Headers | None = None, extra_query: Query | None = None, extra_body: Body | None = None, timeout: float | httpx.Timeout | None | NotGiven = not_given, ) -> AssistantWhatsappResponse: """Start a WhatsApp conversation with a customer from the business side. This endpoint: 1. Validates that `from` is a WhatsApp number on your account whose messaging profile has this assistant configured 2. Creates a new `whatsapp_chat` conversation with the provided metadata 3. Asks the assistant to pick one of its approved WhatsApp templates and fill its variables from `content` 4. Sends the template from `from` to `to` 5. Returns the conversation ID and the message ID When the customer replies, the reply is routed to the same conversation and the assistant answers within the 24-hour customer service window. The assistant needs a `whatsapp_template` tool with at least one approved template, data retention enabled and PII redaction disabled. Args: content: Instruction for the assistant, including the values for the template variables, e.g. `Send the login verification code 482913 to the customer.` from_: WhatsApp number on your account to send from, in E.164 format. Its messaging profile must have this assistant configured. to: Customer to message, as an E.164 phone number or a WhatsApp business-scoped user ID (BSUID). conversation_metadata: Metadata stored on the conversation. Keys starting with `telnyx_` and the `assistant_id` key are reserved. extra_headers: Send extra headers extra_query: Add additional query parameters to the request extra_body: Add additional JSON properties to the request timeout: Override the client-level default timeout for this request, in seconds """ if not assistant_id: raise ValueError(f"Expected a non-empty value for `assistant_id` but received {assistant_id!r}") extra_headers = {**strip_not_given({"Idempotency-Key": idempotency_key}), **(extra_headers or {})} return await self._post( path_template("/ai/assistants/{assistant_id}/chat/whatsapp", assistant_id=assistant_id), body=await async_maybe_transform( { "content": content, "from_": from_, "to": to, "conversation_metadata": conversation_metadata, }, assistant_whatsapp_params.AssistantWhatsappParams, ), options=make_request_options( extra_headers=extra_headers, extra_query=extra_query, extra_body=extra_body, timeout=timeout ), cast_to=AssistantWhatsappResponse, ) class AssistantsResourceWithRawResponse: def __init__(self, assistants: AssistantsResource) -> None: self._assistants = assistants self.create = to_raw_response_wrapper( assistants.create, ) self.retrieve = to_raw_response_wrapper( assistants.retrieve, ) self.update = to_raw_response_wrapper( assistants.update, ) self.list = to_raw_response_wrapper( assistants.list, ) self.delete = to_raw_response_wrapper( assistants.delete, ) self.chat = to_raw_response_wrapper( assistants.chat, ) self.clone = to_raw_response_wrapper( assistants.clone, ) self.get_texml = to_raw_response_wrapper( assistants.get_texml, ) self.imports = to_raw_response_wrapper( assistants.imports, ) self.restore = to_raw_response_wrapper( assistants.restore, ) self.send_sms = to_raw_response_wrapper( assistants.send_sms, ) self.whatsapp = to_raw_response_wrapper( assistants.whatsapp, ) @cached_property def tests(self) -> TestsResourceWithRawResponse: """Configure AI assistant specifications""" return TestsResourceWithRawResponse(self._assistants.tests) @cached_property def canary_deploys(self) -> CanaryDeploysResourceWithRawResponse: """Configure AI assistant specifications""" return CanaryDeploysResourceWithRawResponse(self._assistants.canary_deploys) @cached_property def scheduled_events(self) -> ScheduledEventsResourceWithRawResponse: """Configure AI assistant specifications""" return ScheduledEventsResourceWithRawResponse(self._assistants.scheduled_events) @cached_property def tools(self) -> ToolsResourceWithRawResponse: """Configure AI assistant specifications""" return ToolsResourceWithRawResponse(self._assistants.tools) @cached_property def versions(self) -> VersionsResourceWithRawResponse: """Configure AI assistant specifications""" return VersionsResourceWithRawResponse(self._assistants.versions) @cached_property def tags(self) -> TagsResourceWithRawResponse: """Configure AI assistant specifications""" return TagsResourceWithRawResponse(self._assistants.tags) @cached_property def instructions(self) -> InstructionsResourceWithRawResponse: """Configure AI assistant specifications""" return InstructionsResourceWithRawResponse(self._assistants.instructions) @cached_property def deleted(self) -> DeletedResourceWithRawResponse: """Configure AI assistant specifications""" return DeletedResourceWithRawResponse(self._assistants.deleted) class AsyncAssistantsResourceWithRawResponse: def __init__(self, assistants: AsyncAssistantsResource) -> None: self._assistants = assistants self.create = async_to_raw_response_wrapper( assistants.create, ) self.retrieve = async_to_raw_response_wrapper( assistants.retrieve, ) self.update = async_to_raw_response_wrapper( assistants.update, ) self.list = async_to_raw_response_wrapper( assistants.list, ) self.delete = async_to_raw_response_wrapper( assistants.delete, ) self.chat = async_to_raw_response_wrapper( assistants.chat, ) self.clone = async_to_raw_response_wrapper( assistants.clone, ) self.get_texml = async_to_raw_response_wrapper( assistants.get_texml, ) self.imports = async_to_raw_response_wrapper( assistants.imports, ) self.restore = async_to_raw_response_wrapper( assistants.restore, ) self.send_sms = async_to_raw_response_wrapper( assistants.send_sms, ) self.whatsapp = async_to_raw_response_wrapper( assistants.whatsapp, ) @cached_property def tests(self) -> AsyncTestsResourceWithRawResponse: """Configure AI assistant specifications""" return AsyncTestsResourceWithRawResponse(self._assistants.tests) @cached_property def canary_deploys(self) -> AsyncCanaryDeploysResourceWithRawResponse: """Configure AI assistant specifications""" return AsyncCanaryDeploysResourceWithRawResponse(self._assistants.canary_deploys) @cached_property def scheduled_events(self) -> AsyncScheduledEventsResourceWithRawResponse: """Configure AI assistant specifications""" return AsyncScheduledEventsResourceWithRawResponse(self._assistants.scheduled_events) @cached_property def tools(self) -> AsyncToolsResourceWithRawResponse: """Configure AI assistant specifications""" return AsyncToolsResourceWithRawResponse(self._assistants.tools) @cached_property def versions(self) -> AsyncVersionsResourceWithRawResponse: """Configure AI assistant specifications""" return AsyncVersionsResourceWithRawResponse(self._assistants.versions) @cached_property def tags(self) -> AsyncTagsResourceWithRawResponse: """Configure AI assistant specifications""" return AsyncTagsResourceWithRawResponse(self._assistants.tags) @cached_property def instructions(self) -> AsyncInstructionsResourceWithRawResponse: """Configure AI assistant specifications""" return AsyncInstructionsResourceWithRawResponse(self._assistants.instructions) @cached_property def deleted(self) -> AsyncDeletedResourceWithRawResponse: """Configure AI assistant specifications""" return AsyncDeletedResourceWithRawResponse(self._assistants.deleted) class AssistantsResourceWithStreamingResponse: def __init__(self, assistants: AssistantsResource) -> None: self._assistants = assistants self.create = to_streamed_response_wrapper( assistants.create, ) self.retrieve = to_streamed_response_wrapper( assistants.retrieve, ) self.update = to_streamed_response_wrapper( assistants.update, ) self.list = to_streamed_response_wrapper( assistants.list, ) self.delete = to_streamed_response_wrapper( assistants.delete, ) self.chat = to_streamed_response_wrapper( assistants.chat, ) self.clone = to_streamed_response_wrapper( assistants.clone, ) self.get_texml = to_streamed_response_wrapper( assistants.get_texml, ) self.imports = to_streamed_response_wrapper( assistants.imports, ) self.restore = to_streamed_response_wrapper( assistants.restore, ) self.send_sms = to_streamed_response_wrapper( assistants.send_sms, ) self.whatsapp = to_streamed_response_wrapper( assistants.whatsapp, ) @cached_property def tests(self) -> TestsResourceWithStreamingResponse: """Configure AI assistant specifications""" return TestsResourceWithStreamingResponse(self._assistants.tests) @cached_property def canary_deploys(self) -> CanaryDeploysResourceWithStreamingResponse: """Configure AI assistant specifications""" return CanaryDeploysResourceWithStreamingResponse(self._assistants.canary_deploys) @cached_property def scheduled_events(self) -> ScheduledEventsResourceWithStreamingResponse: """Configure AI assistant specifications""" return ScheduledEventsResourceWithStreamingResponse(self._assistants.scheduled_events) @cached_property def tools(self) -> ToolsResourceWithStreamingResponse: """Configure AI assistant specifications""" return ToolsResourceWithStreamingResponse(self._assistants.tools) @cached_property def versions(self) -> VersionsResourceWithStreamingResponse: """Configure AI assistant specifications""" return VersionsResourceWithStreamingResponse(self._assistants.versions) @cached_property def tags(self) -> TagsResourceWithStreamingResponse: """Configure AI assistant specifications""" return TagsResourceWithStreamingResponse(self._assistants.tags) @cached_property def instructions(self) -> InstructionsResourceWithStreamingResponse: """Configure AI assistant specifications""" return InstructionsResourceWithStreamingResponse(self._assistants.instructions) @cached_property def deleted(self) -> DeletedResourceWithStreamingResponse: """Configure AI assistant specifications""" return DeletedResourceWithStreamingResponse(self._assistants.deleted) class AsyncAssistantsResourceWithStreamingResponse: def __init__(self, assistants: AsyncAssistantsResource) -> None: self._assistants = assistants self.create = async_to_streamed_response_wrapper( assistants.create, ) self.retrieve = async_to_streamed_response_wrapper( assistants.retrieve, ) self.update = async_to_streamed_response_wrapper( assistants.update, ) self.list = async_to_streamed_response_wrapper( assistants.list, ) self.delete = async_to_streamed_response_wrapper( assistants.delete, ) self.chat = async_to_streamed_response_wrapper( assistants.chat, ) self.clone = async_to_streamed_response_wrapper( assistants.clone, ) self.get_texml = async_to_streamed_response_wrapper( assistants.get_texml, ) self.imports = async_to_streamed_response_wrapper( assistants.imports, ) self.restore = async_to_streamed_response_wrapper( assistants.restore, ) self.send_sms = async_to_streamed_response_wrapper( assistants.send_sms, ) self.whatsapp = async_to_streamed_response_wrapper( assistants.whatsapp, ) @cached_property def tests(self) -> AsyncTestsResourceWithStreamingResponse: """Configure AI assistant specifications""" return AsyncTestsResourceWithStreamingResponse(self._assistants.tests) @cached_property def canary_deploys(self) -> AsyncCanaryDeploysResourceWithStreamingResponse: """Configure AI assistant specifications""" return AsyncCanaryDeploysResourceWithStreamingResponse(self._assistants.canary_deploys) @cached_property def scheduled_events(self) -> AsyncScheduledEventsResourceWithStreamingResponse: """Configure AI assistant specifications""" return AsyncScheduledEventsResourceWithStreamingResponse(self._assistants.scheduled_events) @cached_property def tools(self) -> AsyncToolsResourceWithStreamingResponse: """Configure AI assistant specifications""" return AsyncToolsResourceWithStreamingResponse(self._assistants.tools) @cached_property def versions(self) -> AsyncVersionsResourceWithStreamingResponse: """Configure AI assistant specifications""" return AsyncVersionsResourceWithStreamingResponse(self._assistants.versions) @cached_property def tags(self) -> AsyncTagsResourceWithStreamingResponse: """Configure AI assistant specifications""" return AsyncTagsResourceWithStreamingResponse(self._assistants.tags) @cached_property def instructions(self) -> AsyncInstructionsResourceWithStreamingResponse: """Configure AI assistant specifications""" return AsyncInstructionsResourceWithStreamingResponse(self._assistants.instructions) @cached_property def deleted(self) -> AsyncDeletedResourceWithStreamingResponse: """Configure AI assistant specifications""" return AsyncDeletedResourceWithStreamingResponse(self._assistants.deleted)