Twilio Integration
Guide for integrating Twilio Voice with Conversational AI.
Overview
This guide explains how to set up a voice call integration between Twilio and Conversational AI. The integration allows you to handle incoming phone calls and connect Conversational AI agent to phone calls directly.
Prerequisites
- ElevenLabs API key
- Twilio account & phone number
- Python 3.7+
- ngrok for local development
Elevenlabs Agent Configurations
We need to make sure audio encoding for Output and Input is set to “μ-law 8000 Hz”. This is the audio encoding needed for Twilio Voice API, default audio encoding is PCM 16000 Hz
Set TTS Output Format
Navigate to your agent -> Go to Voice Section -> Select “μ-law 8000 Hz”
Set Input Audio Format
Navigate to your agent -> Go to Advanced Section -> Select “μ-law 8000 Hz”
Project Setup
First, install the required dependencies:
Set up your environment variables by creating a .env
file:
Create the main server file (main.py):
Create the Twilio audio interface (twilio_audio_interface.py):
Setting Up Twilio
Start your local server:
Create a public URL using ngrok: shell ngrok http 8003
Note down the
HTTPS URL provided by ngrok (e.g., https://your-ngrok-url.ngrok.app)
Configure your Twilio phone number:
- Go to the Twilio Console
- Navigate to Phone Numbers → Manage → Active numbers
- Select your phone number
- Under “Voice Configuration”, set the webhook for incoming calls to:
https://your-ngrok-url.ngrok.app/incoming-call-eleven
- Make sure the HTTP method is set to POST
Testing the Integration
- Call your Twilio phone number
- You should see console output indicating:
- WebSocket connection established
- Stream SID assigned
- Conversation session started
- Speak into the phone - you should see transcripts of your speech and the agent’s responses in the console
Troubleshooting
Common Issues
-
WebSocket Connection Fails
- Verify your ngrok URL is correct in the Twilio webhook settings
- Check that your server is running and accessible
-
No Audio Output
- Ensure your ElevenLabs API key is correct
- Verify the AGENT_ID is properly configured
-
Audio Quality Issues
- The integration uses mulaw 8kHz format as required by Twilio
- Check your network connectivity and latency
Debug Logging
To enable detailed logging, add these lines to your main.py:
Security Considerations
- Always use environment variables for sensitive information
- Implement proper authentication for your endpoints
- Use HTTPS for all communications
- Regularly rotate API keys
- Monitor usage to prevent abuse
Was this page helpful?