The Conversation object, its attributes, and methods.
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.
Description: Unique identifier of the conversation.Example:
Copy
Ask AI
log.info(f"Conversation ID: {conv.id}")# Example output: "conv_abc123xyz789"
account_id
Description: PolyAI account ID that owns this project. This is the same account ID visible in your Studio URL: https://studio.poly.ai/account/{account_id}/...Example:
Copy
Ask AI
log.info(f"Account: {conv.account_id}")# Example output: "acc_abc123"
project_id
Description: Project ID of the current agent. This is the same project ID visible in your Studio URL: https://studio.poly.ai/account/{account_id}/project/{project_id}/...Example:
Copy
Ask AI
log.info(f"Project ID: {conv.project_id}")# Example output: "proj_abc123"if conv.project_id == "proj_123": print("Running in the main deployment")
env
Description: Current environment.Values: “sandbox”, “pre-release”, “live”Example:
Copy
Ask AI
if conv.env == "live": log.info("Production traffic")
channel_type
Description: Type of channel the conversation is taking place on.Possible values:
if conv.channel_type == "VOICE": log.info("Running a voice call")elif conv.channel_type == "sms": log.info("Running an SMS conversation")
attachments
Description: List of file attachments received or queued for sending (list[Attachment]).Attachment object structure:
url (str) – URL where the file is hosted
filename (str) – Name of the file
content_type (str, optional) – MIME type of the file (e.g., “application/pdf”, “image/jpeg”)
size (int, optional) – File size in bytes
Example:
Copy
Ask AI
for file in conv.attachments: print(f"File: {file.filename}") print(f"URL: {file.url}") print(f"Type: {file.content_type}") print(f"Size: {file.size} bytes")
sip_headers
Description: Dictionary of SIP headers (dict[str, str]) provided by the carrier.Example:
Copy
Ask AI
source_ip = conv.sip_headers.get("X-Src-IP")
integration_attributes
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:
Copy
Ask AI
# In start_functionif shared_id := conv.integration_attributes.get("shared_id"): conv.state.shared_id = shared_id log.info(f"Tracking with shared_id: {shared_id}")else: # Handle missing integration data log.warning("No shared_id provided by integration")
integration_data
Description: Combined payload of integration metadata and attributes (dict[str, Any]).Example:
Copy
Ask AI
crm_id = conv.integration_data.get("contact_id")
caller_number
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: Pending TTSVoice change requested this turn, or None.
language
Description: ISO-639 language code configured for the project (e.g. “en”).
history
Description: Chronological list of UserInput and AgentResponse events so far.Example:
Copy
Ask AI
for event in conv.history: print(event.role, event.text)# Example output:# user "I need to book a table"# agent "I'd be happy to help you book a table"# user "For 4 people at 7pm"
handoffs
Description: Dictionary of configured hand-off destinations (dict[str, HandoffConfig]).Example:
Copy
Ask AI
if "support" in conv.handoffs: print("Support line is available")
transcript_alternatives
Description: List of ASR alternatives for the last user utterance. Each alternative includes the transcribed text and a confidence score.Example:
Copy
Ask AI
for alt in conv.transcript_alternatives: print(f"Text: {alt.text}, Confidence: {alt.confidence}")# Example output:# Text: "book a table for two", Confidence: 0.95# Text: "book a table for too", Confidence: 0.78# Text: "book a table for to", Confidence: 0.65
real_time_config
Description: Returns a dictionary of real-time configuration values defined in Configuration Builder.Example:
Copy
Ask AI
config = conv.real_time_configif config.get("after_hours_enabled"): conv.say("Our offices are currently closed.")
memory
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 allows the agent to recognize returning customers and recall previous interactions.Example:
Copy
Ask AI
cheese = conv.memory.get("cheese_type")if cheese: conv.say(f"You're a fan of {cheese}, right?")# Check if this is a returning customerif conv.memory.get("last_order_date"): conv.say("Welcome back!")
entities
Description: Dictionary of entity validation results collected from the conversation (dict[str, EntityValidationResult]).Example:
Copy
Ask AI
if "email" in conv.entities: validated_email = conv.entities.email
functions
Description: Executor for calling other functions defined in the project. Access functions using dot notation.Example:
Copy
Ask AI
result = conv.functions.lookup_order()
api
Description: Executor for calling configured API integrations. Access APIs using conv.api.{integration_name}.{operation_name}().
Example:
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:
Copy
Ask AI
for event in conv.generic_external_events: if event.data: log.info(f"Received webhook data: {event.data}")
translations
Description: Proxy for accessing localized translations. Access translation keys as attributes to get the translated text for the current language.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: 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:
Copy
Ask AI
response = requests.get("https://api.example.com/user")conv.log_api_response(response)# Response will appear in Conversation Review → Diagnosis
send_whatsapp
Description: Sends a plain-text WhatsApp message with the configured WhatsApp Business API integration.Use case: Send simple, unformatted WhatsApp messages.Difference from send_content_template: Use send_whatsapp for plain text messages. Use send_content_template for pre-approved WhatsApp templates with variables, rich media, or buttons.Example:
Copy
Ask AI
conv.send_whatsapp(to="+441234567890", content="Hello from PolyAI!")
send_content_template
Description: Sends a WhatsApp or SMS template message defined in your content templates.Use case: Send pre-approved templates with dynamic variables, rich media (images, videos), or interactive buttons.Difference from send_whatsapp: Use send_content_template for structured messages with variables and rich content. Use send_whatsapp for simple plain-text messages.Example:
Description: Write a custom metric to the analytics pipeline.Example:
Copy
Ask AI
conv.write_metric("agent_handoff", 1)
call_handoff
Description: Transfer the call to a configured handoff destination.
Parameters: destination (str) – handoff target key; reason (str or None) – escalation reason; utterance (str or None) – message before transfer.
Example:
Copy
Ask AI
conv.call_handoff(destination="BillingQueue", reason="policy_violation", utterance="Let me transfer you to a specialist who can help.")
Where it shows up: In flows using builtin-handoff or using functions; visible in Conversation Review and API.
utils
Description: Provides LLM-powered helper functions for extracting and validating structured data from user input.Available utilities:
extract_address() – Extract postal addresses
extract_name() – Extract person names
extract_city() – Extract city references
extract_date() – Extract dates and times
extract_email() – Extract email addresses
extract_phone() – Extract phone numbers
Note: Some utilities require activation. If a method raises a NotImplementedError, contact PolyAI support to enable it for your account.Example:
See Conversation utilities for the full list of available helpers and detailed documentation.
set_voice
Description: Change the TTS voice for the current conversation moving forward.Parameters: voice (TTSVoice) – the voice configuration to use.Example:
Copy
Ask AI
from polyai.voice import ElevenLabsVoiceconv.set_voice(ElevenLabsVoice(provider_voice_id="abc123"))
set_language
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:
Copy
Ask AI
conv.set_language("es-US")
set_asr_biasing
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.
Description: Clear any previously set ASR biasing for future turns.Example:
Copy
Ask AI
conv.clear_asr_biasing()
goto_csat_flow
Description: Trigger a transition to the CSAT (Customer Satisfaction) survey flow for voice calls.Example:
Copy
Ask AI
if conv.state.get("call_completed"): conv.goto_csat_flow()
send_email
Description: Send an email from the function.SMTP configuration: Emails are sent through a managed delivery service. For custom email delivery requirements, contact PolyAI support.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, optional) – subject line.
Example:
Copy
Ask AI
conv.send_email( to="customer@example.com", body="Thank you for your order!", subject="Order Confirmation")
add_response_suggestions
Description: Add 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: