Skip to main content
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:
log.info(f"Conversation ID: {conv.id}")
# Example output: "conv_abc123xyz789"
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:
log.info(f"Account: {conv.account_id}")
# Example output: "acc_abc123"
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:
log.info(f"Project ID: {conv.project_id}")
# Example output: "proj_abc123"

if conv.project_id == "proj_123":
  print("Running in the main deployment")
Description: Current environment.Values: “sandbox”, “pre-release”, “live”Example:
if conv.env == "live":
  log.info("Production traffic")
Description: Type of channel the conversation is taking place on.Possible values:
  • "VOICE" – Voice calls (telephony)
  • "sms" – SMS text messages
  • "sip.polyai" – SIP-based voice calls
  • Integration-specific identifiers (e.g., "webchat.polyai", "chat.polyai")
Example:
if conv.channel_type == "VOICE":
  log.info("Running a voice call")
elif conv.channel_type == "sms":
  log.info("Running an SMS conversation")
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:
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")
Description: Dictionary of SIP headers (dict[str, str]) provided by the carrier.Example:
source_ip = conv.sip_headers.get("X-Src-IP")
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:
# In start_function
if shared_id := conv.integration_attributes.get("shared_id"):
  conv.state.shared_id = shared_id
  log.info(f\"Tracking with shared_id: {shared_id}\")\n    else:
  # Handle missing integration data
  log.warning(\"No shared_id provided by integration\")
Description: Combined payload of integration metadata and attributes (dict[str, Any]).Example:
crm_id = conv.integration_data.get("contact_id")
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:
identifier = conv.caller_number
log.info(f"Caller identity: {identifier}")
# Inbound example: "+14155551234"
# Chat example: "user@example.com"
Description: Number dialled by the caller.Example:
if conv.callee_number.endswith("1001"):
  conv.state.branch = "Priority"
Description: Dictionary-like store that persists values across turns.Example:
conv.state["attempts"] = conv.state.get("attempts", 0) + 1
Description: Name of the flow currently executing, or None.
Description: Step name currently executing within the active flow.Example:
log.info(f"Current step: {conv.current_step}")
Description: List of OutgoingSMS / OutgoingSMSTemplate objects queued for dispatch at turn end.
Description: List of custom metrics queued for analytics.
Description: List of metric event objects queued for analytics.Example:
for metric in conv.metric_events:
  print(metric.name, metric.value)
Description: Name of the active variant, or None.
Description: Dictionary of all variant definitions (dict[str, Variant]).
Description: Variant object for the active variant, or None.Example:
if conv.variant:
  print(conv.variant.description)
Description: Dictionary of SMS templates (dict[str, SMSTemplate]).Example:
template_body = conv.sms_templates["booking_confirmation"].content
Description: Pending TTSVoice change requested this turn, or None.
Description: ISO-639 language code configured for the project (e.g. “en”).
Description: Chronological list of UserInput and AgentResponse events so far.Example:
for event in conv.history:
  print(event.speaker, event.timestamp, event.text)

# Example output:
# user 2024-01-15T10:30:00Z "I need to book a table"
# agent 2024-01-15T10:30:02Z "I'd be happy to help you book a table"
# user 2024-01-15T10:30:05Z "For 4 people at 7pm"
Description: Dictionary of configured hand-off destinations (dict[str, HandoffConfig]).Example:
if "support" in conv.handoffs:
  print("Support line is available")
Description: List of ASR alternatives for the last user utterance. Each alternative includes the transcribed text and a confidence score.Example:
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
Description: Returns a dictionary of real-time configuration values defined in Configuration Builder.Example:
config = conv.real_time_config
if config.get("after_hours_enabled"):
  conv.say("Our offices are currently closed.")
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:
cheese = conv.memory.get("cheese_type")
if cheese:
  conv.say(f"You're a fan of {cheese}, right?")

# Check if this is a returning customer
if conv.memory.get("last_order_date"):
  conv.say("Welcome back!")
Description: Dictionary of entity validation results collected from the conversation (dict[str, EntityValidationResult]).Example:
if "email" in conv.entities:
  validated_email = conv.entities.email
Description: Executor for calling other functions defined in the project. Access functions using dot notation.Example:
result = conv.functions.lookup_order()
Description: Executor for calling configured API integrations. Access APIs using conv.api.{integration_name}.{operation_name}(). Example:
response = conv.api.salesforce.get_contact(user_id="123")
if response.status_code == 200:
  contact_data = response.json()
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:
for event in conv.generic_external_events:
  if event.data:
    log.info(f"Received webhook data: {event.data}")
Description: Proxy for accessing localized translations. Access translation keys as attributes to get the translated text for the current language.Example:
greeting = conv.translations.welcome_message
conv.say(greeting)
Description: List of quick-reply suggestions for the next agent message. Only supported on webchat channels.Example:
for suggestion in conv.response_suggestions:
  print(suggestion)
Description: Agentic dial data for the conversation, used for advanced dialing scenarios.

Methods

Description: Override the next utterance.Example:
conv.say("I’ve made that change for you.")
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 poly.voice module (e.g., ElevenLabsVoice, CartesiaVoice, PlayHTVoice, RimeVoice). See Voice Selection docs for the full list of available voices and their IDs.Example:
from poly import VoiceWeighting
from poly.voice import Voices

conv.randomize_voice([
  VoiceWeighting(voice=Voices.en_male_calm, weight=70), 
  VoiceWeighting(voice=Voices.en_female_warm, weight=30)
])
Description: Transition to another flow at turn end.Example:
conv.goto_flow("verification")
Description: Exit the current flow.Example:
conv.exit_flow()
Description: Manually set the active variant.Example:
conv.set_variant("evening")
Description: Attach one or more files to the current conversation record.Example:
conv.add_attachments([{"url": "https://example.com/invoice.pdf", "filename": "invoice.pdf"}])
Description: Prevents saving the current call recording, e.g. when sensitive data is detected.Example:
if conv.state.get("contains_pii"):
  conv.discard_recording()
Description: Sends a structured webhook event to the configured external endpoint.Example:
conv.generate_external_events("booking_completed", payload={"id": "1234"})
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:
response = requests.get("https://api.example.com/user")
conv.log_api_response(response)
# Response will appear in Conversation Review → Diagnosis
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:
conv.send_whatsapp(to="+441234567890", content="Hello from PolyAI!")
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:
conv.send_content_template(
  to="+441234567890", 
  template="order_update", 
  parameters={"order_id": "12345", "status": "shipped"}
)
Description: Queue a plain-text SMS.Example:
conv.send_sms(to_number=conv.caller_number, from_number="+441234567890", content="Thanks for calling — here’s your link: https://…")
Description: Queue a pre-configured SMS template.Example:
conv.send_sms_template(to_number=conv.caller_number, template="booking_confirmation")
Description: Write a custom metric to the analytics pipeline.Example:
conv.write_metric("agent_handoff", 1)
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:
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.
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: These utilities are opt-in and may not be enabled in your workspace. Contact your admin to request access.Example:
address = conv.utils.extract_address(country="US")
name = conv.utils.extract_name()
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:
from polyai.voice import ElevenLabsVoice
conv.set_voice(ElevenLabsVoice(provider_voice_id="abc123"))
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:
conv.set_language("es-US")
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:
conv.set_asr_biasing(
  keywords=["reservation", "booking", "cancel"],
  custom_biases={"reservation": 3.0, "cancellation": 2.5}
)
Description: Clear any previously set ASR biasing for future turns.Example:
conv.clear_asr_biasing()
Description: Trigger a transition to the CSAT (Customer Satisfaction) survey flow for voice calls.Example:
if conv.state.get("call_completed"):
  conv.goto_csat_flow()
Description: Send an email from the function.SMTP configuration: Emails are sent using PolyAI’s managed SMTP service. For custom SMTP servers or advanced delivery requirements, contact your PolyAI support team.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:
conv.send_email(
  to="customer@example.com",
  body="Thank you for your order!",
  subject="Order Confirmation"
)
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:
conv.add_response_suggestions(["Yes, confirm", "No, cancel", "More options"])