Twilio Action Block
The Twilio action block enables comprehensive communication through Twilio's platform, supporting SMS messaging, voice calls, WhatsApp messaging, and advanced AI-powered voice agents. This integration allows for automated notifications, interactive voice interviews, and intelligent customer communication.
Features
- SMS Messaging: Send text messages to any phone number globally
- Voice Calls: Make automated voice calls with custom messages
- Voice Agents: AI-powered interactive voice interviews with conditional logic
- WhatsApp Integration: Send messages through WhatsApp Business API
- Variable Integration: Use workflow variables in all message types
- Global Reach: Support for international phone numbers
- Delivery Tracking: Monitor message and call delivery status
- Secure Authentication: Encrypted credential storage
- Real-time Communication: Instant message and call delivery
- Advanced AI Features: LLM-powered conversational agents
Twilio Account Setup
Prerequisites
- Twilio Account: Sign up at twilio.com (opens in a new tab)
- Phone Number: Purchase a Twilio phone number with SMS and Voice capabilities
- API Credentials: Account SID and Auth Token
- Account Verification: Complete account verification process
- Voice Features: Enable voice calling for advanced features
- OpenAI Integration: OpenAI API key for AI voice agents (optional)
Getting Twilio Credentials
-
Access Twilio Console:
- Log in to Twilio Console (opens in a new tab)
- Navigate to Account Dashboard
-
Account SID and Auth Token:
Account SID: ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx Auth Token: your_auth_token_here -
Phone Number:
- Go to Phone Numbers → Manage → Buy a number
- Choose a number with SMS and Voice capabilities
- Configure the number for messaging and voice calls
- Set up webhooks for voice agent functionality
-
Voice Configuration:
- Enable voice calling in your Twilio console
- Configure TwiML applications for voice agents
- Set up webhook URLs for interactive voice responses
Authentication
Adding Twilio Credentials
Configure your Twilio account credentials:
- Credential Name: Descriptive name for the connection
- Account SID: Your Twilio Account SID
- Auth Token: Your Twilio Auth Token
Configuration
Message Type Selection
Choose the communication method for your use case:
- SMS: Text messaging for notifications and alerts
- WhatsApp: Rich messaging through WhatsApp Business API
- Voice: Automated voice calls with pre-recorded messages
- Voice Agent: Interactive AI-powered voice conversations
SMS Configuration
From Number: Your Twilio phone number
Format: +1234567890 (include country code)
Example: +15551234567To Number: Recipient's phone number
Format: +1234567890 (include country code)
Example: +15559876543
Variable: {{customerPhone}}SMS Message: Content to send with variable support
Hi {{customerName}}! Your order #{{orderNumber}} has been shipped.
Track it here: {{trackingUrl}}Voice Call Configuration
From Number: Your Twilio voice-enabled phone number
Format: +1234567890 (include country code)
Example: +15551234567To Number: Recipient's phone number
Format: +1234567890 (include country code)
Example: +15559876543
Variable: {{customerPhone}}Voice Message: Text-to-speech message content
Hello {{customerName}}, this is a reminder about your appointment
scheduled for {{appointmentDate}} at {{appointmentTime}}.
Please call us at {{supportNumber}} if you need to reschedule.Voice Options:
- Voice: Choose from available voices (alice, man, woman)
- Language: Set speech language (en-US, es-ES, fr-FR, etc.)
- Record Call: Option to record the conversation
- Call Timeout: Maximum call duration in seconds
Voice Agent Configuration
Transform your voice calls into intelligent, interactive conversations with AI-powered voice agents.
Agent Types
1. JSON Questions Agent
- Structured interview format with predefined questions
- Sequential or conditional question flow
- Answer validation and retry logic
- Perfect for surveys, interviews, and data collection
2. LLM Agent
- AI-powered conversational agent using OpenAI
- Natural language understanding and responses
- Dynamic conversation flow
- Ideal for customer support and interactive assistance
JSON Questions Agent Setup
Basic Question Structure:
{
id: "name",
question: "What is your full name?",
expectedAnswerType: "text",
maxRetries: 3,
timeout: 10
}Answer Types:
text: Any spoken responsenumber: Numeric answersyes_no: Yes/No questionsmultiple_choice: Predefined options
Advanced Conditional Logic:
{
id: "experience",
question: "How many years of experience do you have?",
expectedAnswerType: "number",
conditionalActions: [
{
condition: {
field: "experience",
operator: "contains",
value: "senior"
},
action: "continue_flow",
nextQuestionId: "salary_discussion"
},
{
condition: {
field: "experience",
operator: "equals",
value: "none"
},
action: "end_call",
customMessage: "Thank you for your interest. We'll contact you about entry-level positions."
}
]
}Conditional Operators:
equals: Exact matchcontains: Partial matchnot_equals: Does not matchany_other: Fallback condition
LLM Agent Setup
OpenAI Configuration:
- API Credentials: Connect your OpenAI account
- Model Selection: Choose from GPT-3.5-turbo, GPT-4, etc.
- System Prompt: Define agent behavior and personality
- Temperature: Control response creativity (0-2)
- Max Tokens: Limit response length
System Prompt Example:
You are a helpful customer service representative for Acme Corp.
Keep responses conversational and brief (1-2 sentences max).
You can help with order status, product information, and general questions.
Always be polite and professional.Advanced Settings:
- Max Conversation Turns: Limit conversation length
- Conversation Timeout: Auto-end after specified minutes
- Allow User Hangup: Let users end call naturally
- Speech Recognition: Multiple language support
Voice Agent Features
Speech Processing:
- Real-time speech-to-text conversion
- Multiple language support
- Confidence scoring for responses
- Background noise filtering
Call Management:
- Automatic retry on unclear responses
- Keypad navigation (press keys to skip/navigate)
- Call recording and transcription
- Session persistence across interactions
Integration Capabilities:
- Save responses to workflow variables
- Integration with CRM systems
- Real-time call monitoring
- Analytics and reporting
Phone Number Formats
International Format
Always use E.164 format with country codes:
// United States
"+15551234567"
// United Kingdom
"+447911123456"
// Germany
"+4915123456789"
// Australia
"+61412345678"
// India
"+919876543210"Variable Usage
// Static numbers
to: "+15551234567"
// Dynamic numbers from variables
to: "{{userPhoneNumber}}"
to: "+1{{areaCode}}{{phoneNumber}}"
// Formatted variables
to: "{{formatPhoneNumber(rawPhone)}}"Message Examples
SMS Notifications
Order Notifications
From: +15551234567
To: {{customerPhone}}
Message:
🎉 Order Confirmed!
Hi {{customerName}},
Your order #{{orderNumber}} is confirmed.
Total: ${{orderTotal}}
Estimated delivery: {{deliveryDate}}
Track: {{trackingLink}}
Questions? Reply HELPAppointment Reminders
From: +15551234567
To: {{patientPhone}}
Message:
📅 Appointment Reminder
Hi {{patientName}},
Reminder: You have an appointment tomorrow at {{appointmentTime}} with Dr. {{doctorName}}.
Location: {{clinicAddress}}
To confirm, reply YES
To reschedule, reply RESCHEDULESystem Alerts
From: +15551234567
To: {{adminPhone}}
Message:
🚨 SYSTEM ALERT
Service: {{serviceName}}
Status: {{alertLevel}}
Time: {{timestamp}}
Error: {{errorMessage}}
Dashboard: {{dashboardLink}}Two-Factor Authentication
From: +15551234567
To: {{userPhone}}
Message:
🔐 Your verification code is: {{verificationCode}}
This code expires in 10 minutes.
Do not share this code with anyone.
Need help? Contact support.Marketing Messages
From: +15551234567
To: {{subscriberPhone}}
Message:
🎯 Special Offer for You!
Hi {{firstName}},
Get 25% off your next purchase with code: SAVE25
Valid until {{expiryDate}}
Shop now: {{storeLink}}
Reply STOP to opt outVoice Call Examples
Appointment Reminders
From: +15551234567
To: {{patientPhone}}
Message:
Hello {{patientName}}, this is a reminder that you have an appointment
tomorrow at {{appointmentTime}} with Dr. {{doctorName}} at our
{{clinicLocation}} office. Please arrive 15 minutes early for check-in.
If you need to reschedule, please call us at {{clinicPhone}}. Thank you.Order Status Updates
From: +15551234567
To: {{customerPhone}}
Message:
Hello {{customerName}}, your order number {{orderNumber}} has been
{{orderStatus}}. {{#if trackingNumber}}Your tracking number is
{{trackingNumber}}.{{/if}} Expected delivery is {{deliveryDate}}.
Thank you for choosing our service.Payment Reminders
From: +15551234567
To: {{customerPhone}}
Message:
Hello, this is a friendly reminder that your payment of {{paymentAmount}}
for account {{accountNumber}} is due on {{dueDate}}. You can pay online
at {{paymentLink}} or call us at {{supportNumber}}. Thank you.Voice Agent Examples
Customer Service Interview
Agent Type: JSON Questions
Questions:
- id: "issue_type"
question: "What type of issue are you experiencing today? You can say billing, technical, or general inquiry."
expectedAnswerType: "multiple_choice"
choices: ["billing", "technical", "general inquiry"]
conditionalActions:
- condition:
field: "issue_type"
operator: "contains"
value: "billing"
action: "continue_flow"
nextQuestionId: "billing_details"
- condition:
field: "issue_type"
operator: "contains"
value: "technical"
action: "continue_flow"
nextQuestionId: "technical_details"
- id: "billing_details"
question: "Please describe your billing concern in detail."
expectedAnswerType: "text"
- id: "technical_details"
question: "What technical problem are you experiencing?"
expectedAnswerType: "text"Job Interview Screening
Agent Type: JSON Questions
Questions:
- id: "name"
question: "Please state your full name."
expectedAnswerType: "text"
- id: "experience"
question: "How many years of relevant experience do you have?"
expectedAnswerType: "number"
conditionalActions:
- condition:
field: "experience"
operator: "contains"
value: "senior"
action: "continue_flow"
nextQuestionId: "leadership_experience"
- condition:
field: "experience"
operator: "equals"
value: "none"
action: "end_call"
customMessage: "Thank you for your interest. We'll review entry-level positions and contact you soon."
- id: "leadership_experience"
question: "Tell me about your leadership experience."
expectedAnswerType: "text"
- id: "availability"
question: "When would you be available to start?"
expectedAnswerType: "text"Customer Satisfaction Survey
Agent Type: JSON Questions
Questions:
- id: "satisfaction_rating"
question: "On a scale of 1 to 10, how would you rate your recent experience with our service?"
expectedAnswerType: "number"
conditionalActions:
- condition:
field: "satisfaction_rating"
operator: "contains"
value: "9"
action: "continue_flow"
nextQuestionId: "testimonial_request"
- condition:
field: "satisfaction_rating"
operator: "contains"
value: "1,2,3,4,5"
action: "continue_flow"
nextQuestionId: "improvement_feedback"
- id: "testimonial_request"
question: "Would you be willing to provide a testimonial about your experience?"
expectedAnswerType: "yes_no"
- id: "improvement_feedback"
question: "What could we have done better to improve your experience?"
expectedAnswerType: "text"LLM-Powered Customer Support
Agent Type: LLM Agent
OpenAI Configuration:
model: "gpt-4o-mini"
systemPrompt: |
You are a helpful customer service representative for TechCorp.
You can help with:
- Order status and tracking
- Product information and specifications
- Return and refund policies
- Technical support basics
- Account management
Keep responses conversational and under 2 sentences.
If you cannot help with something, politely direct them to human support.
Always be professional and empathetic.
temperature: 0.7
maxTokens: 150
maxConversationTurns: 10
allowUserHangup: trueAdvanced Features
Message Personalization
// Dynamic content based on user data
message: `Hi ${userData.firstName}!
Your ${orderData.productName} order is ${orderStatus}.
${orderStatus === 'shipped' ? 'Track here: ' + trackingUrl : 'Processing...'}`Conditional Messaging
// Different messages based on conditions
if (urgencyLevel === 'high') {
message = `🚨 URGENT: ${alertMessage}`;
} else if (urgencyLevel === 'medium') {
message = `⚠️ ALERT: ${alertMessage}`;
} else {
message = `ℹ️ INFO: ${alertMessage}`;
}Multi-Language Support
// Language-specific messages
const messages = {
en: "Your order has been shipped!",
es: "¡Su pedido ha sido enviado!",
fr: "Votre commande a été expédiée!",
de: "Ihre Bestellung wurde versendet!"
};
message = messages[userLanguage] || messages.en;URL Shortening
// Shorten URLs for SMS
longUrl = "https://example.com/very/long/url/with/parameters";
shortUrl = await shortenUrl(longUrl);
message = `Check your order: ${shortUrl}`;Integration Patterns
E-commerce Order Flow
1. Order Placed → Customer completes purchase
2. Order Processing → System processes order
3. SMS Confirmation → Send order confirmation
4. Shipping Update → Send tracking information
5. Delivery Confirmation → Confirm deliveryAppointment System
1. Appointment Booked → Customer schedules appointment
2. Confirmation SMS → Send appointment details
3. Reminder SMS → Send reminder 24h before
4. Check-in SMS → Send check-in instructions
5. Follow-up SMS → Send post-appointment surveySecurity Alerts
1. Security Event → Suspicious activity detected
2. Alert Generation → Create security alert
3. SMS Notification → Notify security team
4. Escalation → Send to management if critical
5. Resolution Update → Confirm threat resolvedCustomer Support
1. Support Ticket → Customer submits issue
2. Acknowledgment SMS → Confirm ticket receipt
3. Status Updates → Send progress updates
4. Resolution SMS → Notify when resolved
5. Feedback Request → Ask for satisfaction ratingCompliance and Regulations
SMS Compliance
Opt-in Requirements:
- Obtain explicit consent before sending promotional messages
- Provide clear opt-out instructions
- Honor opt-out requests immediately
- Maintain consent records
Content Guidelines:
- Include sender identification
- Provide opt-out instructions (STOP, UNSUBSCRIBE)
- Avoid spam-like content
- Respect sending time restrictions
Regional Regulations
United States (TCPA):
- Requires prior written consent for marketing messages
- Honor Do Not Call registry
- Provide clear opt-out mechanism
European Union (GDPR):
- Obtain explicit consent for data processing
- Provide data subject rights
- Implement proper data protection measures
Canada (CASL):
- Requires express consent for commercial messages
- Include sender identification and contact info
- Provide unsubscribe mechanism
Error Handling
Common issues and solutions:
Authentication Errors
"Authentication failed"
- Verify Account SID and Auth Token are correct
- Check if credentials are properly formatted
- Ensure account is in good standing with Twilio
Phone Number Errors
"Invalid phone number"
- Verify numbers are in E.164 format (+1234567890)
- Check country code is included
- Ensure number is valid and reachable
"From number not owned"
- Verify the from number is purchased from Twilio
- Check number is configured for SMS messaging
- Ensure number hasn't been released
Message Delivery Errors
"Message blocked"
- Check if recipient has opted out
- Verify content doesn't violate carrier policies
- Check for spam-like characteristics
"Insufficient funds"
- Check Twilio account balance
- Add funds to account
- Monitor usage and set up auto-recharge
Rate Limiting
"Rate limit exceeded"
- Twilio has rate limits per account and number
- Implement delays between messages
- Consider using multiple phone numbers
Best Practices
Message Design
- Clear Communication: Use concise, clear language
- Brand Consistency: Maintain consistent brand voice
- Call-to-Action: Include clear next steps
- Contact Info: Provide support contact information
Phone Number Management
- Dedicated Numbers: Use dedicated numbers for different purposes
- Local Numbers: Use local numbers when possible
- Shortcodes: Consider shortcodes for high-volume messaging
- Number Pooling: Distribute messages across multiple numbers
Compliance
- Consent Management: Maintain proper consent records
- Opt-out Handling: Honor opt-out requests immediately
- Content Review: Review messages for compliance
- Documentation: Keep records of messaging practices
Performance
- Delivery Monitoring: Track message delivery rates
- Error Handling: Implement robust error handling
- Retry Logic: Add retry mechanisms for failed messages
- Analytics: Monitor messaging performance and costs
Response Mapping
Map Twilio API responses to workflow variables:
Message Response
// Successful message send
{
"sid": "SM1234567890abcdef1234567890abcdef",
"date_created": "2024-01-15T10:30:00Z",
"date_updated": "2024-01-15T10:30:00Z",
"date_sent": "2024-01-15T10:30:01Z",
"account_sid": "AC1234567890abcdef1234567890abcdef",
"to": "+15559876543",
"from": "+15551234567",
"body": "Hello, this is a test message!",
"status": "sent",
"num_segments": "1",
"price": "-0.0075",
"currency": "USD"
}
// Variable mapping
sid → {{messageSid}}
status → {{messageStatus}}
date_sent → {{sentTimestamp}}
price → {{messageCost}}
to → {{recipientNumber}}Delivery Status
// Message status updates
status: "queued" // Message queued for sending
status: "sent" // Message sent to carrier
status: "delivered" // Message delivered to device
status: "failed" // Message failed to deliver
status: "undelivered" // Message could not be delivered
// Error codes for failed messages
error_code: 30001 // Queue overflow
error_code: 30003 // Unreachable destination
error_code: 30004 // Message blocked
error_code: 30005 // Unknown destinationTroubleshooting
Setup Issues
"Invalid credentials"
- Double-check Account SID and Auth Token
- Ensure credentials are from correct Twilio account
- Verify account is active and not suspended
"Phone number not available"
- Check if number is purchased and active
- Verify number has SMS capabilities
- Ensure number isn't in trial mode restrictions
Message Issues
"Message not delivered"
- Check recipient number format and validity
- Verify message content doesn't violate policies
- Check carrier-specific restrictions
"High message costs"
- Review pricing for destination countries
- Consider using local numbers when possible
- Monitor usage and optimize message content
Node Display
The Twilio node shows:
- SMS Configuration: Displays "Twilio SMS" service
- From Number: Shows configured sender number (orange tag)
- To Number: Shows recipient number (blue tag)
- Status: Configuration and sending status
Example Workflows
Customer Onboarding
1. Account Creation → New customer registers
2. Welcome SMS → Send welcome message
3. Verification → Send phone verification code
4. Tutorial Links → Send helpful resources
5. Support Info → Provide contact informationOrder Management
1. Order Received → Customer places order
2. Confirmation SMS → Send order confirmation
3. Processing Update → Notify when processing starts
4. Shipping Alert → Send tracking information
5. Delivery Confirmation → Confirm successful deliveryEmergency Notifications
1. Alert Trigger → Critical system event occurs
2. Severity Assessment → Determine notification priority
3. Contact List → Select appropriate recipients
4. SMS Broadcast → Send emergency notifications
5. Acknowledgment → Track receipt confirmationsMarketing Campaigns
1. Campaign Launch → Marketing campaign starts
2. Audience Segmentation → Target specific groups
3. Message Personalization → Customize content
4. SMS Delivery → Send promotional messages
5. Response Tracking → Monitor engagement and conversionsResponse Mapping
When a text is received by your Twilio phone number, you can parse it and use it in your workflow.
The response will be stored in the variable {{SMS reply}} and contains the text content of the SMS.
Voice Agent Best Practices
Conversation Design
- Keep questions clear and specific: Users should understand exactly what information you're seeking
- Provide response examples: Help users understand the expected format ("You can say yes, no, or maybe")
- Plan conversation flow: Map out all possible conversation paths before implementation
- Handle edge cases: Plan for unexpected responses, connection issues, and user hang-ups
- Use natural language: Voice interactions should feel conversational, not robotic
Technical Implementation
- Optimize response times: Keep OpenAI calls fast to avoid user confusion
- Implement proper error handling: Handle API failures gracefully with fallback responses
- Monitor token usage: Voice conversations can consume tokens quickly with longer interactions
- Test thoroughly: Use Twilio's test environment before deploying to production
- Log conversation data: Maintain detailed logs for debugging and improving agent performance
Security and Privacy
- Protect sensitive data: Never log or store sensitive information unnecessarily
- Validate user input: Sanitize and validate all user responses before processing
- Implement timeouts: End conversations after reasonable periods of inactivity
- Secure webhook endpoints: Ensure your webhook URLs are properly secured
- Monitor usage costs: Track both Twilio and OpenAI costs for voice agent interactions
Performance Optimization
- Use appropriate models: gpt-4o-mini is recommended for most voice applications
- Optimize system prompts: Keep prompts focused and concise to reduce token usage
- Implement caching: Cache common responses where appropriate
- Monitor response quality: Regularly review conversation logs to improve agent performance
- Set reasonable limits: Implement maximum conversation turns to control costs
Advanced Voice Agent Troubleshooting
Common Voice Agent Issues
OpenAI Integration Problems
- API Key errors: Verify your OpenAI API key is valid and has sufficient credits
- Model availability: Ensure the selected model (gpt-4o-mini, gpt-4, etc.) is available
- Token limits: Monitor token usage and implement appropriate limits
- Rate limiting: Handle OpenAI rate limits with proper retry logic
Session Management Issues
- Data persistence: Voice agent sessions are stored in memory and reset on server restart
- Session timeout: Implement appropriate timeout handling for long conversations
- State inconsistency: Ensure webhook responses maintain proper session state
- Memory leaks: Monitor server memory usage with multiple concurrent voice sessions
Conditional Logic Debugging
- Field matching: Ensure condition field names exactly match question IDs
- Operator usage: Use "equals" for exact matches, "contains" for partial text matching
- Value formatting: Text values are case-insensitive, numbers should be strings
- Flow validation: Test all conditional paths including edge cases
TwiML Generation Issues
- Invalid XML: Ensure webhook responses return properly formatted TwiML
- Response timing: Webhook responses must be returned quickly to avoid timeouts
- Say tag limits: Keep speech content under reasonable length limits
- Gather configuration: Properly configure input gathering for user responses
Debugging Strategies
Development Testing
- Use test credentials: Start with Twilio's test environment
- Enable detailed logging: Add comprehensive logging to webhook handlers
- Test incrementally: Build and test simple flows before adding complexity
- Monitor real-time: Use Twilio's webhook debugger for live testing
Production Monitoring
- Error tracking: Implement error tracking for webhook failures
- Performance monitoring: Track response times and conversation success rates
- Cost monitoring: Monitor both Twilio and OpenAI usage and costs
- User experience: Track conversation completion rates and user satisfaction
Common Error Patterns
- Webhook timeouts: Usually caused by slow OpenAI API responses
- Invalid TwiML: Often due to malformed XML in webhook responses
- Session not found: Indicates server restart or session timeout
- Conditional logic failures: Usually field name mismatches or incorrect operators
Performance Optimization Tips
Reducing Latency
- Optimize OpenAI calls: Use streaming responses where possible
- Cache common responses: Store frequently used responses
- Minimize processing: Keep webhook logic simple and fast
- Use CDN: Serve static TwiML responses from CDN when possible
Cost Management
- Model selection: Use gpt-4o-mini for most voice applications
- Token optimization: Craft concise system prompts and user inputs
- Conversation limits: Set maximum turns to control costs
- Usage monitoring: Track and alert on high usage patterns
Scalability Considerations
- Stateless design: Design webhooks to be stateless where possible
- Load balancing: Distribute voice agent traffic across multiple servers
- Database optimization: Use efficient storage for conversation logs
- Rate limiting: Implement proper rate limiting for production deployments