Skip to main content
This page requires Python familiarity. It is a reference for developers writing functions inside Agent Studio. The Conversation object (conv) provides access to conversation data and tools for managing the agent’s behavior. It handles state management, flow transitions, SMS interactions, environment details, and voice selection.

Attributes

Description: Unique identifier of the conversation.Example:
Description: PolyAI account ID (the Workspace ID, prefixed with ws-) that owns this project. This is the same account ID visible in your Studio URL: https://studio.<region>.poly.ai/<account_id>/... (where <region> is us, uk, or eu — Agent Studio is region-specific).Example:
Description: Project ID of the current agent. This is the same project ID visible in your Studio URL: https://studio.<region>.poly.ai/<account_id>/<project_id>/... (where <region> is us, uk, or eu — Agent Studio is region-specific).Example:
Description: Current environment.Values: “sandbox”, “pre-release”, “live”Example:
Description: Type of channel the conversation is taking place on.Possible values:
  • "sip.polyai" – Voice calls (telephony/SIP)
  • "webchat.polyai" – Webchat widget
  • "chat.polyai" – Agent Studio in-browser chat
  • "sms.twilio" – SMS text messages
Use .startswith() for broader matching (e.g., conv.channel_type.startswith("sms")) when you don’t need to distinguish between SMS sub-types.
Example:
Description: List of Attachment objects queued to be included with the next agent message (list[Attachment]). Append to it with conv.add_attachments(...). Attachments are only supported on webchat channels.Attachment object structure:
  • content_url (str) – URL to the main content of the attachment
  • content_type (str) – The type of the attachment ("image", "weblink", or "unspecified")
  • title (str, optional) – Title of the attachment
  • preview_image_url (str, optional) – URL to a preview image for the attachment
  • call_to_action (str, optional) – Text for the call-to-action button or link
Example:
Description: Dictionary of SIP headers (dict[str, str]) provided by the carrier.Example:
Description: Metadata passed from an external integration (dict[str, Any]). These attributes are defined per project and per integration during setup.Supported integrations:
  • DNIs Pooling – Provides shared_id for correlating conversation outcomes
Best practice: Validate and extract required attributes in the start_function to handle missing data appropriately.Example:
Description: The caller’s identifier.For inbound calls: The phone number of the person calling in, in E.164 format (e.g., +14155551234 for USA numbers).For outbound calls: The phone number being called by the agent.For chat channels: This may be an email address or integration-provided user ID.Example:
Description: Number dialled by the caller.Example:
Description: Dictionary-like store that persists values across turns. Validated entities are also written here under their entity name, coerced to their native Python type (int for numeric/quantity entities, float for decimal numerics and currency, str for everything else).Access patterns: conv.state supports both bracket and attribute access — pick whichever reads more clearly. Reads and writes behave identically across the two styles:
Missing-key behavior differs by access style:
  • conv.state["missing_key"] raises KeyError.
  • conv.state.missing_key returns None — it does not raise AttributeError.
  • conv.state.get("missing_key") returns None (or your default).
This means if conv.state.is_verified == False: is not the same as “missing or False” — when the key is missing the value is None, and None == False is False, so the branch is skipped. Prefer if not conv.state.get("is_verified"): to treat missing and falsy the same way.
Example:
Description: Name of the flow currently executing, or None.
Description: Step name currently executing in the active flow.Example:
Description: List of OutgoingSMS / OutgoingSMSTemplate objects queued for dispatch at turn end.
Description: Name of the active variant, or None.
Description: Dictionary of all variant definitions (dict[str, Variant]). Each key is the variant name and each value is a Variant object whose attributes match the columns defined in Knowledge > Variants.Example:
Description: Variant object for the active variant, or None if no variant has been set. Attribute values are returned as strings (the storage type used by Variants) — parse them yourself if you need structured data. Reading an attribute that doesn’t exist on the active variant returns None, not an AttributeError.Example:
Description: Dictionary of SMS templates (dict[str, SMSTemplate]).Example:
Description: Pending TTSVoice change requested this turn, or None.
Description: Language code configured for the project, which may include a locale suffix (e.g. “en-US”, “en-GB”, “es-ES”).
Description: Chronological list of UserInput and AgentResponse events so far.Example:
Description: Dictionary of configured hand-off destinations (dict[str, HandoffConfig]).Example:
Description: List of transcription alternatives (list[str]) for the last user utterance, including the primary transcription.Example:
Description: Returns a dictionary of real-time configuration values defined in Configuration Builder.Example:
Description: Dictionary of memory fields previously stored for the caller, retrieved from Agent Memory.Customer identification: Memory is retrieved using caller_number for voice calls or the integration-provided user identifier for chat channels. This lets the agent recognize returning customers and recall previous interactions.Example:
Description: Dictionary of entity validation results collected from the conversation (dict[str, EntityValidationResult]). Each result’s .value is the raw string captured from the caller.For a typed value (int, float, or str) read the entity from conv.state instead — validated entities are auto-synced there under their entity name.Example:
Description: Executor for calling other functions defined in the project. Access functions using dot notation.Example:
Description: Executor for calling configured API integrations. Access APIs using conv.api.{integration_name}.{operation_name}(). Example:
Description: Executor for calling pre-built third-party integrations (e.g., OpenTable, Tripleseat) configured from Integrations. Access using conv.integrations.{integration_name}.{method}().
conv.integrations is for integrations PolyAI has built and maintains (proxied through Paragon). For custom HTTP APIs you define yourself in the APIs tab, use conv.api.
Example:
See Integrations for the list of available integrations and setup instructions.
Description: Webchat-specific interface for functionality that only applies on webchat.polyai channels. Access webchat-only methods via conv.webchat.{method}().Available methods:
  • set_chat_call_actions(actions) – attach click-to-call buttons to the next agent message.
Example:
Calling webchat methods on non-webchat channels has no effect on the conversation, but you should still gate them on conv.channel_type for clarity.
Description: List of external events initiated by generate_external_event. Each event contains ext_event_id, send_to_llm, created_at, data, and content_type.Example:
Description: Proxy for accessing localized translations. Access translation keys as attributes to get the translated text for the current language.Example:
Description: List of quick-reply suggestions for the next agent message. Only supported on webchat channels.Example:
Description: Agentic dial data for the conversation, used for advanced dialing scenarios.

Methods

Description: Override the next utterance.Example:
Description: Randomly choose a voice based on weighted probabilities.Parameters:
  • voice_weightings (list[VoiceWeighting]) – list of VoiceWeighting objects, each containing a voice and weight.
Available voices: Import from polyai.voice module (e.g., ElevenLabsVoice, CartesiaVoice, PlayHTVoice, RimeVoice). See Voice classes for the full list of available voices and their IDs.Example:
Description: Transition to another flow at turn end.Example:
Description: Exit the current flow.Example:
Description: Manually set the active variant.Example:
Description: Attach one or more visual tiles (images or web links) to the conversation. Only supported on webchat channels.Parameters: attachments (list[Attachment]) – list of Attachment objects.Attachment fields:
  • content_url (str) – URL to the main content of the attachment
  • content_type (str) – The type of the attachment ("image", "weblink", or "unspecified")
  • title (str, optional) – Title of the attachment
  • preview_image_url (str, optional) – URL to a preview image for the attachment
  • call_to_action (str, optional) – Text for the call-to-action button or link
Attachment types:
  • "weblink" – Displays the title, preview image, and call-to-action text. Clicking navigates the user to content_url.
  • "image" – Displays the title (if present), but no call-to-action. preview_image_url should be a lower resolution image, and content_url should be the full resolution image. Clicking shows the higher resolution version.
  • "unspecified" – No specific rendering behaviour is applied.
Example:
Description: Prevents saving the current call recording, e.g. when sensitive data is detected.Example:
Description: Generates a unique external event ID linked to the current conversation. Use this ID to receive webhook data from an external provider through the /v1/external-events/webhook endpoint. The webhook payload is then accessible through conv.generic_external_events.Parameters:
  • send_to_llm (bool, keyword-only, optional) – if True, the webhook payload is also sent to the LLM as a system prompt. Default False.
Returns: str – the generated external event ID (expires after 1 hour).Example:
Description: Logs an external API response for visibility in Conversation Review → Diagnosis and the analytics pipeline.Where logs appear:
  • Conversation Review: View API responses in the Diagnosis tab for debugging
  • Analytics pipeline: API response data is available for reporting and analysis
Example:
Description: Sends a WhatsApp message through a Twilio subaccount. Both the sender phone number and the message template must be pre-approved by Meta. Once approved, Twilio provides a content_id that must be referenced when sending.
WhatsApp messaging requires a configured Twilio integration and is not a native PolyAI channel. Contact your PolyAI representative for setup.
Parameters:
  • to_number (str) – recipient phone number.
  • from_number (str) – sender phone number (must be WhatsApp-enabled in Twilio).
  • content_id (str) – alphanumeric ID of the approved WhatsApp message template.
  • content (str, optional) – text content. Default "".
  • retry_count (int, optional) – number of retries to attempt on failure.
Example:
For richer templating with variables, use send_content_template with whatsapp=True.
Description: Sends a WhatsApp or SMS template message through Twilio’s Content API. Requires the content template to be pre-approved in your Twilio account.
WhatsApp messaging requires a configured Twilio integration and is not a native PolyAI channel. Contact your PolyAI representative for setup.
Parameters:
  • messaging_service_id (str) – Twilio messaging service ID.
  • to_number (str) – recipient phone number.
  • content_id (str) – alphanumeric ID of the approved message template.
  • content (str, optional) – text content. Default "".
  • whatsapp (bool, optional) – set to True to send over WhatsApp. Default False.
  • content_variables (dict, optional) – variables to pass to the message template.
Example:
Description: Queue a plain-text SMS.Example:
Description: Queue a pre-configured SMS template.Example:
Description: Write a custom metric to the analytics pipeline. This is the only way custom metrics are recorded for a conversation – the agent does not write them automatically at runtime, so you must call write_metric explicitly from a function whenever you want a metric value captured.Parameters:
  • name (str) – metric key, as defined in your project’s metrics configuration.
  • value (str, int, float, bool, or None) – the metric value. Must match the type defined in the metric spec.
  • write_once (bool, optional) – if True, the metric can only be written once per conversation. Subsequent calls with the same name are ignored. Default False.
Example:
Description: Transfer the call to a configured handoff destination.Parameters:
  • destination (str) – handoff target key, as defined in your handoff configuration.
  • reason (str, optional) – escalation reason. Defaults to the destination name.
  • utterance (str, optional) – message for the agent to say before transferring.
  • sip_headers (dict[str, str], optional) – SIP headers to pass through. Merged with any headers configured in the handoff config, with passed headers taking precedence.
  • route (str, optional) – phone number or route to override the configured route.
Example:
Where it shows up: In flows using builtin-handoff or using functions; visible in Conversation Review and API.
Description: Provides helper functions for extracting data, validating entities, and accessing secrets.Available utilities:
  • get_secret(name) – Retrieve a stored secret by name
  • extract_address() – Extract postal addresses from user input
  • extract_city() – Extract city references from user input
  • prompt_llm() – Perform a standalone LLM request
  • validate_entity() – Validate a value against an entity config (email, phone, date, etc.)
Note: Some utilities require activation. If a method raises a NotImplementedError, contact your PolyAI representative to enable it for your account.Example:
See Conversation utilities for the full list of available helpers and detailed documentation.
Description: Change the TTS voice for the current conversation moving forward.Parameters: voice (TTSVoice) – the voice configuration to use.Example:
Description: Change the language for the current conversation moving forward.Parameters: language (str) – ISO 639 language code (e.g., “en-US”, “es-ES”, “fr-FR”).Example:
Description: Dynamically configure ASR keywords and custom biases for improved speech recognition. Biasing persists across turns until cleared. Parameters:
  • keywords (list[str], optional) – list of keywords to bias ASR recognition toward.
  • custom_biases (dict[str, float], optional) – dictionary mapping phrases to bias weights. Example:
Description: Clear any previously set ASR biasing for future turns.Example:
Description: Exclude one or more FAQs from RAG retrieval for the rest of the conversation. Useful when an upstream IVR or runtime context means certain topics should not be matched. The list persists across turns until cleared or replaced. See Disable KB topics for full details.Parameters:
  • topics (list[str]) – Managed Topic names to disable. Replaces any previously disabled list.
Example:
Description: Re-enable any FAQs that were previously disabled with conv.disable_kb_topics().Example:
Description: Trigger a transition to the CSAT (Customer Satisfaction) survey flow for voice calls.Example:
Description: Override whether the conversation is eligible for a CSAT survey. When eligible=False, the conversation is excluded from CSAT regardless of call type, percentage rollout, or weekly caps. When eligible=True or this method isn’t called, normal CSAT logic applies.Parameters:
  • eligible (bool) – whether the conversation is eligible for CSAT.
  • reason (str, optional) – reason for the decision (logged for debugging).
Example:
Description: Override the phone number used for CSAT SMS surveys. Useful when the real caller number is delivered via a SIP header (e.g., behind an IVR) rather than as the caller ID.Parameters:
  • phone_number (str) – phone number to send the CSAT SMS to, in E.164 format.
Example:
Description: Mark that the caller entered the CSAT survey flow. This is used internally by the platform’s voice CSAT flow for analytics and is not typically called from custom functions.Example:
Description: Send an email from the function.This function sends outbound emails during a conversation (e.g., confirmations or notifications). Email is not a supported inbound channel for PolyAI agents.SMTP configuration: Emails are sent through a managed delivery service. For custom email delivery requirements, contact your PolyAI representative.Delivery considerations:
  • Emails are sent asynchronously after the turn completes
  • Delivery failures are logged but do not interrupt the conversation
  • For high-volume sending, consider rate limits and reputation management
Parameters:
  • to (str) – recipient email address.
  • body (str) – raw body of the email.
  • subject (str) – subject line.
Example:
Description: Set quick-reply suggestions that appear as clickable options for the user. Only supported on webchat channels. Parameters: suggestions (list[str]) – list of suggested responses. Example:
Last modified on June 18, 2026